xref: /titanic_44/usr/src/uts/common/inet/ip/ip.c (revision 1cb875ae88fb9463b368e725c2444776595895cb)
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 2009 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 <rpc/pmap_prot.h>
125 #include <sys/squeue_impl.h>
126 #include <inet/ip_arp.h>
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
131  * IP_SQUEUE_ENTER: SQ_PROCESS
132  * IP_SQUEUE_FILL: SQ_FILL
133  */
134 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
135 
136 int ip_squeue_flag;
137 
138 /*
139  * Setable in /etc/system
140  */
141 int ip_poll_normal_ms = 100;
142 int ip_poll_normal_ticks = 0;
143 int ip_modclose_ackwait_ms = 3000;
144 
145 /*
146  * It would be nice to have these present only in DEBUG systems, but the
147  * current design of the global symbol checking logic requires them to be
148  * unconditionally present.
149  */
150 uint_t ip_thread_data;			/* TSD key for debug support */
151 krwlock_t ip_thread_rwlock;
152 list_t	ip_thread_list;
153 
154 /*
155  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
156  */
157 
158 struct listptr_s {
159 	mblk_t	*lp_head;	/* pointer to the head of the list */
160 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
161 };
162 
163 typedef struct listptr_s listptr_t;
164 
165 /*
166  * This is used by ip_snmp_get_mib2_ip_route_media and
167  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
168  */
169 typedef struct iproutedata_s {
170 	uint_t		ird_idx;
171 	uint_t		ird_flags;	/* see below */
172 	listptr_t	ird_route;	/* ipRouteEntryTable */
173 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
174 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
175 } iproutedata_t;
176 
177 /* Include ire_testhidden and IRE_IF_CLONE routes */
178 #define	IRD_REPORT_ALL	0x01
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
199     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
200     void *args) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide SPI.
204  */
205 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
206     void *) = NULL;
207 
208 /*
209  * Hook function to verify if the SPI is already utlized.
210  */
211 
212 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
213 
214 /*
215  * Hook function to delete the SPI from the cluster wide repository.
216  */
217 
218 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
219 
220 /*
221  * Hook function to inform the cluster when packet received on an IDLE SA
222  */
223 
224 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
225     in6_addr_t, in6_addr_t, void *) = NULL;
226 
227 /*
228  * Synchronization notes:
229  *
230  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
231  * MT level protection given by STREAMS. IP uses a combination of its own
232  * internal serialization mechanism and standard Solaris locking techniques.
233  * The internal serialization is per phyint.  This is used to serialize
234  * plumbing operations, IPMP operations, most set ioctls, etc.
235  *
236  * Plumbing is a long sequence of operations involving message
237  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
238  * involved in plumbing operations. A natural model is to serialize these
239  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
240  * parallel without any interference. But various set ioctls on hme0 are best
241  * serialized, along with IPMP operations and processing of DLPI control
242  * messages received from drivers on a per phyint basis. This serialization is
243  * provided by the ipsq_t and primitives operating on this. Details can
244  * be found in ip_if.c above the core primitives operating on ipsq_t.
245  *
246  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
247  * Simiarly lookup of an ire by a thread also returns a refheld ire.
248  * In addition ipif's and ill's referenced by the ire are also indirectly
249  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
250  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
251  * address of an ipif has to go through the ipsq_t. This ensures that only
252  * one such exclusive operation proceeds at any time on the ipif. It then
253  * waits for all refcnts
254  * associated with this ipif to come down to zero. The address is changed
255  * only after the ipif has been quiesced. Then the ipif is brought up again.
256  * More details are described above the comment in ip_sioctl_flags.
257  *
258  * Packet processing is based mostly on IREs and are fully multi-threaded
259  * using standard Solaris MT techniques.
260  *
261  * There are explicit locks in IP to handle:
262  * - The ip_g_head list maintained by mi_open_link() and friends.
263  *
264  * - The reassembly data structures (one lock per hash bucket)
265  *
266  * - conn_lock is meant to protect conn_t fields. The fields actually
267  *   protected by conn_lock are documented in the conn_t definition.
268  *
269  * - ire_lock to protect some of the fields of the ire, IRE tables
270  *   (one lock per hash bucket). Refer to ip_ire.c for details.
271  *
272  * - ndp_g_lock and ncec_lock for protecting NCEs.
273  *
274  * - ill_lock protects fields of the ill and ipif. Details in ip.h
275  *
276  * - ill_g_lock: This is a global reader/writer lock. Protects the following
277  *	* The AVL tree based global multi list of all ills.
278  *	* The linked list of all ipifs of an ill
279  *	* The <ipsq-xop> mapping
280  *	* <ill-phyint> association
281  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
282  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
283  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
284  *   writer for the actual duration of the insertion/deletion/change.
285  *
286  * - ill_lock:  This is a per ill mutex.
287  *   It protects some members of the ill_t struct; see ip.h for details.
288  *   It also protects the <ill-phyint> assoc.
289  *   It also protects the list of ipifs hanging off the ill.
290  *
291  * - ipsq_lock: This is a per ipsq_t mutex lock.
292  *   This protects some members of the ipsq_t struct; see ip.h for details.
293  *   It also protects the <ipsq-ipxop> mapping
294  *
295  * - ipx_lock: This is a per ipxop_t mutex lock.
296  *   This protects some members of the ipxop_t struct; see ip.h for details.
297  *
298  * - phyint_lock: This is a per phyint mutex lock. Protects just the
299  *   phyint_flags
300  *
301  * - ip_g_nd_lock: This is a global reader/writer lock.
302  *   Any call to nd_load to load a new parameter to the ND table must hold the
303  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
304  *   as reader.
305  *
306  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
307  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
308  *   uniqueness check also done atomically.
309  *
310  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
311  *   group list linked by ill_usesrc_grp_next. It also protects the
312  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
313  *   group is being added or deleted.  This lock is taken as a reader when
314  *   walking the list/group(eg: to get the number of members in a usesrc group).
315  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
316  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
317  *   example, it is not necessary to take this lock in the initial portion
318  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
319  *   operations are executed exclusively and that ensures that the "usesrc
320  *   group state" cannot change. The "usesrc group state" change can happen
321  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
322  *
323  * Changing <ill-phyint>, <ipsq-xop> assocications:
324  *
325  * To change the <ill-phyint> association, the ill_g_lock must be held
326  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
327  * must be held.
328  *
329  * To change the <ipsq-xop> association, the ill_g_lock must be held as
330  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
331  * This is only done when ills are added or removed from IPMP groups.
332  *
333  * To add or delete an ipif from the list of ipifs hanging off the ill,
334  * ill_g_lock (writer) and ill_lock must be held and the thread must be
335  * a writer on the associated ipsq.
336  *
337  * To add or delete an ill to the system, the ill_g_lock must be held as
338  * writer and the thread must be a writer on the associated ipsq.
339  *
340  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
341  * must be a writer on the associated ipsq.
342  *
343  * Lock hierarchy
344  *
345  * Some lock hierarchy scenarios are listed below.
346  *
347  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
348  * ill_g_lock -> ill_lock(s) -> phyint_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
350  * ill_g_lock -> ip_addr_avail_lock
351  * conn_lock -> irb_lock -> ill_lock -> ire_lock
352  * ill_g_lock -> ip_g_nd_lock
353  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
354  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
355  * arl_lock -> ill_lock
356  * ips_ire_dep_lock -> irb_lock
357  *
358  * When more than 1 ill lock is needed to be held, all ill lock addresses
359  * are sorted on address and locked starting from highest addressed lock
360  * downward.
361  *
362  * Multicast scenarios
363  * ips_ill_g_lock -> ill_mcast_lock
364  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
365  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
366  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
367  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
368  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
369  *
370  * IPsec scenarios
371  *
372  * ipsa_lock -> ill_g_lock -> ill_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
417  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
418  *
419  * IPsec notes :
420  *
421  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
422  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
423  * ip_xmit_attr_t has the
424  * information used by the IPsec code for applying the right level of
425  * protection. The information initialized by IP in the ip_xmit_attr_t
426  * is determined by the per-socket policy or global policy in the system.
427  * For inbound datagrams, the ip_recv_attr_t
428  * starts out with nothing in it. It gets filled
429  * with the right information if it goes through the AH/ESP code, which
430  * happens if the incoming packet is secure. The information initialized
431  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
432  * the policy requirements needed by per-socket policy or global policy
433  * is met or not.
434  *
435  * For fully connected sockets i.e dst, src [addr, port] is known,
436  * conn_policy_cached is set indicating that policy has been cached.
437  * conn_in_enforce_policy may or may not be set depending on whether
438  * there is a global policy match or per-socket policy match.
439  * Policy inheriting happpens in ip_policy_set once the destination is known.
440  * Once the right policy is set on the conn_t, policy cannot change for
441  * this socket. This makes life simpler for TCP (UDP ?) where
442  * re-transmissions go out with the same policy. For symmetry, policy
443  * is cached for fully connected UDP sockets also. Thus if policy is cached,
444  * it also implies that policy is latched i.e policy cannot change
445  * on these sockets. As we have the right policy on the conn, we don't
446  * have to lookup global policy for every outbound and inbound datagram
447  * and thus serving as an optimization. Note that a global policy change
448  * does not affect fully connected sockets if they have policy. If fully
449  * connected sockets did not have any policy associated with it, global
450  * policy change may affect them.
451  *
452  * IP Flow control notes:
453  * ---------------------
454  * Non-TCP streams are flow controlled by IP. The way this is accomplished
455  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
456  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
457  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
458  * functions.
459  *
460  * Per Tx ring udp flow control:
461  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
462  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
463  *
464  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
465  * To achieve best performance, outgoing traffic need to be fanned out among
466  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
467  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
468  * the address of connp as fanout hint to mac_tx(). Under flow controlled
469  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
470  * cookie points to a specific Tx ring that is blocked. The cookie is used to
471  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
472  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
473  * connp's. The drain list is not a single list but a configurable number of
474  * lists.
475  *
476  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
477  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
478  * which is equal to 128. This array in turn contains a pointer to idl_t[],
479  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
480  * list will point to the list of connp's that are flow controlled.
481  *
482  *                      ---------------   -------   -------   -------
483  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
484  *                   |  ---------------   -------   -------   -------
485  *                   |  ---------------   -------   -------   -------
486  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
487  * ----------------  |  ---------------   -------   -------   -------
488  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
489  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
490  *                   |  ---------------   -------   -------   -------
491  *                   .        .              .         .         .
492  *                   |  ---------------   -------   -------   -------
493  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
494  *                      ---------------   -------   -------   -------
495  *                      ---------------   -------   -------   -------
496  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
497  *                   |  ---------------   -------   -------   -------
498  *                   |  ---------------   -------   -------   -------
499  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
500  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
501  * ----------------  |        .              .         .         .
502  *                   |  ---------------   -------   -------   -------
503  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
504  *                      ---------------   -------   -------   -------
505  *     .....
506  * ----------------
507  * |idl_tx_list[n]|-> ...
508  * ----------------
509  *
510  * When mac_tx() returns a cookie, the cookie is used to hash into a
511  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
512  * called passing idl_tx_list. The connp gets inserted in a drain list
513  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
514  * the sockets (non stream based) and sets QFULL condition on the conn_wq
515  * of streams sockets, or the su_txqfull for non-streams sockets.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each conn in the drain list and calls conn_idl_remove
524  * for the conn to clear the qfull condition for the conn, as well as to
525  * remove the conn from the idl list. In addition, streams based sockets
526  * will have the conn_wq enabled, causing ip_wsrv to run for the
527  * conn. ip_wsrv drains the queued messages, and removes the conn from the
528  * drain list, if all messages were drained. It also notifies the
529  * conn_upcalls for the conn to signal that flow-control has opened up.
530  *
531  * In reality the drain list is not a single list, but a configurable number
532  * of lists. conn_walk_drain() in the IP module, notifies the conn_upcalls for
533  * each conn in the list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * from the protocol layer when conn_ip_output returns EWOULDBLOCK.
536  * (as opposed to from ip_wsrv context for STREAMS
537  * case -- see below). The synchronization between drain insertion and flow
538  * control wakeup is handled by using idl_txl->txl_lock.
539  *
540  * Flow control using STREAMS:
541  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
542  * is used. On the send side, if the packet cannot be sent down to the
543  * driver by IP, because of a canput failure, ip_xmit drops the packet
544  * and returns EWOULDBLOCK to the caller, who may then invoke
545  * ixa_check_drain_insert to insert the conn on the 0'th drain list.
546  * When ip_wsrv runs on the ill_wq because flow control has been relieved, the
547  * blocked conns in the * 0'th drain list is drained as with the
548  * non-STREAMS case.
549  *
550  * In both the STREAMS and non-STREAMS case, the sockfs upcall to set
551  * qfull is done when the conn is inserted into the drain list
552  * (conn_drain_insert()) and cleared when the conn is removed from the drain
553  * list (conn_idl_remove()).
554  *
555  * IPQOS notes:
556  *
557  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
558  * and IPQoS modules. IPPF includes hooks in IP at different control points
559  * (callout positions) which direct packets to IPQoS modules for policy
560  * processing. Policies, if present, are global.
561  *
562  * The callout positions are located in the following paths:
563  *		o local_in (packets destined for this host)
564  *		o local_out (packets orginating from this host )
565  *		o fwd_in  (packets forwarded by this m/c - inbound)
566  *		o fwd_out (packets forwarded by this m/c - outbound)
567  * Hooks at these callout points can be enabled/disabled using the ndd variable
568  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
569  * By default all the callout positions are enabled.
570  *
571  * Outbound (local_out)
572  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
573  *
574  * Inbound (local_in)
575  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
576  *
577  * Forwarding (in and out)
578  * Hooks are placed in ire_recv_forward_v4/v6.
579  *
580  * IP Policy Framework processing (IPPF processing)
581  * Policy processing for a packet is initiated by ip_process, which ascertains
582  * that the classifier (ipgpc) is loaded and configured, failing which the
583  * packet resumes normal processing in IP. If the clasifier is present, the
584  * packet is acted upon by one or more IPQoS modules (action instances), per
585  * filters configured in ipgpc and resumes normal IP processing thereafter.
586  * An action instance can drop a packet in course of its processing.
587  *
588  * Zones notes:
589  *
590  * The partitioning rules for networking are as follows:
591  * 1) Packets coming from a zone must have a source address belonging to that
592  * zone.
593  * 2) Packets coming from a zone can only be sent on a physical interface on
594  * which the zone has an IP address.
595  * 3) Between two zones on the same machine, packet delivery is only allowed if
596  * there's a matching route for the destination and zone in the forwarding
597  * table.
598  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
599  * different zones can bind to the same port with the wildcard address
600  * (INADDR_ANY).
601  *
602  * The granularity of interface partitioning is at the logical interface level.
603  * Therefore, every zone has its own IP addresses, and incoming packets can be
604  * attributed to a zone unambiguously. A logical interface is placed into a zone
605  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
606  * structure. Rule (1) is implemented by modifying the source address selection
607  * algorithm so that the list of eligible addresses is filtered based on the
608  * sending process zone.
609  *
610  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
611  * across all zones, depending on their type. Here is the break-up:
612  *
613  * IRE type				Shared/exclusive
614  * --------				----------------
615  * IRE_BROADCAST			Exclusive
616  * IRE_DEFAULT (default routes)		Shared (*)
617  * IRE_LOCAL				Exclusive (x)
618  * IRE_LOOPBACK				Exclusive
619  * IRE_PREFIX (net routes)		Shared (*)
620  * IRE_IF_NORESOLVER (interface routes)	Exclusive
621  * IRE_IF_RESOLVER (interface routes)	Exclusive
622  * IRE_IF_CLONE (interface routes)	Exclusive
623  * IRE_HOST (host routes)		Shared (*)
624  *
625  * (*) A zone can only use a default or off-subnet route if the gateway is
626  * directly reachable from the zone, that is, if the gateway's address matches
627  * one of the zone's logical interfaces.
628  *
629  * (x) IRE_LOCAL are handled a bit differently.
630  * When ip_restrict_interzone_loopback is set (the default),
631  * ire_route_recursive restricts loopback using an IRE_LOCAL
632  * between zone to the case when L2 would have conceptually looped the packet
633  * back, i.e. the loopback which is required since neither Ethernet drivers
634  * nor Ethernet hardware loops them back. This is the case when the normal
635  * routes (ignoring IREs with different zoneids) would send out the packet on
636  * the same ill as the ill with which is IRE_LOCAL is associated.
637  *
638  * Multiple zones can share a common broadcast address; typically all zones
639  * share the 255.255.255.255 address. Incoming as well as locally originated
640  * broadcast packets must be dispatched to all the zones on the broadcast
641  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
642  * since some zones may not be on the 10.16.72/24 network. To handle this, each
643  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
644  * sent to every zone that has an IRE_BROADCAST entry for the destination
645  * address on the input ill, see ip_input_broadcast().
646  *
647  * Applications in different zones can join the same multicast group address.
648  * The same logic applies for multicast as for broadcast. ip_input_multicast
649  * dispatches packets to all zones that have members on the physical interface.
650  */
651 
652 /*
653  * Squeue Fanout flags:
654  *	0: No fanout.
655  *	1: Fanout across all squeues
656  */
657 boolean_t	ip_squeue_fanout = 0;
658 
659 /*
660  * Maximum dups allowed per packet.
661  */
662 uint_t ip_max_frag_dups = 10;
663 
664 /* RFC 1122 Conformance */
665 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
666 
667 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
668 
669 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
670 		    cred_t *credp, boolean_t isv6);
671 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
672 
673 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
674 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
675 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
676     ip_recv_attr_t *);
677 static void	icmp_options_update(ipha_t *);
678 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
679 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
680 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
681 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
682     ip_recv_attr_t *);
683 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
684 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
685     ip_recv_attr_t *);
686 
687 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
688 char		*ip_dot_addr(ipaddr_t, char *);
689 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
690 int		ip_close(queue_t *, int);
691 static char	*ip_dot_saddr(uchar_t *, char *);
692 static void	ip_lrput(queue_t *, mblk_t *);
693 ipaddr_t	ip_net_mask(ipaddr_t);
694 char		*ip_nv_lookup(nv_t *, int);
695 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
696 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
697 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
698     ipndp_t *, size_t);
699 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
700 void	ip_rput(queue_t *, mblk_t *);
701 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
702 		    void *dummy_arg);
703 int		ip_snmp_get(queue_t *, mblk_t *, int);
704 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
705 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
706 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
707 		    ip_stack_t *);
708 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
709 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
710 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
711 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
712 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
713 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
714 		    ip_stack_t *ipst);
715 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
716 		    ip_stack_t *ipst);
717 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
718 		    ip_stack_t *ipst);
719 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
720 		    ip_stack_t *ipst);
721 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
722 		    ip_stack_t *ipst);
723 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
724 		    ip_stack_t *ipst);
725 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
726 		    ip_stack_t *ipst);
727 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
728 		    ip_stack_t *ipst);
729 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
730 		    ip_stack_t *ipst);
731 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
732 		    ip_stack_t *ipst);
733 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
734 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
735 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
736 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
737 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
738 
739 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
740 		    mblk_t *);
741 
742 static void	conn_drain_init(ip_stack_t *);
743 static void	conn_drain_fini(ip_stack_t *);
744 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
745 
746 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
747 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
748 
749 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
750 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
751 static void	ip_stack_fini(netstackid_t stackid, void *arg);
752 
753 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
754 
755 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
756     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
757     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
758     const in6_addr_t *);
759 
760 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
761 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
762     caddr_t, cred_t *);
763 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
764     caddr_t cp, cred_t *cr);
765 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
766     cred_t *);
767 static int	ip_squeue_switch(int);
768 
769 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
770 static void	ip_kstat_fini(netstackid_t, kstat_t *);
771 static int	ip_kstat_update(kstat_t *kp, int rw);
772 static void	*icmp_kstat_init(netstackid_t);
773 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
774 static int	icmp_kstat_update(kstat_t *kp, int rw);
775 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
776 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
777 
778 static void	ipobs_init(ip_stack_t *);
779 static void	ipobs_fini(ip_stack_t *);
780 
781 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
782 
783 /* How long, in seconds, we allow frags to hang around. */
784 #define	IP_FRAG_TIMEOUT		15
785 #define	IPV6_FRAG_TIMEOUT	60
786 
787 static long ip_rput_pullups;
788 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
789 
790 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
791 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
792 
793 int	ip_debug;
794 
795 /*
796  * Multirouting/CGTP stuff
797  */
798 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
799 
800 /*
801  * Named Dispatch Parameter Table.
802  * All of these are alterable, within the min/max values given, at run time.
803  */
804 static ipparam_t	lcl_param_arr[] = {
805 	/* min	max	value	name */
806 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
807 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
808 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
809 	{  0,	1,	0,	"ip_respond_to_timestamp"},
810 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
811 	{  0,	1,	1,	"ip_send_redirects"},
812 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
813 	{  0,	10,	0,	"ip_mrtdebug"},
814 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
815 	{  1,	8,	3,	"ip_nce_reclaim_fraction" },
816 	{  1,	8,	3,	"ip_dce_reclaim_fraction" },
817 	{  1,	255,	255,	"ip_def_ttl" },
818 	{  0,	1,	0,	"ip_forward_src_routed"},
819 	{  0,	256,	32,	"ip_wroff_extra" },
820 	{  2, 999999999, 60*20, "ip_pathmtu_interval" },	/* In seconds */
821 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
822 	{  0,	1,	1,	"ip_path_mtu_discovery" },
823 	{ 68,	65535,	576,	"ip_pmtu_min" },
824 	{  0,	1,	0,	"ip_ignore_redirect" },
825 	{  0,	1,	0,	"ip_arp_icmp_error" },
826 	{  1,	254,	1,	"ip_broadcast_ttl" },
827 	{  0,	99999,	100,	"ip_icmp_err_interval" },
828 	{  1,	99999,	10,	"ip_icmp_err_burst" },
829 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
830 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
831 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
832 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
833 	{  0,	1,	1,	"icmp_accept_clear_messages" },
834 	{  0,	1,	1,	"igmp_accept_clear_messages" },
835 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
836 				"ip_ndp_delay_first_probe_time"},
837 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
838 				"ip_ndp_max_unicast_solicit"},
839 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
840 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
841 	{  0,	1,	0,	"ip6_forward_src_routed"},
842 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
843 	{  0,	1,	1,	"ip6_send_redirects"},
844 	{  0,	1,	0,	"ip6_ignore_redirect" },
845 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
846 
847 	{  0,	2,	2,	"ip_src_check" },
848 
849 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
850 
851 	{  0,	1,	1,	"pim_accept_clear_messages" },
852 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
853 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
854 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
855 	{  0,	15,	0,	"ip_policy_mask" },
856 	{  0,	2,	2,	"ip_ecmp_behavior" },
857 	{  0,	255,	1,	"ip_multirt_ttl" },
858 	{  0,	3600,	60,	"ip_ire_badcnt_lifetime" },	/* In seconds */
859 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
860 	{  0,	1000,	1,	"ip_max_temp_defend" },
861 	/*
862 	 * when a conflict of an active address is detected,
863 	 * defend up to ip_max_defend times, within any
864 	 * ip_defend_interval span.
865 	 */
866 	{  0,	1000,	3,	"ip_max_defend" },
867 	{  0,	999999,	30,	"ip_defend_interval" },
868 	{  0,	3600000, 300000, "ip_dup_recovery" },
869 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
870 	{  0,	1,	1,	"ip_lso_outbound" },
871 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
872 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
873 #ifdef DEBUG
874 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
875 #else
876 	{  0,	0,	0,	"" },
877 #endif
878 	/* delay before sending first probe: */
879 	{  0,	20000,	1000,	"arp_probe_delay" },
880 	{  0,	20000,	100,	"arp_fastprobe_delay" },
881 	/* interval at which DAD probes are sent: */
882 	{ 10,	20000,	1500,	"arp_probe_interval" },
883 	{ 10,	20000,	150,	"arp_fastprobe_interval" },
884 	/* setting probe count to 0 will disable ARP probing for DAD. */
885 	{  0,	20,	3,	"arp_probe_count" },
886 	{  0,	20,	3,	"arp_fastprobe_count" },
887 
888 	{  0,	3600000, 15000,	"ipv4_dad_announce_interval"},
889 	{  0,	3600000, 15000,	"ipv6_dad_announce_interval"},
890 	/*
891 	 * Rate limiting parameters for DAD defense used in
892 	 * ill_defend_rate_limit():
893 	 * defend_rate : pkts/hour permitted
894 	 * defend_interval : time that can elapse before we send out a
895 	 *			DAD defense.
896 	 * defend_period: denominator for defend_rate (in seconds).
897 	 */
898 	{  0,	3600000, 300000,	"arp_defend_interval"},
899 	{  0,	20000, 100,		"arp_defend_rate"},
900 	{  0,	3600000, 300000,	"ndp_defend_interval"},
901 	{  0,	20000, 100,		"ndp_defend_rate"},
902 	{  5,	86400,	3600,		"arp_defend_period"},
903 	{  5,	86400,	3600,		"ndp_defend_period"},
904 	{  0,	1,	1,		"ipv4_icmp_return_pmtu" },
905 	{  0,	1,	1,		"ipv6_icmp_return_pmtu" },
906 	/*
907 	 * publish count/interval values used to announce local addresses
908 	 * for IPv4, IPv6.
909 	 */
910 	{  1,	20,	5,	"ip_arp_publish_count" },
911 	{  1000, 20000,	2000,	"ip_arp_publish_interval" },
912 };
913 
914 /*
915  * Extended NDP table
916  * The addresses for the first two are filled in to be ips_ip_g_forward
917  * and ips_ipv6_forward at init time.
918  */
919 static ipndp_t	lcl_ndp_arr[] = {
920 	/* getf			setf		data			name */
921 #define	IPNDP_IP_FORWARDING_OFFSET	0
922 	{  ip_param_generic_get,	ip_forward_set,	NULL,
923 	    "ip_forwarding" },
924 #define	IPNDP_IP6_FORWARDING_OFFSET	1
925 	{  ip_param_generic_get,	ip_forward_set,	NULL,
926 	    "ip6_forwarding" },
927 	{ ip_param_generic_get, ip_input_proc_set,
928 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
929 	{ ip_param_generic_get, ip_int_set,
930 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
931 #define	IPNDP_CGTP_FILTER_OFFSET	4
932 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
933 	    "ip_cgtp_filter" },
934 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
935 	    "ip_debug" },
936 };
937 
938 /*
939  * Table of IP ioctls encoding the various properties of the ioctl and
940  * indexed based on the last byte of the ioctl command. Occasionally there
941  * is a clash, and there is more than 1 ioctl with the same last byte.
942  * In such a case 1 ioctl is encoded in the ndx table and the remaining
943  * ioctls are encoded in the misc table. An entry in the ndx table is
944  * retrieved by indexing on the last byte of the ioctl command and comparing
945  * the ioctl command with the value in the ndx table. In the event of a
946  * mismatch the misc table is then searched sequentially for the desired
947  * ioctl command.
948  *
949  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
950  */
951 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
952 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 
963 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
964 			MISC_CMD, ip_siocaddrt, NULL },
965 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
966 			MISC_CMD, ip_siocdelrt, NULL },
967 
968 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
969 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
970 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
971 			IF_CMD, ip_sioctl_get_addr, NULL },
972 
973 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
974 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
975 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
976 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
977 
978 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
979 			IPI_PRIV | IPI_WR,
980 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
981 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
982 			IPI_MODOK | IPI_GET_CMD,
983 			IF_CMD, ip_sioctl_get_flags, NULL },
984 
985 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
986 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
987 
988 	/* copyin size cannot be coded for SIOCGIFCONF */
989 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
990 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
991 
992 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
993 			IF_CMD, ip_sioctl_mtu, NULL },
994 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
995 			IF_CMD, ip_sioctl_get_mtu, NULL },
996 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
997 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
998 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
999 			IF_CMD, ip_sioctl_brdaddr, NULL },
1000 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1001 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1002 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1003 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1004 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1005 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1006 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1007 			IF_CMD, ip_sioctl_metric, NULL },
1008 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1009 
1010 	/* See 166-168 below for extended SIOC*XARP ioctls */
1011 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1014 			ARP_CMD, ip_sioctl_arp, NULL },
1015 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1016 			ARP_CMD, ip_sioctl_arp, NULL },
1017 
1018 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 
1040 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1041 			MISC_CMD, if_unitsel, if_unitsel_restart },
1042 
1043 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 
1062 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1063 			IPI_PRIV | IPI_WR | IPI_MODOK,
1064 			IF_CMD, ip_sioctl_sifname, NULL },
1065 
1066 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 
1080 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1081 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1082 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1083 			IF_CMD, ip_sioctl_get_muxid, NULL },
1084 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1085 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1086 
1087 	/* Both if and lif variants share same func */
1088 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1089 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1090 	/* Both if and lif variants share same func */
1091 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1092 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1093 
1094 	/* copyin size cannot be coded for SIOCGIFCONF */
1095 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1096 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1097 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 
1115 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1116 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1117 			ip_sioctl_removeif_restart },
1118 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1119 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1120 			LIF_CMD, ip_sioctl_addif, NULL },
1121 #define	SIOCLIFADDR_NDX 112
1122 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1123 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1124 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1125 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1126 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1127 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1128 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1129 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1130 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1131 			IPI_PRIV | IPI_WR,
1132 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1133 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1134 			IPI_GET_CMD | IPI_MODOK,
1135 			LIF_CMD, ip_sioctl_get_flags, NULL },
1136 
1137 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 
1140 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1141 			ip_sioctl_get_lifconf, NULL },
1142 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1143 			LIF_CMD, ip_sioctl_mtu, NULL },
1144 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1145 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1146 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1147 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1148 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1149 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1150 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1151 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1152 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1153 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1154 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1155 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1156 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1157 			LIF_CMD, ip_sioctl_metric, NULL },
1158 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1159 			IPI_PRIV | IPI_WR | IPI_MODOK,
1160 			LIF_CMD, ip_sioctl_slifname,
1161 			ip_sioctl_slifname_restart },
1162 
1163 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1164 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1165 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1166 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1167 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1168 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1169 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1170 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1171 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1172 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1173 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1174 			LIF_CMD, ip_sioctl_token, NULL },
1175 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1176 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1177 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1178 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1179 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1180 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1181 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1182 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1183 
1184 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1185 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1186 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1187 			LIF_CMD, ip_siocdelndp_v6, NULL },
1188 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1189 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1190 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1191 			LIF_CMD, ip_siocsetndp_v6, NULL },
1192 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1193 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1194 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1195 			MISC_CMD, ip_sioctl_tonlink, NULL },
1196 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1197 			MISC_CMD, ip_sioctl_tmysite, NULL },
1198 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1201 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1202 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1203 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1204 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1205 
1206 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 
1208 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1209 			LIF_CMD, ip_sioctl_get_binding, NULL },
1210 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1211 			IPI_PRIV | IPI_WR,
1212 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1213 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1214 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1215 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1216 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1217 
1218 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1219 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 
1223 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 
1225 	/* These are handled in ip_sioctl_copyin_setup itself */
1226 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1227 			MISC_CMD, NULL, NULL },
1228 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1229 			MISC_CMD, NULL, NULL },
1230 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1231 
1232 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1233 			ip_sioctl_get_lifconf, NULL },
1234 
1235 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1236 			XARP_CMD, ip_sioctl_arp, NULL },
1237 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1238 			XARP_CMD, ip_sioctl_arp, NULL },
1239 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1240 			XARP_CMD, ip_sioctl_arp, NULL },
1241 
1242 	/* SIOCPOPSOCKFS is not handled by IP */
1243 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1244 
1245 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1246 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1247 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1248 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1249 			ip_sioctl_slifzone_restart },
1250 	/* 172-174 are SCTP ioctls and not handled by IP */
1251 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1253 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1254 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1255 			IPI_GET_CMD, LIF_CMD,
1256 			ip_sioctl_get_lifusesrc, 0 },
1257 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1258 			IPI_PRIV | IPI_WR,
1259 			LIF_CMD, ip_sioctl_slifusesrc,
1260 			NULL },
1261 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1262 			ip_sioctl_get_lifsrcof, NULL },
1263 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1264 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1265 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1266 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1267 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1268 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1269 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1270 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1271 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1272 	/* SIOCSENABLESDP is handled by SDP */
1273 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1274 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1275 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1276 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1277 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1278 			ip_sioctl_ilb_cmd, NULL },
1279 };
1280 
1281 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1282 
1283 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1284 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1285 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1286 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1287 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1288 	{ ND_GET,	0, 0, 0, NULL, NULL },
1289 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1290 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1291 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1292 		MISC_CMD, mrt_ioctl},
1293 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1294 		MISC_CMD, mrt_ioctl},
1295 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1296 		MISC_CMD, mrt_ioctl}
1297 };
1298 
1299 int ip_misc_ioctl_count =
1300     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1301 
1302 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1303 					/* Settable in /etc/system */
1304 /* Defined in ip_ire.c */
1305 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1306 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1307 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1308 
1309 static nv_t	ire_nv_arr[] = {
1310 	{ IRE_BROADCAST, "BROADCAST" },
1311 	{ IRE_LOCAL, "LOCAL" },
1312 	{ IRE_LOOPBACK, "LOOPBACK" },
1313 	{ IRE_DEFAULT, "DEFAULT" },
1314 	{ IRE_PREFIX, "PREFIX" },
1315 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1316 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1317 	{ IRE_IF_CLONE, "IF_CLONE" },
1318 	{ IRE_HOST, "HOST" },
1319 	{ IRE_MULTICAST, "MULTICAST" },
1320 	{ IRE_NOROUTE, "NOROUTE" },
1321 	{ 0 }
1322 };
1323 
1324 nv_t	*ire_nv_tbl = ire_nv_arr;
1325 
1326 /* Simple ICMP IP Header Template */
1327 static ipha_t icmp_ipha = {
1328 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1329 };
1330 
1331 struct module_info ip_mod_info = {
1332 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1333 	IP_MOD_LOWAT
1334 };
1335 
1336 /*
1337  * Duplicate static symbols within a module confuses mdb; so we avoid the
1338  * problem by making the symbols here distinct from those in udp.c.
1339  */
1340 
1341 /*
1342  * Entry points for IP as a device and as a module.
1343  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1344  */
1345 static struct qinit iprinitv4 = {
1346 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1347 	&ip_mod_info
1348 };
1349 
1350 struct qinit iprinitv6 = {
1351 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1352 	&ip_mod_info
1353 };
1354 
1355 static struct qinit ipwinit = {
1356 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1357 	&ip_mod_info
1358 };
1359 
1360 static struct qinit iplrinit = {
1361 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1362 	&ip_mod_info
1363 };
1364 
1365 static struct qinit iplwinit = {
1366 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1367 	&ip_mod_info
1368 };
1369 
1370 /* For AF_INET aka /dev/ip */
1371 struct streamtab ipinfov4 = {
1372 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1373 };
1374 
1375 /* For AF_INET6 aka /dev/ip6 */
1376 struct streamtab ipinfov6 = {
1377 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1378 };
1379 
1380 #ifdef	DEBUG
1381 boolean_t skip_sctp_cksum = B_FALSE;
1382 #endif
1383 
1384 /*
1385  * Generate an ICMP fragmentation needed message.
1386  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1387  * constructed by the caller.
1388  */
1389 void
1390 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1391 {
1392 	icmph_t	icmph;
1393 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1394 
1395 	mp = icmp_pkt_err_ok(mp, ira);
1396 	if (mp == NULL)
1397 		return;
1398 
1399 	bzero(&icmph, sizeof (icmph_t));
1400 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1401 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1402 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1403 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1404 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1405 
1406 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1407 }
1408 
1409 /*
1410  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1411  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1412  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1413  * Likewise, if the ICMP error is misformed (too short, etc), then it
1414  * returns NULL. The caller uses this to determine whether or not to send
1415  * to raw sockets.
1416  *
1417  * All error messages are passed to the matching transport stream.
1418  *
1419  * The following cases are handled by icmp_inbound:
1420  * 1) It needs to send a reply back and possibly delivering it
1421  *    to the "interested" upper clients.
1422  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1423  * 3) It needs to change some values in IP only.
1424  * 4) It needs to change some values in IP and upper layers e.g TCP
1425  *    by delivering an error to the upper layers.
1426  *
1427  * We handle the above three cases in the context of IPsec in the
1428  * following way :
1429  *
1430  * 1) Send the reply back in the same way as the request came in.
1431  *    If it came in encrypted, it goes out encrypted. If it came in
1432  *    clear, it goes out in clear. Thus, this will prevent chosen
1433  *    plain text attack.
1434  * 2) The client may or may not expect things to come in secure.
1435  *    If it comes in secure, the policy constraints are checked
1436  *    before delivering it to the upper layers. If it comes in
1437  *    clear, ipsec_inbound_accept_clear will decide whether to
1438  *    accept this in clear or not. In both the cases, if the returned
1439  *    message (IP header + 8 bytes) that caused the icmp message has
1440  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1441  *    sending up. If there are only 8 bytes of returned message, then
1442  *    upper client will not be notified.
1443  * 3) Check with global policy to see whether it matches the constaints.
1444  *    But this will be done only if icmp_accept_messages_in_clear is
1445  *    zero.
1446  * 4) If we need to change both in IP and ULP, then the decision taken
1447  *    while affecting the values in IP and while delivering up to TCP
1448  *    should be the same.
1449  *
1450  * 	There are two cases.
1451  *
1452  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1453  *	   failed), we will not deliver it to the ULP, even though they
1454  *	   are *willing* to accept in *clear*. This is fine as our global
1455  *	   disposition to icmp messages asks us reject the datagram.
1456  *
1457  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1458  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1459  *	   to deliver it to ULP (policy failed), it can lead to
1460  *	   consistency problems. The cases known at this time are
1461  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1462  *	   values :
1463  *
1464  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1465  *	     and Upper layer rejects. Then the communication will
1466  *	     come to a stop. This is solved by making similar decisions
1467  *	     at both levels. Currently, when we are unable to deliver
1468  *	     to the Upper Layer (due to policy failures) while IP has
1469  *	     adjusted dce_pmtu, the next outbound datagram would
1470  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1471  *	     will be with the right level of protection. Thus the right
1472  *	     value will be communicated even if we are not able to
1473  *	     communicate when we get from the wire initially. But this
1474  *	     assumes there would be at least one outbound datagram after
1475  *	     IP has adjusted its dce_pmtu value. To make things
1476  *	     simpler, we accept in clear after the validation of
1477  *	     AH/ESP headers.
1478  *
1479  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1480  *	     upper layer depending on the level of protection the upper
1481  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1482  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1483  *	     should be accepted in clear when the Upper layer expects secure.
1484  *	     Thus the communication may get aborted by some bad ICMP
1485  *	     packets.
1486  */
1487 mblk_t *
1488 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1489 {
1490 	icmph_t		*icmph;
1491 	ipha_t		*ipha;		/* Outer header */
1492 	int		ip_hdr_length;	/* Outer header length */
1493 	boolean_t	interested;
1494 	ipif_t		*ipif;
1495 	uint32_t	ts;
1496 	uint32_t	*tsp;
1497 	timestruc_t	now;
1498 	ill_t		*ill = ira->ira_ill;
1499 	ip_stack_t	*ipst = ill->ill_ipst;
1500 	zoneid_t	zoneid = ira->ira_zoneid;
1501 	int		len_needed;
1502 	mblk_t		*mp_ret = NULL;
1503 
1504 	ipha = (ipha_t *)mp->b_rptr;
1505 
1506 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1507 
1508 	ip_hdr_length = ira->ira_ip_hdr_length;
1509 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1510 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1511 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1512 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1513 			freemsg(mp);
1514 			return (NULL);
1515 		}
1516 		/* Last chance to get real. */
1517 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1518 		if (ipha == NULL) {
1519 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1520 			freemsg(mp);
1521 			return (NULL);
1522 		}
1523 	}
1524 
1525 	/* The IP header will always be a multiple of four bytes */
1526 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1527 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1528 	    icmph->icmph_code));
1529 
1530 	/*
1531 	 * We will set "interested" to "true" if we should pass a copy to
1532 	 * the transport or if we handle the packet locally.
1533 	 */
1534 	interested = B_FALSE;
1535 	switch (icmph->icmph_type) {
1536 	case ICMP_ECHO_REPLY:
1537 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1538 		break;
1539 	case ICMP_DEST_UNREACHABLE:
1540 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1541 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1542 		interested = B_TRUE;	/* Pass up to transport */
1543 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1544 		break;
1545 	case ICMP_SOURCE_QUENCH:
1546 		interested = B_TRUE;	/* Pass up to transport */
1547 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1548 		break;
1549 	case ICMP_REDIRECT:
1550 		if (!ipst->ips_ip_ignore_redirect)
1551 			interested = B_TRUE;
1552 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1553 		break;
1554 	case ICMP_ECHO_REQUEST:
1555 		/*
1556 		 * Whether to respond to echo requests that come in as IP
1557 		 * broadcasts or as IP multicast is subject to debate
1558 		 * (what isn't?).  We aim to please, you pick it.
1559 		 * Default is do it.
1560 		 */
1561 		if (ira->ira_flags & IRAF_MULTICAST) {
1562 			/* multicast: respond based on tunable */
1563 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1564 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1565 			/* broadcast: respond based on tunable */
1566 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1567 		} else {
1568 			/* unicast: always respond */
1569 			interested = B_TRUE;
1570 		}
1571 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1572 		if (!interested) {
1573 			/* We never pass these to RAW sockets */
1574 			freemsg(mp);
1575 			return (NULL);
1576 		}
1577 
1578 		/* Check db_ref to make sure we can modify the packet. */
1579 		if (mp->b_datap->db_ref > 1) {
1580 			mblk_t	*mp1;
1581 
1582 			mp1 = copymsg(mp);
1583 			freemsg(mp);
1584 			if (!mp1) {
1585 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1586 				return (NULL);
1587 			}
1588 			mp = mp1;
1589 			ipha = (ipha_t *)mp->b_rptr;
1590 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1591 		}
1592 		icmph->icmph_type = ICMP_ECHO_REPLY;
1593 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1594 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1595 		return (NULL);
1596 
1597 	case ICMP_ROUTER_ADVERTISEMENT:
1598 	case ICMP_ROUTER_SOLICITATION:
1599 		break;
1600 	case ICMP_TIME_EXCEEDED:
1601 		interested = B_TRUE;	/* Pass up to transport */
1602 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1603 		break;
1604 	case ICMP_PARAM_PROBLEM:
1605 		interested = B_TRUE;	/* Pass up to transport */
1606 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1607 		break;
1608 	case ICMP_TIME_STAMP_REQUEST:
1609 		/* Response to Time Stamp Requests is local policy. */
1610 		if (ipst->ips_ip_g_resp_to_timestamp) {
1611 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1612 				interested =
1613 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1614 			else
1615 				interested = B_TRUE;
1616 		}
1617 		if (!interested) {
1618 			/* We never pass these to RAW sockets */
1619 			freemsg(mp);
1620 			return (NULL);
1621 		}
1622 
1623 		/* Make sure we have enough of the packet */
1624 		len_needed = ip_hdr_length + ICMPH_SIZE +
1625 		    3 * sizeof (uint32_t);
1626 
1627 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1628 			ipha = ip_pullup(mp, len_needed, ira);
1629 			if (ipha == NULL) {
1630 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1631 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1632 				    mp, ill);
1633 				freemsg(mp);
1634 				return (NULL);
1635 			}
1636 			/* Refresh following the pullup. */
1637 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1638 		}
1639 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1640 		/* Check db_ref to make sure we can modify the packet. */
1641 		if (mp->b_datap->db_ref > 1) {
1642 			mblk_t	*mp1;
1643 
1644 			mp1 = copymsg(mp);
1645 			freemsg(mp);
1646 			if (!mp1) {
1647 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1648 				return (NULL);
1649 			}
1650 			mp = mp1;
1651 			ipha = (ipha_t *)mp->b_rptr;
1652 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1653 		}
1654 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1655 		tsp = (uint32_t *)&icmph[1];
1656 		tsp++;		/* Skip past 'originate time' */
1657 		/* Compute # of milliseconds since midnight */
1658 		gethrestime(&now);
1659 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1660 		    now.tv_nsec / (NANOSEC / MILLISEC);
1661 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1662 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1663 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1664 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1665 		return (NULL);
1666 
1667 	case ICMP_TIME_STAMP_REPLY:
1668 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1669 		break;
1670 	case ICMP_INFO_REQUEST:
1671 		/* Per RFC 1122 3.2.2.7, ignore this. */
1672 	case ICMP_INFO_REPLY:
1673 		break;
1674 	case ICMP_ADDRESS_MASK_REQUEST:
1675 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1676 			interested =
1677 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1678 		} else {
1679 			interested = B_TRUE;
1680 		}
1681 		if (!interested) {
1682 			/* We never pass these to RAW sockets */
1683 			freemsg(mp);
1684 			return (NULL);
1685 		}
1686 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1687 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1688 			ipha = ip_pullup(mp, len_needed, ira);
1689 			if (ipha == NULL) {
1690 				BUMP_MIB(ill->ill_ip_mib,
1691 				    ipIfStatsInTruncatedPkts);
1692 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1693 				    ill);
1694 				freemsg(mp);
1695 				return (NULL);
1696 			}
1697 			/* Refresh following the pullup. */
1698 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1699 		}
1700 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1701 		/* Check db_ref to make sure we can modify the packet. */
1702 		if (mp->b_datap->db_ref > 1) {
1703 			mblk_t	*mp1;
1704 
1705 			mp1 = copymsg(mp);
1706 			freemsg(mp);
1707 			if (!mp1) {
1708 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1709 				return (NULL);
1710 			}
1711 			mp = mp1;
1712 			ipha = (ipha_t *)mp->b_rptr;
1713 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1714 		}
1715 		/*
1716 		 * Need the ipif with the mask be the same as the source
1717 		 * address of the mask reply. For unicast we have a specific
1718 		 * ipif. For multicast/broadcast we only handle onlink
1719 		 * senders, and use the source address to pick an ipif.
1720 		 */
1721 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1722 		if (ipif == NULL) {
1723 			/* Broadcast or multicast */
1724 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1725 			if (ipif == NULL) {
1726 				freemsg(mp);
1727 				return (NULL);
1728 			}
1729 		}
1730 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1731 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1732 		ipif_refrele(ipif);
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1734 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1735 		return (NULL);
1736 
1737 	case ICMP_ADDRESS_MASK_REPLY:
1738 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1739 		break;
1740 	default:
1741 		interested = B_TRUE;	/* Pass up to transport */
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1743 		break;
1744 	}
1745 	/*
1746 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1747 	 * if there isn't one.
1748 	 */
1749 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1750 		/* If there is an ICMP client and we want one too, copy it. */
1751 
1752 		if (!interested) {
1753 			/* Caller will deliver to RAW sockets */
1754 			return (mp);
1755 		}
1756 		mp_ret = copymsg(mp);
1757 		if (mp_ret == NULL) {
1758 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1759 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1760 		}
1761 	} else if (!interested) {
1762 		/* Neither we nor raw sockets are interested. Drop packet now */
1763 		freemsg(mp);
1764 		return (NULL);
1765 	}
1766 
1767 	/*
1768 	 * ICMP error or redirect packet. Make sure we have enough of
1769 	 * the header and that db_ref == 1 since we might end up modifying
1770 	 * the packet.
1771 	 */
1772 	if (mp->b_cont != NULL) {
1773 		if (ip_pullup(mp, -1, ira) == NULL) {
1774 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1775 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1776 			    mp, ill);
1777 			freemsg(mp);
1778 			return (mp_ret);
1779 		}
1780 	}
1781 
1782 	if (mp->b_datap->db_ref > 1) {
1783 		mblk_t	*mp1;
1784 
1785 		mp1 = copymsg(mp);
1786 		if (mp1 == NULL) {
1787 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1788 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1789 			freemsg(mp);
1790 			return (mp_ret);
1791 		}
1792 		freemsg(mp);
1793 		mp = mp1;
1794 	}
1795 
1796 	/*
1797 	 * In case mp has changed, verify the message before any further
1798 	 * processes.
1799 	 */
1800 	ipha = (ipha_t *)mp->b_rptr;
1801 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1802 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1803 		freemsg(mp);
1804 		return (mp_ret);
1805 	}
1806 
1807 	switch (icmph->icmph_type) {
1808 	case ICMP_REDIRECT:
1809 		icmp_redirect_v4(mp, ipha, icmph, ira);
1810 		break;
1811 	case ICMP_DEST_UNREACHABLE:
1812 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1813 			/* Update DCE and adjust MTU is icmp header if needed */
1814 			icmp_inbound_too_big_v4(icmph, ira);
1815 		}
1816 		/* FALLTHRU */
1817 	default:
1818 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1819 		break;
1820 	}
1821 	return (mp_ret);
1822 }
1823 
1824 /*
1825  * Send an ICMP echo, timestamp or address mask reply.
1826  * The caller has already updated the payload part of the packet.
1827  * We handle the ICMP checksum, IP source address selection and feed
1828  * the packet into ip_output_simple.
1829  */
1830 static void
1831 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1832     ip_recv_attr_t *ira)
1833 {
1834 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1835 	ill_t		*ill = ira->ira_ill;
1836 	ip_stack_t	*ipst = ill->ill_ipst;
1837 	ip_xmit_attr_t	ixas;
1838 
1839 	/* Send out an ICMP packet */
1840 	icmph->icmph_checksum = 0;
1841 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1842 	/* Reset time to live. */
1843 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1844 	{
1845 		/* Swap source and destination addresses */
1846 		ipaddr_t tmp;
1847 
1848 		tmp = ipha->ipha_src;
1849 		ipha->ipha_src = ipha->ipha_dst;
1850 		ipha->ipha_dst = tmp;
1851 	}
1852 	ipha->ipha_ident = 0;
1853 	if (!IS_SIMPLE_IPH(ipha))
1854 		icmp_options_update(ipha);
1855 
1856 	bzero(&ixas, sizeof (ixas));
1857 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1858 	ixas.ixa_zoneid = ira->ira_zoneid;
1859 	ixas.ixa_cred = kcred;
1860 	ixas.ixa_cpid = NOPID;
1861 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1862 	ixas.ixa_ifindex = 0;
1863 	ixas.ixa_ipst = ipst;
1864 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1865 
1866 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1867 		/*
1868 		 * This packet should go out the same way as it
1869 		 * came in i.e in clear, independent of the IPsec policy
1870 		 * for transmitting packets.
1871 		 */
1872 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1873 	} else {
1874 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1876 			/* Note: mp already consumed and ip_drop_packet done */
1877 			return;
1878 		}
1879 	}
1880 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1881 		/*
1882 		 * Not one or our addresses (IRE_LOCALs), thus we let
1883 		 * ip_output_simple pick the source.
1884 		 */
1885 		ipha->ipha_src = INADDR_ANY;
1886 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1887 	}
1888 	/* Should we send with DF and use dce_pmtu? */
1889 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1890 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1891 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1892 	}
1893 
1894 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1895 
1896 	(void) ip_output_simple(mp, &ixas);
1897 	ixa_cleanup(&ixas);
1898 }
1899 
1900 /*
1901  * Verify the ICMP messages for either for ICMP error or redirect packet.
1902  * The caller should have fully pulled up the message. If it's a redirect
1903  * packet, only basic checks on IP header will be done; otherwise, verify
1904  * the packet by looking at the included ULP header.
1905  *
1906  * Called before icmp_inbound_error_fanout_v4 is called.
1907  */
1908 static boolean_t
1909 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1910 {
1911 	ill_t		*ill = ira->ira_ill;
1912 	int		hdr_length;
1913 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1914 	conn_t		*connp;
1915 	ipha_t		*ipha;	/* Inner IP header */
1916 
1917 	ipha = (ipha_t *)&icmph[1];
1918 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1919 		goto truncated;
1920 
1921 	hdr_length = IPH_HDR_LENGTH(ipha);
1922 
1923 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1924 		goto discard_pkt;
1925 
1926 	if (hdr_length < sizeof (ipha_t))
1927 		goto truncated;
1928 
1929 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1930 		goto truncated;
1931 
1932 	/*
1933 	 * Stop here for ICMP_REDIRECT.
1934 	 */
1935 	if (icmph->icmph_type == ICMP_REDIRECT)
1936 		return (B_TRUE);
1937 
1938 	/*
1939 	 * ICMP errors only.
1940 	 */
1941 	switch (ipha->ipha_protocol) {
1942 	case IPPROTO_UDP:
1943 		/*
1944 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1945 		 * transport header.
1946 		 */
1947 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1948 		    mp->b_wptr)
1949 			goto truncated;
1950 		break;
1951 	case IPPROTO_TCP: {
1952 		tcpha_t		*tcpha;
1953 
1954 		/*
1955 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1956 		 * transport header.
1957 		 */
1958 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1959 		    mp->b_wptr)
1960 			goto truncated;
1961 
1962 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1963 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1964 		    ipst);
1965 		if (connp == NULL)
1966 			goto discard_pkt;
1967 
1968 		if ((connp->conn_verifyicmp != NULL) &&
1969 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1970 			CONN_DEC_REF(connp);
1971 			goto discard_pkt;
1972 		}
1973 		CONN_DEC_REF(connp);
1974 		break;
1975 	}
1976 	case IPPROTO_SCTP:
1977 		/*
1978 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1979 		 * transport header.
1980 		 */
1981 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1982 		    mp->b_wptr)
1983 			goto truncated;
1984 		break;
1985 	case IPPROTO_ESP:
1986 	case IPPROTO_AH:
1987 		break;
1988 	case IPPROTO_ENCAP:
1989 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1990 		    mp->b_wptr)
1991 			goto truncated;
1992 		break;
1993 	default:
1994 		break;
1995 	}
1996 
1997 	return (B_TRUE);
1998 
1999 discard_pkt:
2000 	/* Bogus ICMP error. */
2001 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2002 	return (B_FALSE);
2003 
2004 truncated:
2005 	/* We pulled up everthing already. Must be truncated */
2006 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2007 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2008 	return (B_FALSE);
2009 }
2010 
2011 /* Table from RFC 1191 */
2012 static int icmp_frag_size_table[] =
2013 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2014 
2015 /*
2016  * Process received ICMP Packet too big.
2017  * Just handles the DCE create/update, including using the above table of
2018  * PMTU guesses. The caller is responsible for validating the packet before
2019  * passing it in and also to fanout the ICMP error to any matching transport
2020  * conns. Assumes the message has been fully pulled up and verified.
2021  *
2022  * Before getting here, the caller has called icmp_inbound_verify_v4()
2023  * that should have verified with ULP to prevent undoing the changes we're
2024  * going to make to DCE. For example, TCP might have verified that the packet
2025  * which generated error is in the send window.
2026  *
2027  * In some cases modified this MTU in the ICMP header packet; the caller
2028  * should pass to the matching ULP after this returns.
2029  */
2030 static void
2031 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
2032 {
2033 	dce_t		*dce;
2034 	int		old_mtu;
2035 	int		mtu, orig_mtu;
2036 	ipaddr_t	dst;
2037 	boolean_t	disable_pmtud;
2038 	ill_t		*ill = ira->ira_ill;
2039 	ip_stack_t	*ipst = ill->ill_ipst;
2040 	uint_t		hdr_length;
2041 	ipha_t		*ipha;
2042 
2043 	/* Caller already pulled up everything. */
2044 	ipha = (ipha_t *)&icmph[1];
2045 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2046 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2047 	ASSERT(ill != NULL);
2048 
2049 	hdr_length = IPH_HDR_LENGTH(ipha);
2050 
2051 	/*
2052 	 * We handle path MTU for source routed packets since the DCE
2053 	 * is looked up using the final destination.
2054 	 */
2055 	dst = ip_get_dst(ipha);
2056 
2057 	dce = dce_lookup_and_add_v4(dst, ipst);
2058 	if (dce == NULL) {
2059 		/* Couldn't add a unique one - ENOMEM */
2060 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
2061 		    ntohl(dst)));
2062 		return;
2063 	}
2064 
2065 	/* Check for MTU discovery advice as described in RFC 1191 */
2066 	mtu = ntohs(icmph->icmph_du_mtu);
2067 	orig_mtu = mtu;
2068 	disable_pmtud = B_FALSE;
2069 
2070 	mutex_enter(&dce->dce_lock);
2071 	if (dce->dce_flags & DCEF_PMTU)
2072 		old_mtu = dce->dce_pmtu;
2073 	else
2074 		old_mtu = ill->ill_mtu;
2075 
2076 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2077 		uint32_t length;
2078 		int	i;
2079 
2080 		/*
2081 		 * Use the table from RFC 1191 to figure out
2082 		 * the next "plateau" based on the length in
2083 		 * the original IP packet.
2084 		 */
2085 		length = ntohs(ipha->ipha_length);
2086 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
2087 		    uint32_t, length);
2088 		if (old_mtu <= length &&
2089 		    old_mtu >= length - hdr_length) {
2090 			/*
2091 			 * Handle broken BSD 4.2 systems that
2092 			 * return the wrong ipha_length in ICMP
2093 			 * errors.
2094 			 */
2095 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
2096 			    length, old_mtu));
2097 			length -= hdr_length;
2098 		}
2099 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2100 			if (length > icmp_frag_size_table[i])
2101 				break;
2102 		}
2103 		if (i == A_CNT(icmp_frag_size_table)) {
2104 			/* Smaller than IP_MIN_MTU! */
2105 			ip1dbg(("Too big for packet size %d\n",
2106 			    length));
2107 			disable_pmtud = B_TRUE;
2108 			mtu = ipst->ips_ip_pmtu_min;
2109 		} else {
2110 			mtu = icmp_frag_size_table[i];
2111 			ip1dbg(("Calculated mtu %d, packet size %d, "
2112 			    "before %d\n", mtu, length, old_mtu));
2113 			if (mtu < ipst->ips_ip_pmtu_min) {
2114 				mtu = ipst->ips_ip_pmtu_min;
2115 				disable_pmtud = B_TRUE;
2116 			}
2117 		}
2118 	}
2119 	if (disable_pmtud)
2120 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
2121 	else
2122 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
2123 
2124 	dce->dce_pmtu = MIN(old_mtu, mtu);
2125 	/* Prepare to send the new max frag size for the ULP. */
2126 	icmph->icmph_du_zero = 0;
2127 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
2128 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
2129 	    dce, int, orig_mtu, int, mtu);
2130 
2131 	/* We now have a PMTU for sure */
2132 	dce->dce_flags |= DCEF_PMTU;
2133 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
2134 	mutex_exit(&dce->dce_lock);
2135 	/*
2136 	 * After dropping the lock the new value is visible to everyone.
2137 	 * Then we bump the generation number so any cached values reinspect
2138 	 * the dce_t.
2139 	 */
2140 	dce_increment_generation(dce);
2141 	dce_refrele(dce);
2142 }
2143 
2144 /*
2145  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
2146  * calls this function.
2147  */
2148 static mblk_t *
2149 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
2150 {
2151 	int length;
2152 
2153 	ASSERT(mp->b_datap->db_type == M_DATA);
2154 
2155 	/* icmp_inbound_v4 has already pulled up the whole error packet */
2156 	ASSERT(mp->b_cont == NULL);
2157 
2158 	/*
2159 	 * The length that we want to overlay is the inner header
2160 	 * and what follows it.
2161 	 */
2162 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2163 
2164 	/*
2165 	 * Overlay the inner header and whatever follows it over the
2166 	 * outer header.
2167 	 */
2168 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2169 
2170 	/* Adjust for what we removed */
2171 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2172 	return (mp);
2173 }
2174 
2175 /*
2176  * Try to pass the ICMP message upstream in case the ULP cares.
2177  *
2178  * If the packet that caused the ICMP error is secure, we send
2179  * it to AH/ESP to make sure that the attached packet has a
2180  * valid association. ipha in the code below points to the
2181  * IP header of the packet that caused the error.
2182  *
2183  * For IPsec cases, we let the next-layer-up (which has access to
2184  * cached policy on the conn_t, or can query the SPD directly)
2185  * subtract out any IPsec overhead if they must.  We therefore make no
2186  * adjustments here for IPsec overhead.
2187  *
2188  * IFN could have been generated locally or by some router.
2189  *
2190  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2191  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2192  *	    This happens because IP adjusted its value of MTU on an
2193  *	    earlier IFN message and could not tell the upper layer,
2194  *	    the new adjusted value of MTU e.g. Packet was encrypted
2195  *	    or there was not enough information to fanout to upper
2196  *	    layers. Thus on the next outbound datagram, ire_send_wire
2197  *	    generates the IFN, where IPsec processing has *not* been
2198  *	    done.
2199  *
2200  *	    Note that we retain ixa_fragsize across IPsec thus once
2201  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2202  *	    no change the fragsize even if the path MTU changes before
2203  *	    we reach ip_output_post_ipsec.
2204  *
2205  *	    In the local case, IRAF_LOOPBACK will be set indicating
2206  *	    that IFN was generated locally.
2207  *
2208  * ROUTER : IFN could be secure or non-secure.
2209  *
2210  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2211  *	      packet in error has AH/ESP headers to validate the AH/ESP
2212  *	      headers. AH/ESP will verify whether there is a valid SA or
2213  *	      not and send it back. We will fanout again if we have more
2214  *	      data in the packet.
2215  *
2216  *	      If the packet in error does not have AH/ESP, we handle it
2217  *	      like any other case.
2218  *
2219  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2220  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2221  *	      valid SA or not and send it back. We will fanout again if
2222  *	      we have more data in the packet.
2223  *
2224  *	      If the packet in error does not have AH/ESP, we handle it
2225  *	      like any other case.
2226  *
2227  * The caller must have called icmp_inbound_verify_v4.
2228  */
2229 static void
2230 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2231 {
2232 	uint16_t	*up;	/* Pointer to ports in ULP header */
2233 	uint32_t	ports;	/* reversed ports for fanout */
2234 	ipha_t		ripha;	/* With reversed addresses */
2235 	ipha_t		*ipha;  /* Inner IP header */
2236 	uint_t		hdr_length; /* Inner IP header length */
2237 	tcpha_t		*tcpha;
2238 	conn_t		*connp;
2239 	ill_t		*ill = ira->ira_ill;
2240 	ip_stack_t	*ipst = ill->ill_ipst;
2241 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2242 	ill_t		*rill = ira->ira_rill;
2243 
2244 	/* Caller already pulled up everything. */
2245 	ipha = (ipha_t *)&icmph[1];
2246 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2247 	ASSERT(mp->b_cont == NULL);
2248 
2249 	hdr_length = IPH_HDR_LENGTH(ipha);
2250 	ira->ira_protocol = ipha->ipha_protocol;
2251 
2252 	/*
2253 	 * We need a separate IP header with the source and destination
2254 	 * addresses reversed to do fanout/classification because the ipha in
2255 	 * the ICMP error is in the form we sent it out.
2256 	 */
2257 	ripha.ipha_src = ipha->ipha_dst;
2258 	ripha.ipha_dst = ipha->ipha_src;
2259 	ripha.ipha_protocol = ipha->ipha_protocol;
2260 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2261 
2262 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2263 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2264 	    ntohl(ipha->ipha_dst),
2265 	    icmph->icmph_type, icmph->icmph_code));
2266 
2267 	switch (ipha->ipha_protocol) {
2268 	case IPPROTO_UDP:
2269 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2270 
2271 		/* Attempt to find a client stream based on port. */
2272 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2273 		    ntohs(up[0]), ntohs(up[1])));
2274 
2275 		/* Note that we send error to all matches. */
2276 		ira->ira_flags |= IRAF_ICMP_ERROR;
2277 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2278 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2279 		return;
2280 
2281 	case IPPROTO_TCP:
2282 		/*
2283 		 * Find a TCP client stream for this packet.
2284 		 * Note that we do a reverse lookup since the header is
2285 		 * in the form we sent it out.
2286 		 */
2287 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2288 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2289 		    ipst);
2290 		if (connp == NULL)
2291 			goto discard_pkt;
2292 
2293 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2294 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2295 			mp = ipsec_check_inbound_policy(mp, connp,
2296 			    ipha, NULL, ira);
2297 			if (mp == NULL) {
2298 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2299 				/* Note that mp is NULL */
2300 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2301 				CONN_DEC_REF(connp);
2302 				return;
2303 			}
2304 		}
2305 
2306 		ira->ira_flags |= IRAF_ICMP_ERROR;
2307 		ira->ira_ill = ira->ira_rill = NULL;
2308 		if (IPCL_IS_TCP(connp)) {
2309 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2310 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2311 			    SQTAG_TCP_INPUT_ICMP_ERR);
2312 		} else {
2313 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2314 			(connp->conn_recv)(connp, mp, NULL, ira);
2315 			CONN_DEC_REF(connp);
2316 		}
2317 		ira->ira_ill = ill;
2318 		ira->ira_rill = rill;
2319 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2320 		return;
2321 
2322 	case IPPROTO_SCTP:
2323 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2324 		/* Find a SCTP client stream for this packet. */
2325 		((uint16_t *)&ports)[0] = up[1];
2326 		((uint16_t *)&ports)[1] = up[0];
2327 
2328 		ira->ira_flags |= IRAF_ICMP_ERROR;
2329 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2330 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2331 		return;
2332 
2333 	case IPPROTO_ESP:
2334 	case IPPROTO_AH:
2335 		if (!ipsec_loaded(ipss)) {
2336 			ip_proto_not_sup(mp, ira);
2337 			return;
2338 		}
2339 
2340 		if (ipha->ipha_protocol == IPPROTO_ESP)
2341 			mp = ipsecesp_icmp_error(mp, ira);
2342 		else
2343 			mp = ipsecah_icmp_error(mp, ira);
2344 		if (mp == NULL)
2345 			return;
2346 
2347 		/* Just in case ipsec didn't preserve the NULL b_cont */
2348 		if (mp->b_cont != NULL) {
2349 			if (!pullupmsg(mp, -1))
2350 				goto discard_pkt;
2351 		}
2352 
2353 		/*
2354 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2355 		 * correct, but we don't use them any more here.
2356 		 *
2357 		 * If succesful, the mp has been modified to not include
2358 		 * the ESP/AH header so we can fanout to the ULP's icmp
2359 		 * error handler.
2360 		 */
2361 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2362 			goto truncated;
2363 
2364 		/* Verify the modified message before any further processes. */
2365 		ipha = (ipha_t *)mp->b_rptr;
2366 		hdr_length = IPH_HDR_LENGTH(ipha);
2367 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2368 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2369 			freemsg(mp);
2370 			return;
2371 		}
2372 
2373 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2374 		return;
2375 
2376 	case IPPROTO_ENCAP: {
2377 		/* Look for self-encapsulated packets that caused an error */
2378 		ipha_t *in_ipha;
2379 
2380 		/*
2381 		 * Caller has verified that length has to be
2382 		 * at least the size of IP header.
2383 		 */
2384 		ASSERT(hdr_length >= sizeof (ipha_t));
2385 		/*
2386 		 * Check the sanity of the inner IP header like
2387 		 * we did for the outer header.
2388 		 */
2389 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2390 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2391 			goto discard_pkt;
2392 		}
2393 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2394 			goto discard_pkt;
2395 		}
2396 		/* Check for Self-encapsulated tunnels */
2397 		if (in_ipha->ipha_src == ipha->ipha_src &&
2398 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2399 
2400 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2401 			    in_ipha);
2402 			if (mp == NULL)
2403 				goto discard_pkt;
2404 
2405 			/*
2406 			 * Just in case self_encap didn't preserve the NULL
2407 			 * b_cont
2408 			 */
2409 			if (mp->b_cont != NULL) {
2410 				if (!pullupmsg(mp, -1))
2411 					goto discard_pkt;
2412 			}
2413 			/*
2414 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2415 			 * longer correct, but we don't use them any more here.
2416 			 */
2417 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2418 				goto truncated;
2419 
2420 			/*
2421 			 * Verify the modified message before any further
2422 			 * processes.
2423 			 */
2424 			ipha = (ipha_t *)mp->b_rptr;
2425 			hdr_length = IPH_HDR_LENGTH(ipha);
2426 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2427 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2428 				freemsg(mp);
2429 				return;
2430 			}
2431 
2432 			/*
2433 			 * The packet in error is self-encapsualted.
2434 			 * And we are finding it further encapsulated
2435 			 * which we could not have possibly generated.
2436 			 */
2437 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2438 				goto discard_pkt;
2439 			}
2440 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2441 			return;
2442 		}
2443 		/* No self-encapsulated */
2444 		/* FALLTHRU */
2445 	}
2446 	case IPPROTO_IPV6:
2447 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2448 		    &ripha.ipha_dst, ipst)) != NULL) {
2449 			ira->ira_flags |= IRAF_ICMP_ERROR;
2450 			connp->conn_recvicmp(connp, mp, NULL, ira);
2451 			CONN_DEC_REF(connp);
2452 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2453 			return;
2454 		}
2455 		/*
2456 		 * No IP tunnel is interested, fallthrough and see
2457 		 * if a raw socket will want it.
2458 		 */
2459 		/* FALLTHRU */
2460 	default:
2461 		ira->ira_flags |= IRAF_ICMP_ERROR;
2462 		ip_fanout_proto_v4(mp, &ripha, ira);
2463 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2464 		return;
2465 	}
2466 	/* NOTREACHED */
2467 discard_pkt:
2468 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2469 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2470 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2471 	freemsg(mp);
2472 	return;
2473 
2474 truncated:
2475 	/* We pulled up everthing already. Must be truncated */
2476 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2477 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2478 	freemsg(mp);
2479 }
2480 
2481 /*
2482  * Common IP options parser.
2483  *
2484  * Setup routine: fill in *optp with options-parsing state, then
2485  * tail-call ipoptp_next to return the first option.
2486  */
2487 uint8_t
2488 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2489 {
2490 	uint32_t totallen; /* total length of all options */
2491 
2492 	totallen = ipha->ipha_version_and_hdr_length -
2493 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2494 	totallen <<= 2;
2495 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2496 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2497 	optp->ipoptp_flags = 0;
2498 	return (ipoptp_next(optp));
2499 }
2500 
2501 /* Like above but without an ipha_t */
2502 uint8_t
2503 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2504 {
2505 	optp->ipoptp_next = opt;
2506 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2507 	optp->ipoptp_flags = 0;
2508 	return (ipoptp_next(optp));
2509 }
2510 
2511 /*
2512  * Common IP options parser: extract next option.
2513  */
2514 uint8_t
2515 ipoptp_next(ipoptp_t *optp)
2516 {
2517 	uint8_t *end = optp->ipoptp_end;
2518 	uint8_t *cur = optp->ipoptp_next;
2519 	uint8_t opt, len, pointer;
2520 
2521 	/*
2522 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2523 	 * has been corrupted.
2524 	 */
2525 	ASSERT(cur <= end);
2526 
2527 	if (cur == end)
2528 		return (IPOPT_EOL);
2529 
2530 	opt = cur[IPOPT_OPTVAL];
2531 
2532 	/*
2533 	 * Skip any NOP options.
2534 	 */
2535 	while (opt == IPOPT_NOP) {
2536 		cur++;
2537 		if (cur == end)
2538 			return (IPOPT_EOL);
2539 		opt = cur[IPOPT_OPTVAL];
2540 	}
2541 
2542 	if (opt == IPOPT_EOL)
2543 		return (IPOPT_EOL);
2544 
2545 	/*
2546 	 * Option requiring a length.
2547 	 */
2548 	if ((cur + 1) >= end) {
2549 		optp->ipoptp_flags |= IPOPTP_ERROR;
2550 		return (IPOPT_EOL);
2551 	}
2552 	len = cur[IPOPT_OLEN];
2553 	if (len < 2) {
2554 		optp->ipoptp_flags |= IPOPTP_ERROR;
2555 		return (IPOPT_EOL);
2556 	}
2557 	optp->ipoptp_cur = cur;
2558 	optp->ipoptp_len = len;
2559 	optp->ipoptp_next = cur + len;
2560 	if (cur + len > end) {
2561 		optp->ipoptp_flags |= IPOPTP_ERROR;
2562 		return (IPOPT_EOL);
2563 	}
2564 
2565 	/*
2566 	 * For the options which require a pointer field, make sure
2567 	 * its there, and make sure it points to either something
2568 	 * inside this option, or the end of the option.
2569 	 */
2570 	switch (opt) {
2571 	case IPOPT_RR:
2572 	case IPOPT_TS:
2573 	case IPOPT_LSRR:
2574 	case IPOPT_SSRR:
2575 		if (len <= IPOPT_OFFSET) {
2576 			optp->ipoptp_flags |= IPOPTP_ERROR;
2577 			return (opt);
2578 		}
2579 		pointer = cur[IPOPT_OFFSET];
2580 		if (pointer - 1 > len) {
2581 			optp->ipoptp_flags |= IPOPTP_ERROR;
2582 			return (opt);
2583 		}
2584 		break;
2585 	}
2586 
2587 	/*
2588 	 * Sanity check the pointer field based on the type of the
2589 	 * option.
2590 	 */
2591 	switch (opt) {
2592 	case IPOPT_RR:
2593 	case IPOPT_SSRR:
2594 	case IPOPT_LSRR:
2595 		if (pointer < IPOPT_MINOFF_SR)
2596 			optp->ipoptp_flags |= IPOPTP_ERROR;
2597 		break;
2598 	case IPOPT_TS:
2599 		if (pointer < IPOPT_MINOFF_IT)
2600 			optp->ipoptp_flags |= IPOPTP_ERROR;
2601 		/*
2602 		 * Note that the Internet Timestamp option also
2603 		 * contains two four bit fields (the Overflow field,
2604 		 * and the Flag field), which follow the pointer
2605 		 * field.  We don't need to check that these fields
2606 		 * fall within the length of the option because this
2607 		 * was implicitely done above.  We've checked that the
2608 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2609 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2610 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2611 		 */
2612 		ASSERT(len > IPOPT_POS_OV_FLG);
2613 		break;
2614 	}
2615 
2616 	return (opt);
2617 }
2618 
2619 /*
2620  * Use the outgoing IP header to create an IP_OPTIONS option the way
2621  * it was passed down from the application.
2622  *
2623  * This is compatible with BSD in that it returns
2624  * the reverse source route with the final destination
2625  * as the last entry. The first 4 bytes of the option
2626  * will contain the final destination.
2627  */
2628 int
2629 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2630 {
2631 	ipoptp_t	opts;
2632 	uchar_t		*opt;
2633 	uint8_t		optval;
2634 	uint8_t		optlen;
2635 	uint32_t	len = 0;
2636 	uchar_t		*buf1 = buf;
2637 	uint32_t	totallen;
2638 	ipaddr_t	dst;
2639 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2640 
2641 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2642 		return (0);
2643 
2644 	totallen = ipp->ipp_ipv4_options_len;
2645 	if (totallen & 0x3)
2646 		return (0);
2647 
2648 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2649 	len += IP_ADDR_LEN;
2650 	bzero(buf1, IP_ADDR_LEN);
2651 
2652 	dst = connp->conn_faddr_v4;
2653 
2654 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2655 	    optval != IPOPT_EOL;
2656 	    optval = ipoptp_next(&opts)) {
2657 		int	off;
2658 
2659 		opt = opts.ipoptp_cur;
2660 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2661 			break;
2662 		}
2663 		optlen = opts.ipoptp_len;
2664 
2665 		switch (optval) {
2666 		case IPOPT_SSRR:
2667 		case IPOPT_LSRR:
2668 
2669 			/*
2670 			 * Insert destination as the first entry in the source
2671 			 * route and move down the entries on step.
2672 			 * The last entry gets placed at buf1.
2673 			 */
2674 			buf[IPOPT_OPTVAL] = optval;
2675 			buf[IPOPT_OLEN] = optlen;
2676 			buf[IPOPT_OFFSET] = optlen;
2677 
2678 			off = optlen - IP_ADDR_LEN;
2679 			if (off < 0) {
2680 				/* No entries in source route */
2681 				break;
2682 			}
2683 			/* Last entry in source route if not already set */
2684 			if (dst == INADDR_ANY)
2685 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2686 			off -= IP_ADDR_LEN;
2687 
2688 			while (off > 0) {
2689 				bcopy(opt + off,
2690 				    buf + off + IP_ADDR_LEN,
2691 				    IP_ADDR_LEN);
2692 				off -= IP_ADDR_LEN;
2693 			}
2694 			/* ipha_dst into first slot */
2695 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2696 			    IP_ADDR_LEN);
2697 			buf += optlen;
2698 			len += optlen;
2699 			break;
2700 
2701 		default:
2702 			bcopy(opt, buf, optlen);
2703 			buf += optlen;
2704 			len += optlen;
2705 			break;
2706 		}
2707 	}
2708 done:
2709 	/* Pad the resulting options */
2710 	while (len & 0x3) {
2711 		*buf++ = IPOPT_EOL;
2712 		len++;
2713 	}
2714 	return (len);
2715 }
2716 
2717 /*
2718  * Update any record route or timestamp options to include this host.
2719  * Reverse any source route option.
2720  * This routine assumes that the options are well formed i.e. that they
2721  * have already been checked.
2722  */
2723 static void
2724 icmp_options_update(ipha_t *ipha)
2725 {
2726 	ipoptp_t	opts;
2727 	uchar_t		*opt;
2728 	uint8_t		optval;
2729 	ipaddr_t	src;		/* Our local address */
2730 	ipaddr_t	dst;
2731 
2732 	ip2dbg(("icmp_options_update\n"));
2733 	src = ipha->ipha_src;
2734 	dst = ipha->ipha_dst;
2735 
2736 	for (optval = ipoptp_first(&opts, ipha);
2737 	    optval != IPOPT_EOL;
2738 	    optval = ipoptp_next(&opts)) {
2739 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2740 		opt = opts.ipoptp_cur;
2741 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2742 		    optval, opts.ipoptp_len));
2743 		switch (optval) {
2744 			int off1, off2;
2745 		case IPOPT_SSRR:
2746 		case IPOPT_LSRR:
2747 			/*
2748 			 * Reverse the source route.  The first entry
2749 			 * should be the next to last one in the current
2750 			 * source route (the last entry is our address).
2751 			 * The last entry should be the final destination.
2752 			 */
2753 			off1 = IPOPT_MINOFF_SR - 1;
2754 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2755 			if (off2 < 0) {
2756 				/* No entries in source route */
2757 				ip1dbg((
2758 				    "icmp_options_update: bad src route\n"));
2759 				break;
2760 			}
2761 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2762 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2763 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2764 			off2 -= IP_ADDR_LEN;
2765 
2766 			while (off1 < off2) {
2767 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2768 				bcopy((char *)opt + off2, (char *)opt + off1,
2769 				    IP_ADDR_LEN);
2770 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2771 				off1 += IP_ADDR_LEN;
2772 				off2 -= IP_ADDR_LEN;
2773 			}
2774 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2775 			break;
2776 		}
2777 	}
2778 }
2779 
2780 /*
2781  * Process received ICMP Redirect messages.
2782  * Assumes the caller has verified that the headers are in the pulled up mblk.
2783  * Consumes mp.
2784  */
2785 static void
2786 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2787 {
2788 	ire_t		*ire, *nire;
2789 	ire_t		*prev_ire;
2790 	ipaddr_t  	src, dst, gateway;
2791 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2792 	ipha_t		*inner_ipha;	/* Inner IP header */
2793 
2794 	/* Caller already pulled up everything. */
2795 	inner_ipha = (ipha_t *)&icmph[1];
2796 	src = ipha->ipha_src;
2797 	dst = inner_ipha->ipha_dst;
2798 	gateway = icmph->icmph_rd_gateway;
2799 	/* Make sure the new gateway is reachable somehow. */
2800 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2801 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2802 	/*
2803 	 * Make sure we had a route for the dest in question and that
2804 	 * that route was pointing to the old gateway (the source of the
2805 	 * redirect packet.)
2806 	 * Note: this merely says that there is some IRE which matches that
2807 	 * gateway; not that the longest match matches that gateway.
2808 	 */
2809 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, 0, NULL, ALL_ZONES,
2810 	    NULL, MATCH_IRE_GW, 0, ipst, NULL);
2811 	/*
2812 	 * Check that
2813 	 *	the redirect was not from ourselves
2814 	 *	the new gateway and the old gateway are directly reachable
2815 	 */
2816 	if (prev_ire == NULL || ire == NULL ||
2817 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2818 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2819 	    !(ire->ire_type & IRE_IF_ALL)) {
2820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2821 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2822 		freemsg(mp);
2823 		if (ire != NULL)
2824 			ire_refrele(ire);
2825 		if (prev_ire != NULL)
2826 			ire_refrele(prev_ire);
2827 		return;
2828 	}
2829 
2830 	ire_refrele(prev_ire);
2831 	ire_refrele(ire);
2832 
2833 	/*
2834 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2835 	 * require TOS routing
2836 	 */
2837 	switch (icmph->icmph_code) {
2838 	case 0:
2839 	case 1:
2840 		/* TODO: TOS specificity for cases 2 and 3 */
2841 	case 2:
2842 	case 3:
2843 		break;
2844 	default:
2845 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2846 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2847 		freemsg(mp);
2848 		return;
2849 	}
2850 	/*
2851 	 * Create a Route Association.  This will allow us to remember that
2852 	 * someone we believe told us to use the particular gateway.
2853 	 */
2854 	ire = ire_create(
2855 	    (uchar_t *)&dst,			/* dest addr */
2856 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2857 	    (uchar_t *)&gateway,		/* gateway addr */
2858 	    IRE_HOST,
2859 	    NULL,				/* ill */
2860 	    ALL_ZONES,
2861 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2862 	    NULL,				/* tsol_gc_t */
2863 	    ipst);
2864 
2865 	if (ire == NULL) {
2866 		freemsg(mp);
2867 		return;
2868 	}
2869 	nire = ire_add(ire);
2870 	/* Check if it was a duplicate entry */
2871 	if (nire != NULL && nire != ire) {
2872 		ASSERT(nire->ire_identical_ref > 1);
2873 		ire_delete(nire);
2874 		ire_refrele(nire);
2875 		nire = NULL;
2876 	}
2877 	ire = nire;
2878 	if (ire != NULL) {
2879 		ire_refrele(ire);		/* Held in ire_add */
2880 
2881 		/* tell routing sockets that we received a redirect */
2882 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2883 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2884 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2885 	}
2886 
2887 	/*
2888 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2889 	 * This together with the added IRE has the effect of
2890 	 * modifying an existing redirect.
2891 	 */
2892 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2893 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2894 	if (prev_ire != NULL) {
2895 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2896 			ire_delete(prev_ire);
2897 		ire_refrele(prev_ire);
2898 	}
2899 
2900 	freemsg(mp);
2901 }
2902 
2903 /*
2904  * Generate an ICMP parameter problem message.
2905  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2906  * constructed by the caller.
2907  */
2908 static void
2909 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2910 {
2911 	icmph_t	icmph;
2912 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2913 
2914 	mp = icmp_pkt_err_ok(mp, ira);
2915 	if (mp == NULL)
2916 		return;
2917 
2918 	bzero(&icmph, sizeof (icmph_t));
2919 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2920 	icmph.icmph_pp_ptr = ptr;
2921 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2922 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2923 }
2924 
2925 /*
2926  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2927  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2928  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2929  * an icmp error packet can be sent.
2930  * Assigns an appropriate source address to the packet. If ipha_dst is
2931  * one of our addresses use it for source. Otherwise let ip_output_simple
2932  * pick the source address.
2933  */
2934 static void
2935 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2936 {
2937 	ipaddr_t dst;
2938 	icmph_t	*icmph;
2939 	ipha_t	*ipha;
2940 	uint_t	len_needed;
2941 	size_t	msg_len;
2942 	mblk_t	*mp1;
2943 	ipaddr_t src;
2944 	ire_t	*ire;
2945 	ip_xmit_attr_t ixas;
2946 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2947 
2948 	ipha = (ipha_t *)mp->b_rptr;
2949 
2950 	bzero(&ixas, sizeof (ixas));
2951 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2952 	ixas.ixa_zoneid = ira->ira_zoneid;
2953 	ixas.ixa_ifindex = 0;
2954 	ixas.ixa_ipst = ipst;
2955 	ixas.ixa_cred = kcred;
2956 	ixas.ixa_cpid = NOPID;
2957 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2958 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2959 
2960 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2961 		/*
2962 		 * Apply IPsec based on how IPsec was applied to
2963 		 * the packet that had the error.
2964 		 *
2965 		 * If it was an outbound packet that caused the ICMP
2966 		 * error, then the caller will have setup the IRA
2967 		 * appropriately.
2968 		 */
2969 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2970 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2971 			/* Note: mp already consumed and ip_drop_packet done */
2972 			return;
2973 		}
2974 	} else {
2975 		/*
2976 		 * This is in clear. The icmp message we are building
2977 		 * here should go out in clear, independent of our policy.
2978 		 */
2979 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2980 	}
2981 
2982 	/* Remember our eventual destination */
2983 	dst = ipha->ipha_src;
2984 
2985 	/*
2986 	 * If the packet was for one of our unicast addresses, make
2987 	 * sure we respond with that as the source. Otherwise
2988 	 * have ip_output_simple pick the source address.
2989 	 */
2990 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2991 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2992 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2993 	if (ire != NULL) {
2994 		ire_refrele(ire);
2995 		src = ipha->ipha_dst;
2996 	} else {
2997 		src = INADDR_ANY;
2998 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2999 	}
3000 
3001 	/*
3002 	 * Check if we can send back more then 8 bytes in addition to
3003 	 * the IP header.  We try to send 64 bytes of data and the internal
3004 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3005 	 */
3006 	len_needed = IPH_HDR_LENGTH(ipha);
3007 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3008 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3009 		if (!pullupmsg(mp, -1)) {
3010 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3011 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
3012 			freemsg(mp);
3013 			return;
3014 		}
3015 		ipha = (ipha_t *)mp->b_rptr;
3016 
3017 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3018 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3019 			    len_needed));
3020 		} else {
3021 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3022 
3023 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3024 			len_needed += ip_hdr_length_v6(mp, ip6h);
3025 		}
3026 	}
3027 	len_needed += ipst->ips_ip_icmp_return;
3028 	msg_len = msgdsize(mp);
3029 	if (msg_len > len_needed) {
3030 		(void) adjmsg(mp, len_needed - msg_len);
3031 		msg_len = len_needed;
3032 	}
3033 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
3034 	if (mp1 == NULL) {
3035 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3036 		freemsg(mp);
3037 		return;
3038 	}
3039 	mp1->b_cont = mp;
3040 	mp = mp1;
3041 
3042 	/*
3043 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
3044 	 * node generates be accepted in peace by all on-host destinations.
3045 	 * If we do NOT assume that all on-host destinations trust
3046 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3047 	 * (Look for IXAF_TRUSTED_ICMP).
3048 	 */
3049 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
3050 
3051 	ipha = (ipha_t *)mp->b_rptr;
3052 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3053 	*ipha = icmp_ipha;
3054 	ipha->ipha_src = src;
3055 	ipha->ipha_dst = dst;
3056 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3057 	msg_len += sizeof (icmp_ipha) + len;
3058 	if (msg_len > IP_MAXPACKET) {
3059 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3060 		msg_len = IP_MAXPACKET;
3061 	}
3062 	ipha->ipha_length = htons((uint16_t)msg_len);
3063 	icmph = (icmph_t *)&ipha[1];
3064 	bcopy(stuff, icmph, len);
3065 	icmph->icmph_checksum = 0;
3066 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3067 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3068 
3069 	(void) ip_output_simple(mp, &ixas);
3070 	ixa_cleanup(&ixas);
3071 }
3072 
3073 /*
3074  * Determine if an ICMP error packet can be sent given the rate limit.
3075  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3076  * in milliseconds) and a burst size. Burst size number of packets can
3077  * be sent arbitrarely closely spaced.
3078  * The state is tracked using two variables to implement an approximate
3079  * token bucket filter:
3080  *	icmp_pkt_err_last - lbolt value when the last burst started
3081  *	icmp_pkt_err_sent - number of packets sent in current burst
3082  */
3083 boolean_t
3084 icmp_err_rate_limit(ip_stack_t *ipst)
3085 {
3086 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
3087 	uint_t refilled; /* Number of packets refilled in tbf since last */
3088 	/* Guard against changes by loading into local variable */
3089 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3090 
3091 	if (err_interval == 0)
3092 		return (B_FALSE);
3093 
3094 	if (ipst->ips_icmp_pkt_err_last > now) {
3095 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3096 		ipst->ips_icmp_pkt_err_last = 0;
3097 		ipst->ips_icmp_pkt_err_sent = 0;
3098 	}
3099 	/*
3100 	 * If we are in a burst update the token bucket filter.
3101 	 * Update the "last" time to be close to "now" but make sure
3102 	 * we don't loose precision.
3103 	 */
3104 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3105 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3106 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3107 			ipst->ips_icmp_pkt_err_sent = 0;
3108 		} else {
3109 			ipst->ips_icmp_pkt_err_sent -= refilled;
3110 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3111 		}
3112 	}
3113 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3114 		/* Start of new burst */
3115 		ipst->ips_icmp_pkt_err_last = now;
3116 	}
3117 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3118 		ipst->ips_icmp_pkt_err_sent++;
3119 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3120 		    ipst->ips_icmp_pkt_err_sent));
3121 		return (B_FALSE);
3122 	}
3123 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3124 	return (B_TRUE);
3125 }
3126 
3127 /*
3128  * Check if it is ok to send an IPv4 ICMP error packet in
3129  * response to the IPv4 packet in mp.
3130  * Free the message and return null if no
3131  * ICMP error packet should be sent.
3132  */
3133 static mblk_t *
3134 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
3135 {
3136 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3137 	icmph_t	*icmph;
3138 	ipha_t	*ipha;
3139 	uint_t	len_needed;
3140 
3141 	if (!mp)
3142 		return (NULL);
3143 	ipha = (ipha_t *)mp->b_rptr;
3144 	if (ip_csum_hdr(ipha)) {
3145 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3146 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
3147 		freemsg(mp);
3148 		return (NULL);
3149 	}
3150 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
3151 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
3152 	    CLASSD(ipha->ipha_dst) ||
3153 	    CLASSD(ipha->ipha_src) ||
3154 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3155 		/* Note: only errors to the fragment with offset 0 */
3156 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3157 		freemsg(mp);
3158 		return (NULL);
3159 	}
3160 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3161 		/*
3162 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3163 		 * errors in response to any ICMP errors.
3164 		 */
3165 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3166 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3167 			if (!pullupmsg(mp, len_needed)) {
3168 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3169 				freemsg(mp);
3170 				return (NULL);
3171 			}
3172 			ipha = (ipha_t *)mp->b_rptr;
3173 		}
3174 		icmph = (icmph_t *)
3175 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3176 		switch (icmph->icmph_type) {
3177 		case ICMP_DEST_UNREACHABLE:
3178 		case ICMP_SOURCE_QUENCH:
3179 		case ICMP_TIME_EXCEEDED:
3180 		case ICMP_PARAM_PROBLEM:
3181 		case ICMP_REDIRECT:
3182 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3183 			freemsg(mp);
3184 			return (NULL);
3185 		default:
3186 			break;
3187 		}
3188 	}
3189 	/*
3190 	 * If this is a labeled system, then check to see if we're allowed to
3191 	 * send a response to this particular sender.  If not, then just drop.
3192 	 */
3193 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3194 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3195 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3196 		freemsg(mp);
3197 		return (NULL);
3198 	}
3199 	if (icmp_err_rate_limit(ipst)) {
3200 		/*
3201 		 * Only send ICMP error packets every so often.
3202 		 * This should be done on a per port/source basis,
3203 		 * but for now this will suffice.
3204 		 */
3205 		freemsg(mp);
3206 		return (NULL);
3207 	}
3208 	return (mp);
3209 }
3210 
3211 /*
3212  * Called when a packet was sent out the same link that it arrived on.
3213  * Check if it is ok to send a redirect and then send it.
3214  */
3215 void
3216 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3217     ip_recv_attr_t *ira)
3218 {
3219 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3220 	ipaddr_t	src, nhop;
3221 	mblk_t		*mp1;
3222 	ire_t		*nhop_ire;
3223 
3224 	/*
3225 	 * Check the source address to see if it originated
3226 	 * on the same logical subnet it is going back out on.
3227 	 * If so, we should be able to send it a redirect.
3228 	 * Avoid sending a redirect if the destination
3229 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3230 	 * or if the packet was source routed out this interface.
3231 	 *
3232 	 * We avoid sending a redirect if the
3233 	 * destination is directly connected
3234 	 * because it is possible that multiple
3235 	 * IP subnets may have been configured on
3236 	 * the link, and the source may not
3237 	 * be on the same subnet as ip destination,
3238 	 * even though they are on the same
3239 	 * physical link.
3240 	 */
3241 	if ((ire->ire_type & IRE_ONLINK) ||
3242 	    ip_source_routed(ipha, ipst))
3243 		return;
3244 
3245 	nhop_ire = ire_nexthop(ire);
3246 	if (nhop_ire == NULL)
3247 		return;
3248 
3249 	nhop = nhop_ire->ire_addr;
3250 
3251 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3252 		ire_t	*ire2;
3253 
3254 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3255 		mutex_enter(&nhop_ire->ire_lock);
3256 		ire2 = nhop_ire->ire_dep_parent;
3257 		if (ire2 != NULL)
3258 			ire_refhold(ire2);
3259 		mutex_exit(&nhop_ire->ire_lock);
3260 		ire_refrele(nhop_ire);
3261 		nhop_ire = ire2;
3262 	}
3263 	if (nhop_ire == NULL)
3264 		return;
3265 
3266 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3267 
3268 	src = ipha->ipha_src;
3269 
3270 	/*
3271 	 * We look at the interface ire for the nexthop,
3272 	 * to see if ipha_src is in the same subnet
3273 	 * as the nexthop.
3274 	 */
3275 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3276 		/*
3277 		 * The source is directly connected.
3278 		 */
3279 		mp1 = copymsg(mp);
3280 		if (mp1 != NULL) {
3281 			icmp_send_redirect(mp1, nhop, ira);
3282 		}
3283 	}
3284 	ire_refrele(nhop_ire);
3285 }
3286 
3287 /*
3288  * Generate an ICMP redirect message.
3289  */
3290 static void
3291 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3292 {
3293 	icmph_t	icmph;
3294 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3295 
3296 	mp = icmp_pkt_err_ok(mp, ira);
3297 	if (mp == NULL)
3298 		return;
3299 
3300 	bzero(&icmph, sizeof (icmph_t));
3301 	icmph.icmph_type = ICMP_REDIRECT;
3302 	icmph.icmph_code = 1;
3303 	icmph.icmph_rd_gateway = gateway;
3304 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3305 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3306 }
3307 
3308 /*
3309  * Generate an ICMP time exceeded message.
3310  */
3311 void
3312 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3313 {
3314 	icmph_t	icmph;
3315 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3316 
3317 	mp = icmp_pkt_err_ok(mp, ira);
3318 	if (mp == NULL)
3319 		return;
3320 
3321 	bzero(&icmph, sizeof (icmph_t));
3322 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3323 	icmph.icmph_code = code;
3324 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3325 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3326 }
3327 
3328 /*
3329  * Generate an ICMP unreachable message.
3330  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3331  * constructed by the caller.
3332  */
3333 void
3334 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3335 {
3336 	icmph_t	icmph;
3337 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3338 
3339 	mp = icmp_pkt_err_ok(mp, ira);
3340 	if (mp == NULL)
3341 		return;
3342 
3343 	bzero(&icmph, sizeof (icmph_t));
3344 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3345 	icmph.icmph_code = code;
3346 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3347 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3348 }
3349 
3350 /*
3351  * Latch in the IPsec state for a stream based the policy in the listener
3352  * and the actions in the ip_recv_attr_t.
3353  * Called directly from TCP and SCTP.
3354  */
3355 boolean_t
3356 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3357 {
3358 	ASSERT(lconnp->conn_policy != NULL);
3359 	ASSERT(connp->conn_policy == NULL);
3360 
3361 	IPPH_REFHOLD(lconnp->conn_policy);
3362 	connp->conn_policy = lconnp->conn_policy;
3363 
3364 	if (ira->ira_ipsec_action != NULL) {
3365 		if (connp->conn_latch == NULL) {
3366 			connp->conn_latch = iplatch_create();
3367 			if (connp->conn_latch == NULL)
3368 				return (B_FALSE);
3369 		}
3370 		ipsec_latch_inbound(connp, ira);
3371 	}
3372 	return (B_TRUE);
3373 }
3374 
3375 /*
3376  * Verify whether or not the IP address is a valid local address.
3377  * Could be a unicast, including one for a down interface.
3378  * If allow_mcbc then a multicast or broadcast address is also
3379  * acceptable.
3380  *
3381  * In the case of a broadcast/multicast address, however, the
3382  * upper protocol is expected to reset the src address
3383  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3384  * no packets are emitted with broadcast/multicast address as
3385  * source address (that violates hosts requirements RFC 1122)
3386  * The addresses valid for bind are:
3387  *	(1) - INADDR_ANY (0)
3388  *	(2) - IP address of an UP interface
3389  *	(3) - IP address of a DOWN interface
3390  *	(4) - valid local IP broadcast addresses. In this case
3391  *	the conn will only receive packets destined to
3392  *	the specified broadcast address.
3393  *	(5) - a multicast address. In this case
3394  *	the conn will only receive packets destined to
3395  *	the specified multicast address. Note: the
3396  *	application still has to issue an
3397  *	IP_ADD_MEMBERSHIP socket option.
3398  *
3399  * In all the above cases, the bound address must be valid in the current zone.
3400  * When the address is loopback, multicast or broadcast, there might be many
3401  * matching IREs so bind has to look up based on the zone.
3402  */
3403 ip_laddr_t
3404 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3405     ip_stack_t *ipst, boolean_t allow_mcbc)
3406 {
3407 	ire_t *src_ire;
3408 
3409 	ASSERT(src_addr != INADDR_ANY);
3410 
3411 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3412 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3413 
3414 	/*
3415 	 * If an address other than in6addr_any is requested,
3416 	 * we verify that it is a valid address for bind
3417 	 * Note: Following code is in if-else-if form for
3418 	 * readability compared to a condition check.
3419 	 */
3420 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3421 		/*
3422 		 * (2) Bind to address of local UP interface
3423 		 */
3424 		ire_refrele(src_ire);
3425 		return (IPVL_UNICAST_UP);
3426 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3427 		/*
3428 		 * (4) Bind to broadcast address
3429 		 */
3430 		ire_refrele(src_ire);
3431 		if (allow_mcbc)
3432 			return (IPVL_BCAST);
3433 		else
3434 			return (IPVL_BAD);
3435 	} else if (CLASSD(src_addr)) {
3436 		/* (5) bind to multicast address. */
3437 		if (src_ire != NULL)
3438 			ire_refrele(src_ire);
3439 
3440 		if (allow_mcbc)
3441 			return (IPVL_MCAST);
3442 		else
3443 			return (IPVL_BAD);
3444 	} else {
3445 		ipif_t *ipif;
3446 
3447 		/*
3448 		 * (3) Bind to address of local DOWN interface?
3449 		 * (ipif_lookup_addr() looks up all interfaces
3450 		 * but we do not get here for UP interfaces
3451 		 * - case (2) above)
3452 		 */
3453 		if (src_ire != NULL)
3454 			ire_refrele(src_ire);
3455 
3456 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3457 		if (ipif == NULL)
3458 			return (IPVL_BAD);
3459 
3460 		/* Not a useful source? */
3461 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3462 			ipif_refrele(ipif);
3463 			return (IPVL_BAD);
3464 		}
3465 		ipif_refrele(ipif);
3466 		return (IPVL_UNICAST_DOWN);
3467 	}
3468 }
3469 
3470 /*
3471  * Insert in the bind fanout for IPv4 and IPv6.
3472  * The caller should already have used ip_laddr_verify_v*() before calling
3473  * this.
3474  */
3475 int
3476 ip_laddr_fanout_insert(conn_t *connp)
3477 {
3478 	int		error;
3479 
3480 	/*
3481 	 * Allow setting new policies. For example, disconnects result
3482 	 * in us being called. As we would have set conn_policy_cached
3483 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3484 	 * can change after the disconnect.
3485 	 */
3486 	connp->conn_policy_cached = B_FALSE;
3487 
3488 	error = ipcl_bind_insert(connp);
3489 	if (error != 0) {
3490 		if (connp->conn_anon_port) {
3491 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3492 			    connp->conn_mlp_type, connp->conn_proto,
3493 			    ntohs(connp->conn_lport), B_FALSE);
3494 		}
3495 		connp->conn_mlp_type = mlptSingle;
3496 	}
3497 	return (error);
3498 }
3499 
3500 /*
3501  * Verify that both the source and destination addresses are valid. If
3502  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3503  * i.e. have no route to it.  Protocols like TCP want to verify destination
3504  * reachability, while tunnels do not.
3505  *
3506  * Determine the route, the interface, and (optionally) the source address
3507  * to use to reach a given destination.
3508  * Note that we allow connect to broadcast and multicast addresses when
3509  * IPDF_ALLOW_MCBC is set.
3510  * first_hop and dst_addr are normally the same, but if source routing
3511  * they will differ; in that case the first_hop is what we'll use for the
3512  * routing lookup but the dce and label checks will be done on dst_addr,
3513  *
3514  * If uinfo is set, then we fill in the best available information
3515  * we have for the destination. This is based on (in priority order) any
3516  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3517  * ill_mtu.
3518  *
3519  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3520  * always do the label check on dst_addr.
3521  */
3522 int
3523 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3524     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3525 {
3526 	ire_t		*ire = NULL;
3527 	int		error = 0;
3528 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3529 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3530 	ip_stack_t	*ipst = ixa->ixa_ipst;
3531 	dce_t		*dce;
3532 	uint_t		pmtu;
3533 	uint_t		generation;
3534 	nce_t		*nce;
3535 	ill_t		*ill = NULL;
3536 	boolean_t	multirt = B_FALSE;
3537 
3538 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3539 
3540 	/*
3541 	 * We never send to zero; the ULPs map it to the loopback address.
3542 	 * We can't allow it since we use zero to mean unitialized in some
3543 	 * places.
3544 	 */
3545 	ASSERT(dst_addr != INADDR_ANY);
3546 
3547 	if (is_system_labeled()) {
3548 		ts_label_t *tsl = NULL;
3549 
3550 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3551 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3552 		if (error != 0)
3553 			return (error);
3554 		if (tsl != NULL) {
3555 			/* Update the label */
3556 			ip_xmit_attr_replace_tsl(ixa, tsl);
3557 		}
3558 	}
3559 
3560 	setsrc = INADDR_ANY;
3561 	/*
3562 	 * Select a route; For IPMP interfaces, we would only select
3563 	 * a "hidden" route (i.e., going through a specific under_ill)
3564 	 * if ixa_ifindex has been specified.
3565 	 */
3566 	ire = ip_select_route_v4(firsthop, ixa, &generation, &setsrc, &error,
3567 	    &multirt);
3568 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3569 	if (error != 0)
3570 		goto bad_addr;
3571 
3572 	/*
3573 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3574 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3575 	 * Otherwise the destination needn't be reachable.
3576 	 *
3577 	 * If we match on a reject or black hole, then we've got a
3578 	 * local failure.  May as well fail out the connect() attempt,
3579 	 * since it's never going to succeed.
3580 	 */
3581 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3582 		/*
3583 		 * If we're verifying destination reachability, we always want
3584 		 * to complain here.
3585 		 *
3586 		 * If we're not verifying destination reachability but the
3587 		 * destination has a route, we still want to fail on the
3588 		 * temporary address and broadcast address tests.
3589 		 *
3590 		 * In both cases do we let the code continue so some reasonable
3591 		 * information is returned to the caller. That enables the
3592 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3593 		 * use the generation mismatch path to check for the unreachable
3594 		 * case thereby avoiding any specific check in the main path.
3595 		 */
3596 		ASSERT(generation == IRE_GENERATION_VERIFY);
3597 		if (flags & IPDF_VERIFY_DST) {
3598 			/*
3599 			 * Set errno but continue to set up ixa_ire to be
3600 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3601 			 * That allows callers to use ip_output to get an
3602 			 * ICMP error back.
3603 			 */
3604 			if (!(ire->ire_type & IRE_HOST))
3605 				error = ENETUNREACH;
3606 			else
3607 				error = EHOSTUNREACH;
3608 		}
3609 	}
3610 
3611 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3612 	    !(flags & IPDF_ALLOW_MCBC)) {
3613 		ire_refrele(ire);
3614 		ire = ire_reject(ipst, B_FALSE);
3615 		generation = IRE_GENERATION_VERIFY;
3616 		error = ENETUNREACH;
3617 	}
3618 
3619 	/* Cache things */
3620 	if (ixa->ixa_ire != NULL)
3621 		ire_refrele_notr(ixa->ixa_ire);
3622 #ifdef DEBUG
3623 	ire_refhold_notr(ire);
3624 	ire_refrele(ire);
3625 #endif
3626 	ixa->ixa_ire = ire;
3627 	ixa->ixa_ire_generation = generation;
3628 
3629 	/*
3630 	 * For multicast with multirt we have a flag passed back from
3631 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3632 	 * possible multicast address.
3633 	 * We also need a flag for multicast since we can't check
3634 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3635 	 */
3636 	if (multirt) {
3637 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3638 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3639 	} else {
3640 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3641 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3642 	}
3643 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3644 		/* Get an nce to cache. */
3645 		nce = ire_to_nce(ire, firsthop, NULL);
3646 		if (nce == NULL) {
3647 			/* Allocation failure? */
3648 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3649 		} else {
3650 			if (ixa->ixa_nce != NULL)
3651 				nce_refrele(ixa->ixa_nce);
3652 			ixa->ixa_nce = nce;
3653 		}
3654 	}
3655 
3656 	/*
3657 	 * We use use ire_nexthop_ill to avoid the under ipmp
3658 	 * interface for source address selection. Note that for ipmp
3659 	 * probe packets, ixa_ifindex would have been specified, and
3660 	 * the ip_select_route() invocation would have picked an ire
3661 	 * will ire_ill pointing at an under interface.
3662 	 */
3663 	ill = ire_nexthop_ill(ire);
3664 
3665 	/*
3666 	 * If the source address is a loopback address, the
3667 	 * destination had best be local or multicast.
3668 	 * If we are sending to an IRE_LOCAL using a loopback source then
3669 	 * it had better be the same zoneid.
3670 	 */
3671 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3672 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3673 			ire = NULL;	/* Stored in ixa_ire */
3674 			error = EADDRNOTAVAIL;
3675 			goto bad_addr;
3676 		}
3677 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3678 			ire = NULL;	/* Stored in ixa_ire */
3679 			error = EADDRNOTAVAIL;
3680 			goto bad_addr;
3681 		}
3682 	}
3683 	if (ire->ire_type & IRE_BROADCAST) {
3684 		/*
3685 		 * If the ULP didn't have a specified source, then we
3686 		 * make sure we reselect the source when sending
3687 		 * broadcasts out different interfaces.
3688 		 */
3689 		if (flags & IPDF_SELECT_SRC)
3690 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3691 		else
3692 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3693 	}
3694 
3695 	/*
3696 	 * Does the caller want us to pick a source address?
3697 	 */
3698 	if (flags & IPDF_SELECT_SRC) {
3699 		ipaddr_t	src_addr;
3700 
3701 		/* If unreachable we have no ill but need some source */
3702 		if (ill == NULL) {
3703 			src_addr = htonl(INADDR_LOOPBACK);
3704 			/* Make sure we look for a better source address */
3705 			generation = SRC_GENERATION_VERIFY;
3706 		} else {
3707 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3708 			    ixa->ixa_multicast_ifaddr, zoneid,
3709 			    ipst, &src_addr, &generation, NULL);
3710 			if (error != 0) {
3711 				ire = NULL;	/* Stored in ixa_ire */
3712 				goto bad_addr;
3713 			}
3714 		}
3715 
3716 		/*
3717 		 * We allow the source address to to down.
3718 		 * However, we check that we don't use the loopback address
3719 		 * as a source when sending out on the wire.
3720 		 */
3721 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3722 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3723 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3724 			ire = NULL;	/* Stored in ixa_ire */
3725 			error = EADDRNOTAVAIL;
3726 			goto bad_addr;
3727 		}
3728 
3729 		*src_addrp = src_addr;
3730 		ixa->ixa_src_generation = generation;
3731 	}
3732 
3733 	if (flags & IPDF_UNIQUE_DCE) {
3734 		/* Fallback to the default dce if allocation fails */
3735 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3736 		if (dce != NULL)
3737 			generation = dce->dce_generation;
3738 		else
3739 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3740 	} else {
3741 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3742 	}
3743 	ASSERT(dce != NULL);
3744 	if (ixa->ixa_dce != NULL)
3745 		dce_refrele_notr(ixa->ixa_dce);
3746 #ifdef DEBUG
3747 	dce_refhold_notr(dce);
3748 	dce_refrele(dce);
3749 #endif
3750 	ixa->ixa_dce = dce;
3751 	ixa->ixa_dce_generation = generation;
3752 
3753 	/*
3754 	 * Make sure we don't leave an unreachable ixa_nce in place
3755 	 * since ip_select_route is used when we unplumb i.e., remove
3756 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3757 	 */
3758 	nce = ixa->ixa_nce;
3759 	if (nce != NULL && nce->nce_is_condemned) {
3760 		nce_refrele(nce);
3761 		ixa->ixa_nce = NULL;
3762 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3763 	}
3764 
3765 	/*
3766 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3767 	 * However, we can't do it for IPv4 multicast or broadcast.
3768 	 */
3769 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3770 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3771 
3772 	/*
3773 	 * Set initial value for fragmentation limit. Either conn_ip_output
3774 	 * or ULP might updates it when there are routing changes.
3775 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3776 	 */
3777 	pmtu = ip_get_pmtu(ixa);
3778 	ixa->ixa_fragsize = pmtu;
3779 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3780 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3781 		ixa->ixa_pmtu = pmtu;
3782 
3783 	/*
3784 	 * Extract information useful for some transports.
3785 	 * First we look for DCE metrics. Then we take what we have in
3786 	 * the metrics in the route, where the offlink is used if we have
3787 	 * one.
3788 	 */
3789 	if (uinfo != NULL) {
3790 		bzero(uinfo, sizeof (*uinfo));
3791 
3792 		if (dce->dce_flags & DCEF_UINFO)
3793 			*uinfo = dce->dce_uinfo;
3794 
3795 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3796 
3797 		/* Allow ire_metrics to decrease the path MTU from above */
3798 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3799 			uinfo->iulp_mtu = pmtu;
3800 
3801 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3802 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3803 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3804 	}
3805 
3806 	if (ill != NULL)
3807 		ill_refrele(ill);
3808 
3809 	return (error);
3810 
3811 bad_addr:
3812 	if (ire != NULL)
3813 		ire_refrele(ire);
3814 
3815 	if (ill != NULL)
3816 		ill_refrele(ill);
3817 
3818 	/*
3819 	 * Make sure we don't leave an unreachable ixa_nce in place
3820 	 * since ip_select_route is used when we unplumb i.e., remove
3821 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3822 	 */
3823 	nce = ixa->ixa_nce;
3824 	if (nce != NULL && nce->nce_is_condemned) {
3825 		nce_refrele(nce);
3826 		ixa->ixa_nce = NULL;
3827 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3828 	}
3829 
3830 	return (error);
3831 }
3832 
3833 
3834 /*
3835  * Get the base MTU for the case when path MTU discovery is not used.
3836  * Takes the MTU of the IRE into account.
3837  */
3838 uint_t
3839 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3840 {
3841 	uint_t mtu = ill->ill_mtu;
3842 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3843 
3844 	if (iremtu != 0 && iremtu < mtu)
3845 		mtu = iremtu;
3846 
3847 	return (mtu);
3848 }
3849 
3850 /*
3851  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3852  * Assumes that ixa_ire, dce, and nce have already been set up.
3853  *
3854  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3855  * We avoid path MTU discovery if it is disabled with ndd.
3856  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3857  *
3858  * NOTE: We also used to turn it off for source routed packets. That
3859  * is no longer required since the dce is per final destination.
3860  */
3861 uint_t
3862 ip_get_pmtu(ip_xmit_attr_t *ixa)
3863 {
3864 	ip_stack_t	*ipst = ixa->ixa_ipst;
3865 	dce_t		*dce;
3866 	nce_t		*nce;
3867 	ire_t		*ire;
3868 	uint_t		pmtu;
3869 
3870 	ire = ixa->ixa_ire;
3871 	dce = ixa->ixa_dce;
3872 	nce = ixa->ixa_nce;
3873 
3874 	/*
3875 	 * If path MTU discovery has been turned off by ndd, then we ignore
3876 	 * any dce_pmtu and for IPv4 we will not set DF.
3877 	 */
3878 	if (!ipst->ips_ip_path_mtu_discovery)
3879 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3880 
3881 	pmtu = IP_MAXPACKET;
3882 	/*
3883 	 * Decide whether whether IPv4 sets DF
3884 	 * For IPv6 "no DF" means to use the 1280 mtu
3885 	 */
3886 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3887 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3888 	} else {
3889 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3890 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3891 			pmtu = IPV6_MIN_MTU;
3892 	}
3893 
3894 	/* Check if the PMTU is to old before we use it */
3895 	if ((dce->dce_flags & DCEF_PMTU) &&
3896 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3897 	    ipst->ips_ip_pathmtu_interval) {
3898 		/*
3899 		 * Older than 20 minutes. Drop the path MTU information.
3900 		 */
3901 		mutex_enter(&dce->dce_lock);
3902 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3903 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3904 		mutex_exit(&dce->dce_lock);
3905 		dce_increment_generation(dce);
3906 	}
3907 
3908 	/* The metrics on the route can lower the path MTU */
3909 	if (ire->ire_metrics.iulp_mtu != 0 &&
3910 	    ire->ire_metrics.iulp_mtu < pmtu)
3911 		pmtu = ire->ire_metrics.iulp_mtu;
3912 
3913 	/*
3914 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3915 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3916 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3917 	 */
3918 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3919 		if (dce->dce_flags & DCEF_PMTU) {
3920 			if (dce->dce_pmtu < pmtu)
3921 				pmtu = dce->dce_pmtu;
3922 
3923 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3924 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3925 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3926 			} else {
3927 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3928 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3929 			}
3930 		} else {
3931 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3932 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3933 		}
3934 	}
3935 
3936 	/*
3937 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3938 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3939 	 * mtu as IRE_LOOPBACK.
3940 	 */
3941 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3942 		uint_t loopback_mtu;
3943 
3944 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3945 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3946 
3947 		if (loopback_mtu < pmtu)
3948 			pmtu = loopback_mtu;
3949 	} else if (nce != NULL) {
3950 		/*
3951 		 * Make sure we don't exceed the interface MTU.
3952 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3953 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3954 		 * to tell the transport something larger than zero.
3955 		 */
3956 		if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3957 			pmtu = nce->nce_common->ncec_ill->ill_mtu;
3958 		if (nce->nce_common->ncec_ill != nce->nce_ill &&
3959 		    nce->nce_ill->ill_mtu < pmtu) {
3960 			/*
3961 			 * for interfaces in an IPMP group, the mtu of
3962 			 * the nce_ill (under_ill) could be different
3963 			 * from the mtu of the ncec_ill, so we take the
3964 			 * min of the two.
3965 			 */
3966 			pmtu = nce->nce_ill->ill_mtu;
3967 		}
3968 	}
3969 
3970 	/*
3971 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3972 	 * Only applies to IPv6.
3973 	 */
3974 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3975 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3976 			switch (ixa->ixa_use_min_mtu) {
3977 			case IPV6_USE_MIN_MTU_MULTICAST:
3978 				if (ire->ire_type & IRE_MULTICAST)
3979 					pmtu = IPV6_MIN_MTU;
3980 				break;
3981 			case IPV6_USE_MIN_MTU_ALWAYS:
3982 				pmtu = IPV6_MIN_MTU;
3983 				break;
3984 			case IPV6_USE_MIN_MTU_NEVER:
3985 				break;
3986 			}
3987 		} else {
3988 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3989 			if (ire->ire_type & IRE_MULTICAST)
3990 				pmtu = IPV6_MIN_MTU;
3991 		}
3992 	}
3993 
3994 	/*
3995 	 * After receiving an ICMPv6 "packet too big" message with a
3996 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3997 	 * will insert a 8-byte fragment header in every packet. We compensate
3998 	 * for those cases by returning a smaller path MTU to the ULP.
3999 	 *
4000 	 * In the case of CGTP then ip_output will add a fragment header.
4001 	 * Make sure there is room for it by telling a smaller number
4002 	 * to the transport.
4003 	 *
4004 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
4005 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
4006 	 * which is the size of the packets it can send.
4007 	 */
4008 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
4009 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
4010 		    (ire->ire_flags & RTF_MULTIRT) ||
4011 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
4012 			pmtu -= sizeof (ip6_frag_t);
4013 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
4014 		}
4015 	}
4016 
4017 	return (pmtu);
4018 }
4019 
4020 /*
4021  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4022  * the final piece where we don't.  Return a pointer to the first mblk in the
4023  * result, and update the pointer to the next mblk to chew on.  If anything
4024  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4025  * NULL pointer.
4026  */
4027 mblk_t *
4028 ip_carve_mp(mblk_t **mpp, ssize_t len)
4029 {
4030 	mblk_t	*mp0;
4031 	mblk_t	*mp1;
4032 	mblk_t	*mp2;
4033 
4034 	if (!len || !mpp || !(mp0 = *mpp))
4035 		return (NULL);
4036 	/* If we aren't going to consume the first mblk, we need a dup. */
4037 	if (mp0->b_wptr - mp0->b_rptr > len) {
4038 		mp1 = dupb(mp0);
4039 		if (mp1) {
4040 			/* Partition the data between the two mblks. */
4041 			mp1->b_wptr = mp1->b_rptr + len;
4042 			mp0->b_rptr = mp1->b_wptr;
4043 			/*
4044 			 * after adjustments if mblk not consumed is now
4045 			 * unaligned, try to align it. If this fails free
4046 			 * all messages and let upper layer recover.
4047 			 */
4048 			if (!OK_32PTR(mp0->b_rptr)) {
4049 				if (!pullupmsg(mp0, -1)) {
4050 					freemsg(mp0);
4051 					freemsg(mp1);
4052 					*mpp = NULL;
4053 					return (NULL);
4054 				}
4055 			}
4056 		}
4057 		return (mp1);
4058 	}
4059 	/* Eat through as many mblks as we need to get len bytes. */
4060 	len -= mp0->b_wptr - mp0->b_rptr;
4061 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4062 		if (mp2->b_wptr - mp2->b_rptr > len) {
4063 			/*
4064 			 * We won't consume the entire last mblk.  Like
4065 			 * above, dup and partition it.
4066 			 */
4067 			mp1->b_cont = dupb(mp2);
4068 			mp1 = mp1->b_cont;
4069 			if (!mp1) {
4070 				/*
4071 				 * Trouble.  Rather than go to a lot of
4072 				 * trouble to clean up, we free the messages.
4073 				 * This won't be any worse than losing it on
4074 				 * the wire.
4075 				 */
4076 				freemsg(mp0);
4077 				freemsg(mp2);
4078 				*mpp = NULL;
4079 				return (NULL);
4080 			}
4081 			mp1->b_wptr = mp1->b_rptr + len;
4082 			mp2->b_rptr = mp1->b_wptr;
4083 			/*
4084 			 * after adjustments if mblk not consumed is now
4085 			 * unaligned, try to align it. If this fails free
4086 			 * all messages and let upper layer recover.
4087 			 */
4088 			if (!OK_32PTR(mp2->b_rptr)) {
4089 				if (!pullupmsg(mp2, -1)) {
4090 					freemsg(mp0);
4091 					freemsg(mp2);
4092 					*mpp = NULL;
4093 					return (NULL);
4094 				}
4095 			}
4096 			*mpp = mp2;
4097 			return (mp0);
4098 		}
4099 		/* Decrement len by the amount we just got. */
4100 		len -= mp2->b_wptr - mp2->b_rptr;
4101 	}
4102 	/*
4103 	 * len should be reduced to zero now.  If not our caller has
4104 	 * screwed up.
4105 	 */
4106 	if (len) {
4107 		/* Shouldn't happen! */
4108 		freemsg(mp0);
4109 		*mpp = NULL;
4110 		return (NULL);
4111 	}
4112 	/*
4113 	 * We consumed up to exactly the end of an mblk.  Detach the part
4114 	 * we are returning from the rest of the chain.
4115 	 */
4116 	mp1->b_cont = NULL;
4117 	*mpp = mp2;
4118 	return (mp0);
4119 }
4120 
4121 /* The ill stream is being unplumbed. Called from ip_close */
4122 int
4123 ip_modclose(ill_t *ill)
4124 {
4125 	boolean_t success;
4126 	ipsq_t	*ipsq;
4127 	ipif_t	*ipif;
4128 	queue_t	*q = ill->ill_rq;
4129 	ip_stack_t	*ipst = ill->ill_ipst;
4130 	int	i;
4131 	arl_ill_common_t *ai = ill->ill_common;
4132 
4133 	/*
4134 	 * The punlink prior to this may have initiated a capability
4135 	 * negotiation. But ipsq_enter will block until that finishes or
4136 	 * times out.
4137 	 */
4138 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
4139 
4140 	/*
4141 	 * Open/close/push/pop is guaranteed to be single threaded
4142 	 * per stream by STREAMS. FS guarantees that all references
4143 	 * from top are gone before close is called. So there can't
4144 	 * be another close thread that has set CONDEMNED on this ill.
4145 	 * and cause ipsq_enter to return failure.
4146 	 */
4147 	ASSERT(success);
4148 	ipsq = ill->ill_phyint->phyint_ipsq;
4149 
4150 	/*
4151 	 * Mark it condemned. No new reference will be made to this ill.
4152 	 * Lookup functions will return an error. Threads that try to
4153 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4154 	 * that the refcnt will drop down to zero.
4155 	 */
4156 	mutex_enter(&ill->ill_lock);
4157 	ill->ill_state_flags |= ILL_CONDEMNED;
4158 	for (ipif = ill->ill_ipif; ipif != NULL;
4159 	    ipif = ipif->ipif_next) {
4160 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4161 	}
4162 	/*
4163 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4164 	 * returns  error if ILL_CONDEMNED is set
4165 	 */
4166 	cv_broadcast(&ill->ill_cv);
4167 	mutex_exit(&ill->ill_lock);
4168 
4169 	/*
4170 	 * Send all the deferred DLPI messages downstream which came in
4171 	 * during the small window right before ipsq_enter(). We do this
4172 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4173 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4174 	 */
4175 	ill_dlpi_send_deferred(ill);
4176 
4177 	/*
4178 	 * Shut down fragmentation reassembly.
4179 	 * ill_frag_timer won't start a timer again.
4180 	 * Now cancel any existing timer
4181 	 */
4182 	(void) untimeout(ill->ill_frag_timer_id);
4183 	(void) ill_frag_timeout(ill, 0);
4184 
4185 	/*
4186 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4187 	 * this ill. Then wait for the refcnts to drop to zero.
4188 	 * ill_is_freeable checks whether the ill is really quiescent.
4189 	 * Then make sure that threads that are waiting to enter the
4190 	 * ipsq have seen the error returned by ipsq_enter and have
4191 	 * gone away. Then we call ill_delete_tail which does the
4192 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4193 	 */
4194 	ill_delete(ill);
4195 	mutex_enter(&ill->ill_lock);
4196 	while (!ill_is_freeable(ill))
4197 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4198 
4199 	while (ill->ill_waiters)
4200 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4201 
4202 	mutex_exit(&ill->ill_lock);
4203 
4204 	/*
4205 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4206 	 * it held until the end of the function since the cleanup
4207 	 * below needs to be able to use the ip_stack_t.
4208 	 */
4209 	netstack_hold(ipst->ips_netstack);
4210 
4211 	/* qprocsoff is done via ill_delete_tail */
4212 	ill_delete_tail(ill);
4213 	/*
4214 	 * synchronously wait for arp stream to unbind. After this, we
4215 	 * cannot get any data packets up from the driver.
4216 	 */
4217 	arp_unbind_complete(ill);
4218 	ASSERT(ill->ill_ipst == NULL);
4219 
4220 	/*
4221 	 * Walk through all conns and qenable those that have queued data.
4222 	 * Close synchronization needs this to
4223 	 * be done to ensure that all upper layers blocked
4224 	 * due to flow control to the closing device
4225 	 * get unblocked.
4226 	 */
4227 	ip1dbg(("ip_wsrv: walking\n"));
4228 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4229 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4230 	}
4231 
4232 	/*
4233 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4234 	 * stream is being torn down before ARP was plumbed (e.g.,
4235 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4236 	 * an error
4237 	 */
4238 	if (ai != NULL) {
4239 		ASSERT(!ill->ill_isv6);
4240 		mutex_enter(&ai->ai_lock);
4241 		ai->ai_ill = NULL;
4242 		if (ai->ai_arl == NULL) {
4243 			mutex_destroy(&ai->ai_lock);
4244 			kmem_free(ai, sizeof (*ai));
4245 		} else {
4246 			cv_signal(&ai->ai_ill_unplumb_done);
4247 			mutex_exit(&ai->ai_lock);
4248 		}
4249 	}
4250 
4251 	mutex_enter(&ipst->ips_ip_mi_lock);
4252 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4253 	mutex_exit(&ipst->ips_ip_mi_lock);
4254 
4255 	/*
4256 	 * credp could be null if the open didn't succeed and ip_modopen
4257 	 * itself calls ip_close.
4258 	 */
4259 	if (ill->ill_credp != NULL)
4260 		crfree(ill->ill_credp);
4261 
4262 	mutex_destroy(&ill->ill_saved_ire_lock);
4263 	mutex_destroy(&ill->ill_lock);
4264 	rw_destroy(&ill->ill_mcast_lock);
4265 	mutex_destroy(&ill->ill_mcast_serializer);
4266 	list_destroy(&ill->ill_nce);
4267 
4268 	/*
4269 	 * Now we are done with the module close pieces that
4270 	 * need the netstack_t.
4271 	 */
4272 	netstack_rele(ipst->ips_netstack);
4273 
4274 	mi_close_free((IDP)ill);
4275 	q->q_ptr = WR(q)->q_ptr = NULL;
4276 
4277 	ipsq_exit(ipsq);
4278 
4279 	return (0);
4280 }
4281 
4282 /*
4283  * This is called as part of close() for IP, UDP, ICMP, and RTS
4284  * in order to quiesce the conn.
4285  */
4286 void
4287 ip_quiesce_conn(conn_t *connp)
4288 {
4289 	boolean_t	drain_cleanup_reqd = B_FALSE;
4290 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4291 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4292 	ip_stack_t	*ipst;
4293 
4294 	ASSERT(!IPCL_IS_TCP(connp));
4295 	ipst = connp->conn_netstack->netstack_ip;
4296 
4297 	/*
4298 	 * Mark the conn as closing, and this conn must not be
4299 	 * inserted in future into any list. Eg. conn_drain_insert(),
4300 	 * won't insert this conn into the conn_drain_list.
4301 	 *
4302 	 * conn_idl, and conn_ilg cannot get set henceforth.
4303 	 */
4304 	mutex_enter(&connp->conn_lock);
4305 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4306 	connp->conn_state_flags |= CONN_CLOSING;
4307 	if (connp->conn_idl != NULL)
4308 		drain_cleanup_reqd = B_TRUE;
4309 	if (connp->conn_oper_pending_ill != NULL)
4310 		conn_ioctl_cleanup_reqd = B_TRUE;
4311 	if (connp->conn_dhcpinit_ill != NULL) {
4312 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4313 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4314 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4315 		connp->conn_dhcpinit_ill = NULL;
4316 	}
4317 	if (connp->conn_ilg != NULL)
4318 		ilg_cleanup_reqd = B_TRUE;
4319 	mutex_exit(&connp->conn_lock);
4320 
4321 	if (conn_ioctl_cleanup_reqd)
4322 		conn_ioctl_cleanup(connp);
4323 
4324 	if (is_system_labeled() && connp->conn_anon_port) {
4325 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4326 		    connp->conn_mlp_type, connp->conn_proto,
4327 		    ntohs(connp->conn_lport), B_FALSE);
4328 		connp->conn_anon_port = 0;
4329 	}
4330 	connp->conn_mlp_type = mlptSingle;
4331 
4332 	/*
4333 	 * Remove this conn from any fanout list it is on.
4334 	 * and then wait for any threads currently operating
4335 	 * on this endpoint to finish
4336 	 */
4337 	ipcl_hash_remove(connp);
4338 
4339 	/*
4340 	 * Remove this conn from the drain list, and do
4341 	 * any other cleanup that may be required.
4342 	 * (Only non-tcp conns may have a non-null conn_idl.
4343 	 * TCP conns are never flow controlled, and
4344 	 * conn_idl will be null)
4345 	 */
4346 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4347 		mutex_enter(&connp->conn_idl->idl_lock);
4348 		conn_drain_tail(connp, B_TRUE);
4349 		mutex_exit(&connp->conn_idl->idl_lock);
4350 	}
4351 
4352 	if (connp == ipst->ips_ip_g_mrouter)
4353 		(void) ip_mrouter_done(ipst);
4354 
4355 	if (ilg_cleanup_reqd)
4356 		ilg_delete_all(connp);
4357 
4358 	/*
4359 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4360 	 * callers from write side can't be there now because close
4361 	 * is in progress. The only other caller is ipcl_walk
4362 	 * which checks for the condemned flag.
4363 	 */
4364 	mutex_enter(&connp->conn_lock);
4365 	connp->conn_state_flags |= CONN_CONDEMNED;
4366 	while (connp->conn_ref != 1)
4367 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4368 	connp->conn_state_flags |= CONN_QUIESCED;
4369 	mutex_exit(&connp->conn_lock);
4370 }
4371 
4372 /* ARGSUSED */
4373 int
4374 ip_close(queue_t *q, int flags)
4375 {
4376 	conn_t		*connp;
4377 
4378 	/*
4379 	 * Call the appropriate delete routine depending on whether this is
4380 	 * a module or device.
4381 	 */
4382 	if (WR(q)->q_next != NULL) {
4383 		/* This is a module close */
4384 		return (ip_modclose((ill_t *)q->q_ptr));
4385 	}
4386 
4387 	connp = q->q_ptr;
4388 	ip_quiesce_conn(connp);
4389 
4390 	qprocsoff(q);
4391 
4392 	/*
4393 	 * Now we are truly single threaded on this stream, and can
4394 	 * delete the things hanging off the connp, and finally the connp.
4395 	 * We removed this connp from the fanout list, it cannot be
4396 	 * accessed thru the fanouts, and we already waited for the
4397 	 * conn_ref to drop to 0. We are already in close, so
4398 	 * there cannot be any other thread from the top. qprocsoff
4399 	 * has completed, and service has completed or won't run in
4400 	 * future.
4401 	 */
4402 	ASSERT(connp->conn_ref == 1);
4403 
4404 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4405 
4406 	connp->conn_ref--;
4407 	ipcl_conn_destroy(connp);
4408 
4409 	q->q_ptr = WR(q)->q_ptr = NULL;
4410 	return (0);
4411 }
4412 
4413 /*
4414  * Wapper around putnext() so that ip_rts_request can merely use
4415  * conn_recv.
4416  */
4417 /*ARGSUSED2*/
4418 static void
4419 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4420 {
4421 	conn_t *connp = (conn_t *)arg1;
4422 
4423 	putnext(connp->conn_rq, mp);
4424 }
4425 
4426 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4427 /* ARGSUSED */
4428 static void
4429 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4430 {
4431 	freemsg(mp);
4432 }
4433 
4434 /*
4435  * Called when the module is about to be unloaded
4436  */
4437 void
4438 ip_ddi_destroy(void)
4439 {
4440 	tnet_fini();
4441 
4442 	icmp_ddi_g_destroy();
4443 	rts_ddi_g_destroy();
4444 	udp_ddi_g_destroy();
4445 	sctp_ddi_g_destroy();
4446 	tcp_ddi_g_destroy();
4447 	ilb_ddi_g_destroy();
4448 	dce_g_destroy();
4449 	ipsec_policy_g_destroy();
4450 	ipcl_g_destroy();
4451 	ip_net_g_destroy();
4452 	ip_ire_g_fini();
4453 	inet_minor_destroy(ip_minor_arena_sa);
4454 #if defined(_LP64)
4455 	inet_minor_destroy(ip_minor_arena_la);
4456 #endif
4457 
4458 #ifdef DEBUG
4459 	list_destroy(&ip_thread_list);
4460 	rw_destroy(&ip_thread_rwlock);
4461 	tsd_destroy(&ip_thread_data);
4462 #endif
4463 
4464 	netstack_unregister(NS_IP);
4465 }
4466 
4467 /*
4468  * First step in cleanup.
4469  */
4470 /* ARGSUSED */
4471 static void
4472 ip_stack_shutdown(netstackid_t stackid, void *arg)
4473 {
4474 	ip_stack_t *ipst = (ip_stack_t *)arg;
4475 
4476 #ifdef NS_DEBUG
4477 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4478 #endif
4479 
4480 	/*
4481 	 * Perform cleanup for special interfaces (loopback and IPMP).
4482 	 */
4483 	ip_interface_cleanup(ipst);
4484 
4485 	/*
4486 	 * The *_hook_shutdown()s start the process of notifying any
4487 	 * consumers that things are going away.... nothing is destroyed.
4488 	 */
4489 	ipv4_hook_shutdown(ipst);
4490 	ipv6_hook_shutdown(ipst);
4491 	arp_hook_shutdown(ipst);
4492 
4493 	mutex_enter(&ipst->ips_capab_taskq_lock);
4494 	ipst->ips_capab_taskq_quit = B_TRUE;
4495 	cv_signal(&ipst->ips_capab_taskq_cv);
4496 	mutex_exit(&ipst->ips_capab_taskq_lock);
4497 }
4498 
4499 /*
4500  * Free the IP stack instance.
4501  */
4502 static void
4503 ip_stack_fini(netstackid_t stackid, void *arg)
4504 {
4505 	ip_stack_t *ipst = (ip_stack_t *)arg;
4506 	int ret;
4507 
4508 #ifdef NS_DEBUG
4509 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4510 #endif
4511 	/*
4512 	 * At this point, all of the notifications that the events and
4513 	 * protocols are going away have been run, meaning that we can
4514 	 * now set about starting to clean things up.
4515 	 */
4516 	ipobs_fini(ipst);
4517 	ipv4_hook_destroy(ipst);
4518 	ipv6_hook_destroy(ipst);
4519 	arp_hook_destroy(ipst);
4520 	ip_net_destroy(ipst);
4521 
4522 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4523 	cv_destroy(&ipst->ips_capab_taskq_cv);
4524 
4525 	ipmp_destroy(ipst);
4526 	rw_destroy(&ipst->ips_srcid_lock);
4527 
4528 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4529 	ipst->ips_ip_mibkp = NULL;
4530 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4531 	ipst->ips_icmp_mibkp = NULL;
4532 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4533 	ipst->ips_ip_kstat = NULL;
4534 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4535 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4536 	ipst->ips_ip6_kstat = NULL;
4537 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4538 
4539 	nd_free(&ipst->ips_ip_g_nd);
4540 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
4541 	ipst->ips_param_arr = NULL;
4542 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
4543 	ipst->ips_ndp_arr = NULL;
4544 
4545 	dce_stack_destroy(ipst);
4546 	ip_mrouter_stack_destroy(ipst);
4547 
4548 	mutex_destroy(&ipst->ips_ip_mi_lock);
4549 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4550 	rw_destroy(&ipst->ips_ip_g_nd_lock);
4551 
4552 	ret = untimeout(ipst->ips_igmp_timeout_id);
4553 	if (ret == -1) {
4554 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4555 	} else {
4556 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4557 		ipst->ips_igmp_timeout_id = 0;
4558 	}
4559 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4560 	if (ret == -1) {
4561 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4562 	} else {
4563 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4564 		ipst->ips_igmp_slowtimeout_id = 0;
4565 	}
4566 	ret = untimeout(ipst->ips_mld_timeout_id);
4567 	if (ret == -1) {
4568 		ASSERT(ipst->ips_mld_timeout_id == 0);
4569 	} else {
4570 		ASSERT(ipst->ips_mld_timeout_id != 0);
4571 		ipst->ips_mld_timeout_id = 0;
4572 	}
4573 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4574 	if (ret == -1) {
4575 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4576 	} else {
4577 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4578 		ipst->ips_mld_slowtimeout_id = 0;
4579 	}
4580 
4581 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4582 	mutex_destroy(&ipst->ips_mld_timer_lock);
4583 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4584 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4585 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4586 	rw_destroy(&ipst->ips_ill_g_lock);
4587 
4588 	ip_ire_fini(ipst);
4589 	ip6_asp_free(ipst);
4590 	conn_drain_fini(ipst);
4591 	ipcl_destroy(ipst);
4592 
4593 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4594 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4595 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4596 	ipst->ips_ndp4 = NULL;
4597 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4598 	ipst->ips_ndp6 = NULL;
4599 
4600 	if (ipst->ips_loopback_ksp != NULL) {
4601 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4602 		ipst->ips_loopback_ksp = NULL;
4603 	}
4604 
4605 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4606 	ipst->ips_phyint_g_list = NULL;
4607 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4608 	ipst->ips_ill_g_heads = NULL;
4609 
4610 	ldi_ident_release(ipst->ips_ldi_ident);
4611 	kmem_free(ipst, sizeof (*ipst));
4612 }
4613 
4614 /*
4615  * This function is called from the TSD destructor, and is used to debug
4616  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4617  * details.
4618  */
4619 static void
4620 ip_thread_exit(void *phash)
4621 {
4622 	th_hash_t *thh = phash;
4623 
4624 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4625 	list_remove(&ip_thread_list, thh);
4626 	rw_exit(&ip_thread_rwlock);
4627 	mod_hash_destroy_hash(thh->thh_hash);
4628 	kmem_free(thh, sizeof (*thh));
4629 }
4630 
4631 /*
4632  * Called when the IP kernel module is loaded into the kernel
4633  */
4634 void
4635 ip_ddi_init(void)
4636 {
4637 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4638 
4639 	/*
4640 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4641 	 * initial devices: ip, ip6, tcp, tcp6.
4642 	 */
4643 	/*
4644 	 * If this is a 64-bit kernel, then create two separate arenas -
4645 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4646 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4647 	 */
4648 	ip_minor_arena_la = NULL;
4649 	ip_minor_arena_sa = NULL;
4650 #if defined(_LP64)
4651 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4652 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4653 		cmn_err(CE_PANIC,
4654 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4655 	}
4656 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4657 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4658 		cmn_err(CE_PANIC,
4659 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4660 	}
4661 #else
4662 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4663 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4664 		cmn_err(CE_PANIC,
4665 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4666 	}
4667 #endif
4668 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4669 
4670 	ipcl_g_init();
4671 	ip_ire_g_init();
4672 	ip_net_g_init();
4673 
4674 #ifdef DEBUG
4675 	tsd_create(&ip_thread_data, ip_thread_exit);
4676 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4677 	list_create(&ip_thread_list, sizeof (th_hash_t),
4678 	    offsetof(th_hash_t, thh_link));
4679 #endif
4680 	ipsec_policy_g_init();
4681 	tcp_ddi_g_init();
4682 	sctp_ddi_g_init();
4683 	dce_g_init();
4684 
4685 	/*
4686 	 * We want to be informed each time a stack is created or
4687 	 * destroyed in the kernel, so we can maintain the
4688 	 * set of udp_stack_t's.
4689 	 */
4690 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4691 	    ip_stack_fini);
4692 
4693 	tnet_init();
4694 
4695 	udp_ddi_g_init();
4696 	rts_ddi_g_init();
4697 	icmp_ddi_g_init();
4698 	ilb_ddi_g_init();
4699 }
4700 
4701 /*
4702  * Initialize the IP stack instance.
4703  */
4704 static void *
4705 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4706 {
4707 	ip_stack_t	*ipst;
4708 	ipparam_t	*pa;
4709 	ipndp_t		*na;
4710 	major_t		major;
4711 
4712 #ifdef NS_DEBUG
4713 	printf("ip_stack_init(stack %d)\n", stackid);
4714 #endif
4715 
4716 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4717 	ipst->ips_netstack = ns;
4718 
4719 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4720 	    KM_SLEEP);
4721 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4722 	    KM_SLEEP);
4723 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4724 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4725 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4726 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4727 
4728 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
4729 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4730 	ipst->ips_igmp_deferred_next = INFINITY;
4731 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4732 	ipst->ips_mld_deferred_next = INFINITY;
4733 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4734 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4735 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4736 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4737 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4738 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4739 
4740 	ipcl_init(ipst);
4741 	ip_ire_init(ipst);
4742 	ip6_asp_init(ipst);
4743 	ipif_init(ipst);
4744 	conn_drain_init(ipst);
4745 	ip_mrouter_stack_init(ipst);
4746 	dce_stack_init(ipst);
4747 
4748 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
4749 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
4750 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
4751 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
4752 
4753 	ipst->ips_ip_multirt_log_interval = 1000;
4754 
4755 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
4756 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
4757 	ipst->ips_ill_index = 1;
4758 
4759 	ipst->ips_saved_ip_g_forward = -1;
4760 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4761 
4762 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
4763 	ipst->ips_param_arr = pa;
4764 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
4765 
4766 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
4767 	ipst->ips_ndp_arr = na;
4768 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
4769 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
4770 	    (caddr_t)&ipst->ips_ip_g_forward;
4771 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
4772 	    (caddr_t)&ipst->ips_ipv6_forward;
4773 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
4774 	    "ip_cgtp_filter") == 0);
4775 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
4776 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
4777 
4778 	(void) ip_param_register(&ipst->ips_ip_g_nd,
4779 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
4780 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
4781 
4782 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4783 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4784 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4785 	ipst->ips_ip6_kstat =
4786 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4787 
4788 	ipst->ips_ip_src_id = 1;
4789 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4790 
4791 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4792 
4793 	ip_net_init(ipst, ns);
4794 	ipv4_hook_init(ipst);
4795 	ipv6_hook_init(ipst);
4796 	arp_hook_init(ipst);
4797 	ipmp_init(ipst);
4798 	ipobs_init(ipst);
4799 
4800 	/*
4801 	 * Create the taskq dispatcher thread and initialize related stuff.
4802 	 */
4803 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4804 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4805 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4806 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4807 
4808 	major = mod_name_to_major(INET_NAME);
4809 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4810 	return (ipst);
4811 }
4812 
4813 /*
4814  * Allocate and initialize a DLPI template of the specified length.  (May be
4815  * called as writer.)
4816  */
4817 mblk_t *
4818 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4819 {
4820 	mblk_t	*mp;
4821 
4822 	mp = allocb(len, BPRI_MED);
4823 	if (!mp)
4824 		return (NULL);
4825 
4826 	/*
4827 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4828 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4829 	 * that other DLPI are M_PROTO.
4830 	 */
4831 	if (prim == DL_INFO_REQ) {
4832 		mp->b_datap->db_type = M_PCPROTO;
4833 	} else {
4834 		mp->b_datap->db_type = M_PROTO;
4835 	}
4836 
4837 	mp->b_wptr = mp->b_rptr + len;
4838 	bzero(mp->b_rptr, len);
4839 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4840 	return (mp);
4841 }
4842 
4843 /*
4844  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4845  */
4846 mblk_t *
4847 ip_dlnotify_alloc(uint_t notification, uint_t data)
4848 {
4849 	dl_notify_ind_t	*notifyp;
4850 	mblk_t		*mp;
4851 
4852 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4853 		return (NULL);
4854 
4855 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4856 	notifyp->dl_notification = notification;
4857 	notifyp->dl_data = data;
4858 	return (mp);
4859 }
4860 
4861 /*
4862  * Debug formatting routine.  Returns a character string representation of the
4863  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4864  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4865  *
4866  * Once the ndd table-printing interfaces are removed, this can be changed to
4867  * standard dotted-decimal form.
4868  */
4869 char *
4870 ip_dot_addr(ipaddr_t addr, char *buf)
4871 {
4872 	uint8_t *ap = (uint8_t *)&addr;
4873 
4874 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4875 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4876 	return (buf);
4877 }
4878 
4879 /*
4880  * Write the given MAC address as a printable string in the usual colon-
4881  * separated format.
4882  */
4883 const char *
4884 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4885 {
4886 	char *bp;
4887 
4888 	if (alen == 0 || buflen < 4)
4889 		return ("?");
4890 	bp = buf;
4891 	for (;;) {
4892 		/*
4893 		 * If there are more MAC address bytes available, but we won't
4894 		 * have any room to print them, then add "..." to the string
4895 		 * instead.  See below for the 'magic number' explanation.
4896 		 */
4897 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4898 			(void) strcpy(bp, "...");
4899 			break;
4900 		}
4901 		(void) sprintf(bp, "%02x", *addr++);
4902 		bp += 2;
4903 		if (--alen == 0)
4904 			break;
4905 		*bp++ = ':';
4906 		buflen -= 3;
4907 		/*
4908 		 * At this point, based on the first 'if' statement above,
4909 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4910 		 * buflen >= 4.  The first case leaves room for the final "xx"
4911 		 * number and trailing NUL byte.  The second leaves room for at
4912 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4913 		 * that statement.
4914 		 */
4915 	}
4916 	return (buf);
4917 }
4918 
4919 /*
4920  * Called when it is conceptually a ULP that would sent the packet
4921  * e.g., port unreachable and protocol unreachable. Check that the packet
4922  * would have passed the IPsec global policy before sending the error.
4923  *
4924  * Send an ICMP error after patching up the packet appropriately.
4925  * Uses ip_drop_input and bumps the appropriate MIB.
4926  */
4927 void
4928 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4929     ip_recv_attr_t *ira)
4930 {
4931 	ipha_t		*ipha;
4932 	boolean_t	secure;
4933 	ill_t		*ill = ira->ira_ill;
4934 	ip_stack_t	*ipst = ill->ill_ipst;
4935 	netstack_t	*ns = ipst->ips_netstack;
4936 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4937 
4938 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4939 
4940 	/*
4941 	 * We are generating an icmp error for some inbound packet.
4942 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4943 	 * Before we generate an error, check with global policy
4944 	 * to see whether this is allowed to enter the system. As
4945 	 * there is no "conn", we are checking with global policy.
4946 	 */
4947 	ipha = (ipha_t *)mp->b_rptr;
4948 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4949 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4950 		if (mp == NULL)
4951 			return;
4952 	}
4953 
4954 	/* We never send errors for protocols that we do implement */
4955 	if (ira->ira_protocol == IPPROTO_ICMP ||
4956 	    ira->ira_protocol == IPPROTO_IGMP) {
4957 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4958 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4959 		freemsg(mp);
4960 		return;
4961 	}
4962 	/*
4963 	 * Have to correct checksum since
4964 	 * the packet might have been
4965 	 * fragmented and the reassembly code in ip_rput
4966 	 * does not restore the IP checksum.
4967 	 */
4968 	ipha->ipha_hdr_checksum = 0;
4969 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4970 
4971 	switch (icmp_type) {
4972 	case ICMP_DEST_UNREACHABLE:
4973 		switch (icmp_code) {
4974 		case ICMP_PROTOCOL_UNREACHABLE:
4975 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4976 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4977 			break;
4978 		case ICMP_PORT_UNREACHABLE:
4979 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4980 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4981 			break;
4982 		}
4983 
4984 		icmp_unreachable(mp, icmp_code, ira);
4985 		break;
4986 	default:
4987 #ifdef DEBUG
4988 		panic("ip_fanout_send_icmp_v4: wrong type");
4989 		/*NOTREACHED*/
4990 #else
4991 		freemsg(mp);
4992 		break;
4993 #endif
4994 	}
4995 }
4996 
4997 /*
4998  * Used to send an ICMP error message when a packet is received for
4999  * a protocol that is not supported. The mblk passed as argument
5000  * is consumed by this function.
5001  */
5002 void
5003 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
5004 {
5005 	ipha_t		*ipha;
5006 
5007 	ipha = (ipha_t *)mp->b_rptr;
5008 	if (ira->ira_flags & IRAF_IS_IPV4) {
5009 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
5010 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5011 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5012 	} else {
5013 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
5014 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
5015 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
5016 	}
5017 }
5018 
5019 /*
5020  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
5021  * Handles IPv4 and IPv6.
5022  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5023  * Caller is responsible for dropping references to the conn.
5024  */
5025 void
5026 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5027     ip_recv_attr_t *ira)
5028 {
5029 	ill_t		*ill = ira->ira_ill;
5030 	ip_stack_t	*ipst = ill->ill_ipst;
5031 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5032 	boolean_t	secure;
5033 	uint_t		protocol = ira->ira_protocol;
5034 	iaflags_t	iraflags = ira->ira_flags;
5035 	queue_t		*rq;
5036 
5037 	secure = iraflags & IRAF_IPSEC_SECURE;
5038 
5039 	rq = connp->conn_rq;
5040 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
5041 		switch (protocol) {
5042 		case IPPROTO_ICMPV6:
5043 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
5044 			break;
5045 		case IPPROTO_ICMP:
5046 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
5047 			break;
5048 		default:
5049 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
5050 			break;
5051 		}
5052 		freemsg(mp);
5053 		return;
5054 	}
5055 
5056 	ASSERT(!(IPCL_IS_IPTUN(connp)));
5057 
5058 	if (((iraflags & IRAF_IS_IPV4) ?
5059 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5060 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5061 	    secure) {
5062 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5063 		    ip6h, ira);
5064 		if (mp == NULL) {
5065 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5066 			/* Note that mp is NULL */
5067 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5068 			return;
5069 		}
5070 	}
5071 
5072 	if (iraflags & IRAF_ICMP_ERROR) {
5073 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5074 	} else {
5075 		ill_t *rill = ira->ira_rill;
5076 
5077 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5078 		ira->ira_ill = ira->ira_rill = NULL;
5079 		/* Send it upstream */
5080 		(connp->conn_recv)(connp, mp, NULL, ira);
5081 		ira->ira_ill = ill;
5082 		ira->ira_rill = rill;
5083 	}
5084 }
5085 
5086 /*
5087  * Handle protocols with which IP is less intimate.  There
5088  * can be more than one stream bound to a particular
5089  * protocol.  When this is the case, normally each one gets a copy
5090  * of any incoming packets.
5091  *
5092  * IPsec NOTE :
5093  *
5094  * Don't allow a secure packet going up a non-secure connection.
5095  * We don't allow this because
5096  *
5097  * 1) Reply might go out in clear which will be dropped at
5098  *    the sending side.
5099  * 2) If the reply goes out in clear it will give the
5100  *    adversary enough information for getting the key in
5101  *    most of the cases.
5102  *
5103  * Moreover getting a secure packet when we expect clear
5104  * implies that SA's were added without checking for
5105  * policy on both ends. This should not happen once ISAKMP
5106  * is used to negotiate SAs as SAs will be added only after
5107  * verifying the policy.
5108  *
5109  * Zones notes:
5110  * Earlier in ip_input on a system with multiple shared-IP zones we
5111  * duplicate the multicast and broadcast packets and send them up
5112  * with each explicit zoneid that exists on that ill.
5113  * This means that here we can match the zoneid with SO_ALLZONES being special.
5114  */
5115 void
5116 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5117 {
5118 	mblk_t		*mp1;
5119 	ipaddr_t	laddr;
5120 	conn_t		*connp, *first_connp, *next_connp;
5121 	connf_t		*connfp;
5122 	ill_t		*ill = ira->ira_ill;
5123 	ip_stack_t	*ipst = ill->ill_ipst;
5124 
5125 	laddr = ipha->ipha_dst;
5126 
5127 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5128 	mutex_enter(&connfp->connf_lock);
5129 	connp = connfp->connf_head;
5130 	for (connp = connfp->connf_head; connp != NULL;
5131 	    connp = connp->conn_next) {
5132 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5133 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5134 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5135 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5136 			break;
5137 		}
5138 	}
5139 
5140 	if (connp == NULL) {
5141 		/*
5142 		 * No one bound to these addresses.  Is
5143 		 * there a client that wants all
5144 		 * unclaimed datagrams?
5145 		 */
5146 		mutex_exit(&connfp->connf_lock);
5147 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5148 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5149 		return;
5150 	}
5151 
5152 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5153 
5154 	CONN_INC_REF(connp);
5155 	first_connp = connp;
5156 	connp = connp->conn_next;
5157 
5158 	for (;;) {
5159 		while (connp != NULL) {
5160 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5161 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5162 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5163 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5164 			    ira, connp)))
5165 				break;
5166 			connp = connp->conn_next;
5167 		}
5168 
5169 		if (connp == NULL) {
5170 			/* No more interested clients */
5171 			connp = first_connp;
5172 			break;
5173 		}
5174 		if (((mp1 = dupmsg(mp)) == NULL) &&
5175 		    ((mp1 = copymsg(mp)) == NULL)) {
5176 			/* Memory allocation failed */
5177 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5178 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5179 			connp = first_connp;
5180 			break;
5181 		}
5182 
5183 		CONN_INC_REF(connp);
5184 		mutex_exit(&connfp->connf_lock);
5185 
5186 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5187 		    ira);
5188 
5189 		mutex_enter(&connfp->connf_lock);
5190 		/* Follow the next pointer before releasing the conn. */
5191 		next_connp = connp->conn_next;
5192 		CONN_DEC_REF(connp);
5193 		connp = next_connp;
5194 	}
5195 
5196 	/* Last one.  Send it upstream. */
5197 	mutex_exit(&connfp->connf_lock);
5198 
5199 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5200 
5201 	CONN_DEC_REF(connp);
5202 }
5203 
5204 /*
5205  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5206  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5207  * is not consumed.
5208  *
5209  * One of three things can happen, all of which affect the passed-in mblk:
5210  *
5211  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5212  *
5213  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5214  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5215  *
5216  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5217  */
5218 mblk_t *
5219 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5220 {
5221 	int shift, plen, iph_len;
5222 	ipha_t *ipha;
5223 	udpha_t *udpha;
5224 	uint32_t *spi;
5225 	uint32_t esp_ports;
5226 	uint8_t *orptr;
5227 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5228 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5229 
5230 	ipha = (ipha_t *)mp->b_rptr;
5231 	iph_len = ira->ira_ip_hdr_length;
5232 	plen = ira->ira_pktlen;
5233 
5234 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5235 		/*
5236 		 * Most likely a keepalive for the benefit of an intervening
5237 		 * NAT.  These aren't for us, per se, so drop it.
5238 		 *
5239 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5240 		 * byte packets (keepalives are 1-byte), but we'll drop them
5241 		 * also.
5242 		 */
5243 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5244 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5245 		return (NULL);
5246 	}
5247 
5248 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5249 		/* might as well pull it all up - it might be ESP. */
5250 		if (!pullupmsg(mp, -1)) {
5251 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5252 			    DROPPER(ipss, ipds_esp_nomem),
5253 			    &ipss->ipsec_dropper);
5254 			return (NULL);
5255 		}
5256 
5257 		ipha = (ipha_t *)mp->b_rptr;
5258 	}
5259 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5260 	if (*spi == 0) {
5261 		/* UDP packet - remove 0-spi. */
5262 		shift = sizeof (uint32_t);
5263 	} else {
5264 		/* ESP-in-UDP packet - reduce to ESP. */
5265 		ipha->ipha_protocol = IPPROTO_ESP;
5266 		shift = sizeof (udpha_t);
5267 	}
5268 
5269 	/* Fix IP header */
5270 	ira->ira_pktlen = (plen - shift);
5271 	ipha->ipha_length = htons(ira->ira_pktlen);
5272 	ipha->ipha_hdr_checksum = 0;
5273 
5274 	orptr = mp->b_rptr;
5275 	mp->b_rptr += shift;
5276 
5277 	udpha = (udpha_t *)(orptr + iph_len);
5278 	if (*spi == 0) {
5279 		ASSERT((uint8_t *)ipha == orptr);
5280 		udpha->uha_length = htons(plen - shift - iph_len);
5281 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5282 		esp_ports = 0;
5283 	} else {
5284 		esp_ports = *((uint32_t *)udpha);
5285 		ASSERT(esp_ports != 0);
5286 	}
5287 	ovbcopy(orptr, orptr + shift, iph_len);
5288 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5289 		ipha = (ipha_t *)(orptr + shift);
5290 
5291 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5292 		ira->ira_esp_udp_ports = esp_ports;
5293 		ip_fanout_v4(mp, ipha, ira);
5294 		return (NULL);
5295 	}
5296 	return (mp);
5297 }
5298 
5299 /*
5300  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5301  * Handles IPv4 and IPv6.
5302  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5303  * Caller is responsible for dropping references to the conn.
5304  */
5305 void
5306 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5307     ip_recv_attr_t *ira)
5308 {
5309 	ill_t		*ill = ira->ira_ill;
5310 	ip_stack_t	*ipst = ill->ill_ipst;
5311 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5312 	boolean_t	secure;
5313 	iaflags_t	iraflags = ira->ira_flags;
5314 
5315 	secure = iraflags & IRAF_IPSEC_SECURE;
5316 
5317 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5318 	    !canputnext(connp->conn_rq)) {
5319 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5320 		freemsg(mp);
5321 		return;
5322 	}
5323 
5324 	if (((iraflags & IRAF_IS_IPV4) ?
5325 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5326 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5327 	    secure) {
5328 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5329 		    ip6h, ira);
5330 		if (mp == NULL) {
5331 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5332 			/* Note that mp is NULL */
5333 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5334 			return;
5335 		}
5336 	}
5337 
5338 	/*
5339 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5340 	 * check. Only ip_fanout_v4 has that check.
5341 	 */
5342 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5343 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5344 	} else {
5345 		ill_t *rill = ira->ira_rill;
5346 
5347 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5348 		ira->ira_ill = ira->ira_rill = NULL;
5349 		/* Send it upstream */
5350 		(connp->conn_recv)(connp, mp, NULL, ira);
5351 		ira->ira_ill = ill;
5352 		ira->ira_rill = rill;
5353 	}
5354 }
5355 
5356 /*
5357  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5358  * (Unicast fanout is handled in ip_input_v4.)
5359  *
5360  * If SO_REUSEADDR is set all multicast and broadcast packets
5361  * will be delivered to all conns bound to the same port.
5362  *
5363  * If there is at least one matching AF_INET receiver, then we will
5364  * ignore any AF_INET6 receivers.
5365  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5366  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5367  * packets.
5368  *
5369  * Zones notes:
5370  * Earlier in ip_input on a system with multiple shared-IP zones we
5371  * duplicate the multicast and broadcast packets and send them up
5372  * with each explicit zoneid that exists on that ill.
5373  * This means that here we can match the zoneid with SO_ALLZONES being special.
5374  */
5375 void
5376 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5377     ip_recv_attr_t *ira)
5378 {
5379 	ipaddr_t	laddr;
5380 	in6_addr_t	v6faddr;
5381 	conn_t		*connp;
5382 	connf_t		*connfp;
5383 	ipaddr_t	faddr;
5384 	ill_t		*ill = ira->ira_ill;
5385 	ip_stack_t	*ipst = ill->ill_ipst;
5386 
5387 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5388 
5389 	laddr = ipha->ipha_dst;
5390 	faddr = ipha->ipha_src;
5391 
5392 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5393 	mutex_enter(&connfp->connf_lock);
5394 	connp = connfp->connf_head;
5395 
5396 	/*
5397 	 * If SO_REUSEADDR has been set on the first we send the
5398 	 * packet to all clients that have joined the group and
5399 	 * match the port.
5400 	 */
5401 	while (connp != NULL) {
5402 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5403 		    conn_wantpacket(connp, ira, ipha) &&
5404 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5405 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5406 			break;
5407 		connp = connp->conn_next;
5408 	}
5409 
5410 	if (connp == NULL)
5411 		goto notfound;
5412 
5413 	CONN_INC_REF(connp);
5414 
5415 	if (connp->conn_reuseaddr) {
5416 		conn_t		*first_connp = connp;
5417 		conn_t		*next_connp;
5418 		mblk_t		*mp1;
5419 
5420 		connp = connp->conn_next;
5421 		for (;;) {
5422 			while (connp != NULL) {
5423 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5424 				    fport, faddr) &&
5425 				    conn_wantpacket(connp, ira, ipha) &&
5426 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5427 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5428 				    ira, connp)))
5429 					break;
5430 				connp = connp->conn_next;
5431 			}
5432 			if (connp == NULL) {
5433 				/* No more interested clients */
5434 				connp = first_connp;
5435 				break;
5436 			}
5437 			if (((mp1 = dupmsg(mp)) == NULL) &&
5438 			    ((mp1 = copymsg(mp)) == NULL)) {
5439 				/* Memory allocation failed */
5440 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5441 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5442 				connp = first_connp;
5443 				break;
5444 			}
5445 			CONN_INC_REF(connp);
5446 			mutex_exit(&connfp->connf_lock);
5447 
5448 			IP_STAT(ipst, ip_udp_fanmb);
5449 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5450 			    NULL, ira);
5451 			mutex_enter(&connfp->connf_lock);
5452 			/* Follow the next pointer before releasing the conn */
5453 			next_connp = connp->conn_next;
5454 			CONN_DEC_REF(connp);
5455 			connp = next_connp;
5456 		}
5457 	}
5458 
5459 	/* Last one.  Send it upstream. */
5460 	mutex_exit(&connfp->connf_lock);
5461 	IP_STAT(ipst, ip_udp_fanmb);
5462 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5463 	CONN_DEC_REF(connp);
5464 	return;
5465 
5466 notfound:
5467 	mutex_exit(&connfp->connf_lock);
5468 	/*
5469 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5470 	 * have already been matched above, since they live in the IPv4
5471 	 * fanout tables. This implies we only need to
5472 	 * check for IPv6 in6addr_any endpoints here.
5473 	 * Thus we compare using ipv6_all_zeros instead of the destination
5474 	 * address, except for the multicast group membership lookup which
5475 	 * uses the IPv4 destination.
5476 	 */
5477 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5478 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5479 	mutex_enter(&connfp->connf_lock);
5480 	connp = connfp->connf_head;
5481 	/*
5482 	 * IPv4 multicast packet being delivered to an AF_INET6
5483 	 * in6addr_any endpoint.
5484 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5485 	 * and not conn_wantpacket_v6() since any multicast membership is
5486 	 * for an IPv4-mapped multicast address.
5487 	 */
5488 	while (connp != NULL) {
5489 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5490 		    fport, v6faddr) &&
5491 		    conn_wantpacket(connp, ira, ipha) &&
5492 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5493 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5494 			break;
5495 		connp = connp->conn_next;
5496 	}
5497 
5498 	if (connp == NULL) {
5499 		/*
5500 		 * No one bound to this port.  Is
5501 		 * there a client that wants all
5502 		 * unclaimed datagrams?
5503 		 */
5504 		mutex_exit(&connfp->connf_lock);
5505 
5506 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5507 		    NULL) {
5508 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5509 			ip_fanout_proto_v4(mp, ipha, ira);
5510 		} else {
5511 			/*
5512 			 * We used to attempt to send an icmp error here, but
5513 			 * since this is known to be a multicast packet
5514 			 * and we don't send icmp errors in response to
5515 			 * multicast, just drop the packet and give up sooner.
5516 			 */
5517 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5518 			freemsg(mp);
5519 		}
5520 		return;
5521 	}
5522 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5523 
5524 	/*
5525 	 * If SO_REUSEADDR has been set on the first we send the
5526 	 * packet to all clients that have joined the group and
5527 	 * match the port.
5528 	 */
5529 	if (connp->conn_reuseaddr) {
5530 		conn_t		*first_connp = connp;
5531 		conn_t		*next_connp;
5532 		mblk_t		*mp1;
5533 
5534 		CONN_INC_REF(connp);
5535 		connp = connp->conn_next;
5536 		for (;;) {
5537 			while (connp != NULL) {
5538 				if (IPCL_UDP_MATCH_V6(connp, lport,
5539 				    ipv6_all_zeros, fport, v6faddr) &&
5540 				    conn_wantpacket(connp, ira, ipha) &&
5541 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5542 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5543 				    ira, connp)))
5544 					break;
5545 				connp = connp->conn_next;
5546 			}
5547 			if (connp == NULL) {
5548 				/* No more interested clients */
5549 				connp = first_connp;
5550 				break;
5551 			}
5552 			if (((mp1 = dupmsg(mp)) == NULL) &&
5553 			    ((mp1 = copymsg(mp)) == NULL)) {
5554 				/* Memory allocation failed */
5555 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5556 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5557 				connp = first_connp;
5558 				break;
5559 			}
5560 			CONN_INC_REF(connp);
5561 			mutex_exit(&connfp->connf_lock);
5562 
5563 			IP_STAT(ipst, ip_udp_fanmb);
5564 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5565 			    NULL, ira);
5566 			mutex_enter(&connfp->connf_lock);
5567 			/* Follow the next pointer before releasing the conn */
5568 			next_connp = connp->conn_next;
5569 			CONN_DEC_REF(connp);
5570 			connp = next_connp;
5571 		}
5572 	}
5573 
5574 	/* Last one.  Send it upstream. */
5575 	mutex_exit(&connfp->connf_lock);
5576 	IP_STAT(ipst, ip_udp_fanmb);
5577 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5578 	CONN_DEC_REF(connp);
5579 }
5580 
5581 /*
5582  * Split an incoming packet's IPv4 options into the label and the other options.
5583  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5584  * clearing out any leftover label or options.
5585  * Otherwise it just makes ipp point into the packet.
5586  *
5587  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5588  */
5589 int
5590 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5591 {
5592 	uchar_t		*opt;
5593 	uint32_t	totallen;
5594 	uint32_t	optval;
5595 	uint32_t	optlen;
5596 
5597 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5598 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5599 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5600 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5601 
5602 	/*
5603 	 * Get length (in 4 byte octets) of IP header options.
5604 	 */
5605 	totallen = ipha->ipha_version_and_hdr_length -
5606 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5607 
5608 	if (totallen == 0) {
5609 		if (!allocate)
5610 			return (0);
5611 
5612 		/* Clear out anything from a previous packet */
5613 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5614 			kmem_free(ipp->ipp_ipv4_options,
5615 			    ipp->ipp_ipv4_options_len);
5616 			ipp->ipp_ipv4_options = NULL;
5617 			ipp->ipp_ipv4_options_len = 0;
5618 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5619 		}
5620 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5621 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5622 			ipp->ipp_label_v4 = NULL;
5623 			ipp->ipp_label_len_v4 = 0;
5624 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5625 		}
5626 		return (0);
5627 	}
5628 
5629 	totallen <<= 2;
5630 	opt = (uchar_t *)&ipha[1];
5631 	if (!is_system_labeled()) {
5632 
5633 	copyall:
5634 		if (!allocate) {
5635 			if (totallen != 0) {
5636 				ipp->ipp_ipv4_options = opt;
5637 				ipp->ipp_ipv4_options_len = totallen;
5638 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5639 			}
5640 			return (0);
5641 		}
5642 		/* Just copy all of options */
5643 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5644 			if (totallen == ipp->ipp_ipv4_options_len) {
5645 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5646 				return (0);
5647 			}
5648 			kmem_free(ipp->ipp_ipv4_options,
5649 			    ipp->ipp_ipv4_options_len);
5650 			ipp->ipp_ipv4_options = NULL;
5651 			ipp->ipp_ipv4_options_len = 0;
5652 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5653 		}
5654 		if (totallen == 0)
5655 			return (0);
5656 
5657 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5658 		if (ipp->ipp_ipv4_options == NULL)
5659 			return (ENOMEM);
5660 		ipp->ipp_ipv4_options_len = totallen;
5661 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5662 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5663 		return (0);
5664 	}
5665 
5666 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5667 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5668 		ipp->ipp_label_v4 = NULL;
5669 		ipp->ipp_label_len_v4 = 0;
5670 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5671 	}
5672 
5673 	/*
5674 	 * Search for CIPSO option.
5675 	 * We assume CIPSO is first in options if it is present.
5676 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5677 	 * prior to the CIPSO option.
5678 	 */
5679 	while (totallen != 0) {
5680 		switch (optval = opt[IPOPT_OPTVAL]) {
5681 		case IPOPT_EOL:
5682 			return (0);
5683 		case IPOPT_NOP:
5684 			optlen = 1;
5685 			break;
5686 		default:
5687 			if (totallen <= IPOPT_OLEN)
5688 				return (EINVAL);
5689 			optlen = opt[IPOPT_OLEN];
5690 			if (optlen < 2)
5691 				return (EINVAL);
5692 		}
5693 		if (optlen > totallen)
5694 			return (EINVAL);
5695 
5696 		switch (optval) {
5697 		case IPOPT_COMSEC:
5698 			if (!allocate) {
5699 				ipp->ipp_label_v4 = opt;
5700 				ipp->ipp_label_len_v4 = optlen;
5701 				ipp->ipp_fields |= IPPF_LABEL_V4;
5702 			} else {
5703 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5704 				    KM_NOSLEEP);
5705 				if (ipp->ipp_label_v4 == NULL)
5706 					return (ENOMEM);
5707 				ipp->ipp_label_len_v4 = optlen;
5708 				ipp->ipp_fields |= IPPF_LABEL_V4;
5709 				bcopy(opt, ipp->ipp_label_v4, optlen);
5710 			}
5711 			totallen -= optlen;
5712 			opt += optlen;
5713 
5714 			/* Skip padding bytes until we get to a multiple of 4 */
5715 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5716 				totallen--;
5717 				opt++;
5718 			}
5719 			/* Remaining as ipp_ipv4_options */
5720 			goto copyall;
5721 		}
5722 		totallen -= optlen;
5723 		opt += optlen;
5724 	}
5725 	/* No CIPSO found; return everything as ipp_ipv4_options */
5726 	totallen = ipha->ipha_version_and_hdr_length -
5727 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5728 	totallen <<= 2;
5729 	opt = (uchar_t *)&ipha[1];
5730 	goto copyall;
5731 }
5732 
5733 /*
5734  * Efficient versions of lookup for an IRE when we only
5735  * match the address.
5736  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5737  * Does not handle multicast addresses.
5738  */
5739 uint_t
5740 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5741 {
5742 	ire_t *ire;
5743 	uint_t result;
5744 
5745 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5746 	ASSERT(ire != NULL);
5747 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5748 		result = IRE_NOROUTE;
5749 	else
5750 		result = ire->ire_type;
5751 	ire_refrele(ire);
5752 	return (result);
5753 }
5754 
5755 /*
5756  * Efficient versions of lookup for an IRE when we only
5757  * match the address.
5758  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5759  * Does not handle multicast addresses.
5760  */
5761 uint_t
5762 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5763 {
5764 	ire_t *ire;
5765 	uint_t result;
5766 
5767 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5768 	ASSERT(ire != NULL);
5769 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5770 		result = IRE_NOROUTE;
5771 	else
5772 		result = ire->ire_type;
5773 	ire_refrele(ire);
5774 	return (result);
5775 }
5776 
5777 /*
5778  * Nobody should be sending
5779  * packets up this stream
5780  */
5781 static void
5782 ip_lrput(queue_t *q, mblk_t *mp)
5783 {
5784 	switch (mp->b_datap->db_type) {
5785 	case M_FLUSH:
5786 		/* Turn around */
5787 		if (*mp->b_rptr & FLUSHW) {
5788 			*mp->b_rptr &= ~FLUSHR;
5789 			qreply(q, mp);
5790 			return;
5791 		}
5792 		break;
5793 	}
5794 	freemsg(mp);
5795 }
5796 
5797 /* Nobody should be sending packets down this stream */
5798 /* ARGSUSED */
5799 void
5800 ip_lwput(queue_t *q, mblk_t *mp)
5801 {
5802 	freemsg(mp);
5803 }
5804 
5805 /*
5806  * Move the first hop in any source route to ipha_dst and remove that part of
5807  * the source route.  Called by other protocols.  Errors in option formatting
5808  * are ignored - will be handled by ip_output_options. Return the final
5809  * destination (either ipha_dst or the last entry in a source route.)
5810  */
5811 ipaddr_t
5812 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5813 {
5814 	ipoptp_t	opts;
5815 	uchar_t		*opt;
5816 	uint8_t		optval;
5817 	uint8_t		optlen;
5818 	ipaddr_t	dst;
5819 	int		i;
5820 	ip_stack_t	*ipst = ns->netstack_ip;
5821 
5822 	ip2dbg(("ip_massage_options\n"));
5823 	dst = ipha->ipha_dst;
5824 	for (optval = ipoptp_first(&opts, ipha);
5825 	    optval != IPOPT_EOL;
5826 	    optval = ipoptp_next(&opts)) {
5827 		opt = opts.ipoptp_cur;
5828 		switch (optval) {
5829 			uint8_t off;
5830 		case IPOPT_SSRR:
5831 		case IPOPT_LSRR:
5832 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5833 				ip1dbg(("ip_massage_options: bad src route\n"));
5834 				break;
5835 			}
5836 			optlen = opts.ipoptp_len;
5837 			off = opt[IPOPT_OFFSET];
5838 			off--;
5839 		redo_srr:
5840 			if (optlen < IP_ADDR_LEN ||
5841 			    off > optlen - IP_ADDR_LEN) {
5842 				/* End of source route */
5843 				ip1dbg(("ip_massage_options: end of SR\n"));
5844 				break;
5845 			}
5846 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5847 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5848 			    ntohl(dst)));
5849 			/*
5850 			 * Check if our address is present more than
5851 			 * once as consecutive hops in source route.
5852 			 * XXX verify per-interface ip_forwarding
5853 			 * for source route?
5854 			 */
5855 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5856 				off += IP_ADDR_LEN;
5857 				goto redo_srr;
5858 			}
5859 			if (dst == htonl(INADDR_LOOPBACK)) {
5860 				ip1dbg(("ip_massage_options: loopback addr in "
5861 				    "source route!\n"));
5862 				break;
5863 			}
5864 			/*
5865 			 * Update ipha_dst to be the first hop and remove the
5866 			 * first hop from the source route (by overwriting
5867 			 * part of the option with NOP options).
5868 			 */
5869 			ipha->ipha_dst = dst;
5870 			/* Put the last entry in dst */
5871 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5872 			    3;
5873 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5874 
5875 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5876 			    ntohl(dst)));
5877 			/* Move down and overwrite */
5878 			opt[IP_ADDR_LEN] = opt[0];
5879 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5880 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5881 			for (i = 0; i < IP_ADDR_LEN; i++)
5882 				opt[i] = IPOPT_NOP;
5883 			break;
5884 		}
5885 	}
5886 	return (dst);
5887 }
5888 
5889 /*
5890  * Return the network mask
5891  * associated with the specified address.
5892  */
5893 ipaddr_t
5894 ip_net_mask(ipaddr_t addr)
5895 {
5896 	uchar_t	*up = (uchar_t *)&addr;
5897 	ipaddr_t mask = 0;
5898 	uchar_t	*maskp = (uchar_t *)&mask;
5899 
5900 #if defined(__i386) || defined(__amd64)
5901 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5902 #endif
5903 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5904 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5905 #endif
5906 	if (CLASSD(addr)) {
5907 		maskp[0] = 0xF0;
5908 		return (mask);
5909 	}
5910 
5911 	/* We assume Class E default netmask to be 32 */
5912 	if (CLASSE(addr))
5913 		return (0xffffffffU);
5914 
5915 	if (addr == 0)
5916 		return (0);
5917 	maskp[0] = 0xFF;
5918 	if ((up[0] & 0x80) == 0)
5919 		return (mask);
5920 
5921 	maskp[1] = 0xFF;
5922 	if ((up[0] & 0xC0) == 0x80)
5923 		return (mask);
5924 
5925 	maskp[2] = 0xFF;
5926 	if ((up[0] & 0xE0) == 0xC0)
5927 		return (mask);
5928 
5929 	/* Otherwise return no mask */
5930 	return ((ipaddr_t)0);
5931 }
5932 
5933 /* Name/Value Table Lookup Routine */
5934 char *
5935 ip_nv_lookup(nv_t *nv, int value)
5936 {
5937 	if (!nv)
5938 		return (NULL);
5939 	for (; nv->nv_name; nv++) {
5940 		if (nv->nv_value == value)
5941 			return (nv->nv_name);
5942 	}
5943 	return ("unknown");
5944 }
5945 
5946 static int
5947 ip_wait_for_info_ack(ill_t *ill)
5948 {
5949 	int err;
5950 
5951 	mutex_enter(&ill->ill_lock);
5952 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5953 		/*
5954 		 * Return value of 0 indicates a pending signal.
5955 		 */
5956 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5957 		if (err == 0) {
5958 			mutex_exit(&ill->ill_lock);
5959 			return (EINTR);
5960 		}
5961 	}
5962 	mutex_exit(&ill->ill_lock);
5963 	/*
5964 	 * ip_rput_other could have set an error  in ill_error on
5965 	 * receipt of M_ERROR.
5966 	 */
5967 	return (ill->ill_error);
5968 }
5969 
5970 /*
5971  * This is a module open, i.e. this is a control stream for access
5972  * to a DLPI device.  We allocate an ill_t as the instance data in
5973  * this case.
5974  */
5975 static int
5976 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5977 {
5978 	ill_t	*ill;
5979 	int	err;
5980 	zoneid_t zoneid;
5981 	netstack_t *ns;
5982 	ip_stack_t *ipst;
5983 
5984 	/*
5985 	 * Prevent unprivileged processes from pushing IP so that
5986 	 * they can't send raw IP.
5987 	 */
5988 	if (secpolicy_net_rawaccess(credp) != 0)
5989 		return (EPERM);
5990 
5991 	ns = netstack_find_by_cred(credp);
5992 	ASSERT(ns != NULL);
5993 	ipst = ns->netstack_ip;
5994 	ASSERT(ipst != NULL);
5995 
5996 	/*
5997 	 * For exclusive stacks we set the zoneid to zero
5998 	 * to make IP operate as if in the global zone.
5999 	 */
6000 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6001 		zoneid = GLOBAL_ZONEID;
6002 	else
6003 		zoneid = crgetzoneid(credp);
6004 
6005 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
6006 	q->q_ptr = WR(q)->q_ptr = ill;
6007 	ill->ill_ipst = ipst;
6008 	ill->ill_zoneid = zoneid;
6009 
6010 	/*
6011 	 * ill_init initializes the ill fields and then sends down
6012 	 * down a DL_INFO_REQ after calling qprocson.
6013 	 */
6014 	err = ill_init(q, ill);
6015 
6016 	if (err != 0) {
6017 		mi_free(ill);
6018 		netstack_rele(ipst->ips_netstack);
6019 		q->q_ptr = NULL;
6020 		WR(q)->q_ptr = NULL;
6021 		return (err);
6022 	}
6023 
6024 	/*
6025 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
6026 	 *
6027 	 * ill_init initializes the ipsq marking this thread as
6028 	 * writer
6029 	 */
6030 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
6031 	err = ip_wait_for_info_ack(ill);
6032 	if (err == 0)
6033 		ill->ill_credp = credp;
6034 	else
6035 		goto fail;
6036 
6037 	crhold(credp);
6038 
6039 	mutex_enter(&ipst->ips_ip_mi_lock);
6040 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
6041 	    sflag, credp);
6042 	mutex_exit(&ipst->ips_ip_mi_lock);
6043 fail:
6044 	if (err) {
6045 		(void) ip_close(q, 0);
6046 		return (err);
6047 	}
6048 	return (0);
6049 }
6050 
6051 /* For /dev/ip aka AF_INET open */
6052 int
6053 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
6054 {
6055 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
6056 }
6057 
6058 /* For /dev/ip6 aka AF_INET6 open */
6059 int
6060 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
6061 {
6062 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
6063 }
6064 
6065 /* IP open routine. */
6066 int
6067 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
6068     boolean_t isv6)
6069 {
6070 	conn_t 		*connp;
6071 	major_t		maj;
6072 	zoneid_t	zoneid;
6073 	netstack_t	*ns;
6074 	ip_stack_t	*ipst;
6075 
6076 	/* Allow reopen. */
6077 	if (q->q_ptr != NULL)
6078 		return (0);
6079 
6080 	if (sflag & MODOPEN) {
6081 		/* This is a module open */
6082 		return (ip_modopen(q, devp, flag, sflag, credp));
6083 	}
6084 
6085 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
6086 		/*
6087 		 * Non streams based socket looking for a stream
6088 		 * to access IP
6089 		 */
6090 		return (ip_helper_stream_setup(q, devp, flag, sflag,
6091 		    credp, isv6));
6092 	}
6093 
6094 	ns = netstack_find_by_cred(credp);
6095 	ASSERT(ns != NULL);
6096 	ipst = ns->netstack_ip;
6097 	ASSERT(ipst != NULL);
6098 
6099 	/*
6100 	 * For exclusive stacks we set the zoneid to zero
6101 	 * to make IP operate as if in the global zone.
6102 	 */
6103 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6104 		zoneid = GLOBAL_ZONEID;
6105 	else
6106 		zoneid = crgetzoneid(credp);
6107 
6108 	/*
6109 	 * We are opening as a device. This is an IP client stream, and we
6110 	 * allocate an conn_t as the instance data.
6111 	 */
6112 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6113 
6114 	/*
6115 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
6116 	 * done by netstack_find_by_cred()
6117 	 */
6118 	netstack_rele(ipst->ips_netstack);
6119 
6120 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6121 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6122 	connp->conn_ixa->ixa_zoneid = zoneid;
6123 	connp->conn_zoneid = zoneid;
6124 
6125 	connp->conn_rq = q;
6126 	q->q_ptr = WR(q)->q_ptr = connp;
6127 
6128 	/* Minor tells us which /dev entry was opened */
6129 	if (isv6) {
6130 		connp->conn_family = AF_INET6;
6131 		connp->conn_ipversion = IPV6_VERSION;
6132 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6133 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6134 	} else {
6135 		connp->conn_family = AF_INET;
6136 		connp->conn_ipversion = IPV4_VERSION;
6137 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6138 	}
6139 
6140 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6141 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6142 		connp->conn_minor_arena = ip_minor_arena_la;
6143 	} else {
6144 		/*
6145 		 * Either minor numbers in the large arena were exhausted
6146 		 * or a non socket application is doing the open.
6147 		 * Try to allocate from the small arena.
6148 		 */
6149 		if ((connp->conn_dev =
6150 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6151 			/* CONN_DEC_REF takes care of netstack_rele() */
6152 			q->q_ptr = WR(q)->q_ptr = NULL;
6153 			CONN_DEC_REF(connp);
6154 			return (EBUSY);
6155 		}
6156 		connp->conn_minor_arena = ip_minor_arena_sa;
6157 	}
6158 
6159 	maj = getemajor(*devp);
6160 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
6161 
6162 	/*
6163 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6164 	 */
6165 	connp->conn_cred = credp;
6166 	/* Cache things in ixa without an extra refhold */
6167 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6168 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6169 	if (is_system_labeled())
6170 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6171 
6172 	/*
6173 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6174 	 */
6175 	connp->conn_recv = ip_conn_input;
6176 	connp->conn_recvicmp = ip_conn_input_icmp;
6177 
6178 	crhold(connp->conn_cred);
6179 
6180 	/*
6181 	 * If the caller has the process-wide flag set, then default to MAC
6182 	 * exempt mode.  This allows read-down to unlabeled hosts.
6183 	 */
6184 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6185 		connp->conn_mac_mode = CONN_MAC_AWARE;
6186 
6187 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6188 
6189 	connp->conn_rq = q;
6190 	connp->conn_wq = WR(q);
6191 
6192 	/* Non-zero default values */
6193 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6194 
6195 	/*
6196 	 * Make the conn globally visible to walkers
6197 	 */
6198 	ASSERT(connp->conn_ref == 1);
6199 	mutex_enter(&connp->conn_lock);
6200 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6201 	mutex_exit(&connp->conn_lock);
6202 
6203 	qprocson(q);
6204 
6205 	return (0);
6206 }
6207 
6208 /*
6209  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6210  * all of them are copied to the conn_t. If the req is "zero", the policy is
6211  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6212  * fields.
6213  * We keep only the latest setting of the policy and thus policy setting
6214  * is not incremental/cumulative.
6215  *
6216  * Requests to set policies with multiple alternative actions will
6217  * go through a different API.
6218  */
6219 int
6220 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6221 {
6222 	uint_t ah_req = 0;
6223 	uint_t esp_req = 0;
6224 	uint_t se_req = 0;
6225 	ipsec_act_t *actp = NULL;
6226 	uint_t nact;
6227 	ipsec_policy_head_t *ph;
6228 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6229 	int error = 0;
6230 	netstack_t	*ns = connp->conn_netstack;
6231 	ip_stack_t	*ipst = ns->netstack_ip;
6232 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6233 
6234 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6235 
6236 	/*
6237 	 * The IP_SEC_OPT option does not allow variable length parameters,
6238 	 * hence a request cannot be NULL.
6239 	 */
6240 	if (req == NULL)
6241 		return (EINVAL);
6242 
6243 	ah_req = req->ipsr_ah_req;
6244 	esp_req = req->ipsr_esp_req;
6245 	se_req = req->ipsr_self_encap_req;
6246 
6247 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6248 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6249 		return (EINVAL);
6250 
6251 	/*
6252 	 * Are we dealing with a request to reset the policy (i.e.
6253 	 * zero requests).
6254 	 */
6255 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6256 	    (esp_req & REQ_MASK) == 0 &&
6257 	    (se_req & REQ_MASK) == 0);
6258 
6259 	if (!is_pol_reset) {
6260 		/*
6261 		 * If we couldn't load IPsec, fail with "protocol
6262 		 * not supported".
6263 		 * IPsec may not have been loaded for a request with zero
6264 		 * policies, so we don't fail in this case.
6265 		 */
6266 		mutex_enter(&ipss->ipsec_loader_lock);
6267 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6268 			mutex_exit(&ipss->ipsec_loader_lock);
6269 			return (EPROTONOSUPPORT);
6270 		}
6271 		mutex_exit(&ipss->ipsec_loader_lock);
6272 
6273 		/*
6274 		 * Test for valid requests. Invalid algorithms
6275 		 * need to be tested by IPsec code because new
6276 		 * algorithms can be added dynamically.
6277 		 */
6278 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6279 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6280 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6281 			return (EINVAL);
6282 		}
6283 
6284 		/*
6285 		 * Only privileged users can issue these
6286 		 * requests.
6287 		 */
6288 		if (((ah_req & IPSEC_PREF_NEVER) ||
6289 		    (esp_req & IPSEC_PREF_NEVER) ||
6290 		    (se_req & IPSEC_PREF_NEVER)) &&
6291 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6292 			return (EPERM);
6293 		}
6294 
6295 		/*
6296 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6297 		 * are mutually exclusive.
6298 		 */
6299 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6300 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6301 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6302 			/* Both of them are set */
6303 			return (EINVAL);
6304 		}
6305 	}
6306 
6307 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6308 
6309 	/*
6310 	 * If we have already cached policies in conn_connect(), don't
6311 	 * let them change now. We cache policies for connections
6312 	 * whose src,dst [addr, port] is known.
6313 	 */
6314 	if (connp->conn_policy_cached) {
6315 		return (EINVAL);
6316 	}
6317 
6318 	/*
6319 	 * We have a zero policies, reset the connection policy if already
6320 	 * set. This will cause the connection to inherit the
6321 	 * global policy, if any.
6322 	 */
6323 	if (is_pol_reset) {
6324 		if (connp->conn_policy != NULL) {
6325 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6326 			connp->conn_policy = NULL;
6327 		}
6328 		connp->conn_in_enforce_policy = B_FALSE;
6329 		connp->conn_out_enforce_policy = B_FALSE;
6330 		return (0);
6331 	}
6332 
6333 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6334 	    ipst->ips_netstack);
6335 	if (ph == NULL)
6336 		goto enomem;
6337 
6338 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6339 	if (actp == NULL)
6340 		goto enomem;
6341 
6342 	/*
6343 	 * Always insert IPv4 policy entries, since they can also apply to
6344 	 * ipv6 sockets being used in ipv4-compat mode.
6345 	 */
6346 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6347 	    IPSEC_TYPE_INBOUND, ns))
6348 		goto enomem;
6349 	is_pol_inserted = B_TRUE;
6350 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6351 	    IPSEC_TYPE_OUTBOUND, ns))
6352 		goto enomem;
6353 
6354 	/*
6355 	 * We're looking at a v6 socket, also insert the v6-specific
6356 	 * entries.
6357 	 */
6358 	if (connp->conn_family == AF_INET6) {
6359 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6360 		    IPSEC_TYPE_INBOUND, ns))
6361 			goto enomem;
6362 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6363 		    IPSEC_TYPE_OUTBOUND, ns))
6364 			goto enomem;
6365 	}
6366 
6367 	ipsec_actvec_free(actp, nact);
6368 
6369 	/*
6370 	 * If the requests need security, set enforce_policy.
6371 	 * If the requests are IPSEC_PREF_NEVER, one should
6372 	 * still set conn_out_enforce_policy so that ip_set_destination
6373 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6374 	 * for connections that we don't cache policy in at connect time,
6375 	 * if global policy matches in ip_output_attach_policy, we
6376 	 * don't wrongly inherit global policy. Similarly, we need
6377 	 * to set conn_in_enforce_policy also so that we don't verify
6378 	 * policy wrongly.
6379 	 */
6380 	if ((ah_req & REQ_MASK) != 0 ||
6381 	    (esp_req & REQ_MASK) != 0 ||
6382 	    (se_req & REQ_MASK) != 0) {
6383 		connp->conn_in_enforce_policy = B_TRUE;
6384 		connp->conn_out_enforce_policy = B_TRUE;
6385 	}
6386 
6387 	return (error);
6388 #undef REQ_MASK
6389 
6390 	/*
6391 	 * Common memory-allocation-failure exit path.
6392 	 */
6393 enomem:
6394 	if (actp != NULL)
6395 		ipsec_actvec_free(actp, nact);
6396 	if (is_pol_inserted)
6397 		ipsec_polhead_flush(ph, ns);
6398 	return (ENOMEM);
6399 }
6400 
6401 /*
6402  * Set socket options for joining and leaving multicast groups.
6403  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6404  * The caller has already check that the option name is consistent with
6405  * the address family of the socket.
6406  */
6407 int
6408 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6409     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6410 {
6411 	int		*i1 = (int *)invalp;
6412 	int		error = 0;
6413 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6414 	struct ip_mreq	*v4_mreqp;
6415 	struct ipv6_mreq *v6_mreqp;
6416 	struct group_req *greqp;
6417 	ire_t *ire;
6418 	boolean_t done = B_FALSE;
6419 	ipaddr_t ifaddr;
6420 	in6_addr_t v6group;
6421 	uint_t ifindex;
6422 	boolean_t mcast_opt = B_TRUE;
6423 	mcast_record_t fmode;
6424 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6425 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6426 
6427 	switch (name) {
6428 	case IP_ADD_MEMBERSHIP:
6429 	case IPV6_JOIN_GROUP:
6430 		mcast_opt = B_FALSE;
6431 		/* FALLTHRU */
6432 	case MCAST_JOIN_GROUP:
6433 		fmode = MODE_IS_EXCLUDE;
6434 		optfn = ip_opt_add_group;
6435 		break;
6436 
6437 	case IP_DROP_MEMBERSHIP:
6438 	case IPV6_LEAVE_GROUP:
6439 		mcast_opt = B_FALSE;
6440 		/* FALLTHRU */
6441 	case MCAST_LEAVE_GROUP:
6442 		fmode = MODE_IS_INCLUDE;
6443 		optfn = ip_opt_delete_group;
6444 		break;
6445 	default:
6446 		ASSERT(0);
6447 	}
6448 
6449 	if (mcast_opt) {
6450 		struct sockaddr_in *sin;
6451 		struct sockaddr_in6 *sin6;
6452 
6453 		greqp = (struct group_req *)i1;
6454 		if (greqp->gr_group.ss_family == AF_INET) {
6455 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6456 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6457 		} else {
6458 			if (!inet6)
6459 				return (EINVAL);	/* Not on INET socket */
6460 
6461 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6462 			v6group = sin6->sin6_addr;
6463 		}
6464 		ifaddr = INADDR_ANY;
6465 		ifindex = greqp->gr_interface;
6466 	} else if (inet6) {
6467 		v6_mreqp = (struct ipv6_mreq *)i1;
6468 		v6group = v6_mreqp->ipv6mr_multiaddr;
6469 		ifaddr = INADDR_ANY;
6470 		ifindex = v6_mreqp->ipv6mr_interface;
6471 	} else {
6472 		v4_mreqp = (struct ip_mreq *)i1;
6473 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6474 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6475 		ifindex = 0;
6476 	}
6477 
6478 	/*
6479 	 * In the multirouting case, we need to replicate
6480 	 * the request on all interfaces that will take part
6481 	 * in replication.  We do so because multirouting is
6482 	 * reflective, thus we will probably receive multi-
6483 	 * casts on those interfaces.
6484 	 * The ip_multirt_apply_membership() succeeds if
6485 	 * the operation succeeds on at least one interface.
6486 	 */
6487 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6488 		ipaddr_t group;
6489 
6490 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6491 
6492 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6493 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6494 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6495 	} else {
6496 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6497 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6498 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6499 	}
6500 	if (ire != NULL) {
6501 		if (ire->ire_flags & RTF_MULTIRT) {
6502 			error = ip_multirt_apply_membership(optfn, ire, connp,
6503 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6504 			done = B_TRUE;
6505 		}
6506 		ire_refrele(ire);
6507 	}
6508 
6509 	if (!done) {
6510 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6511 		    fmode, &ipv6_all_zeros);
6512 	}
6513 	return (error);
6514 }
6515 
6516 /*
6517  * Set socket options for joining and leaving multicast groups
6518  * for specific sources.
6519  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6520  * The caller has already check that the option name is consistent with
6521  * the address family of the socket.
6522  */
6523 int
6524 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6525     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6526 {
6527 	int		*i1 = (int *)invalp;
6528 	int		error = 0;
6529 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6530 	struct ip_mreq_source *imreqp;
6531 	struct group_source_req *gsreqp;
6532 	in6_addr_t v6group, v6src;
6533 	uint32_t ifindex;
6534 	ipaddr_t ifaddr;
6535 	boolean_t mcast_opt = B_TRUE;
6536 	mcast_record_t fmode;
6537 	ire_t *ire;
6538 	boolean_t done = B_FALSE;
6539 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6540 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6541 
6542 	switch (name) {
6543 	case IP_BLOCK_SOURCE:
6544 		mcast_opt = B_FALSE;
6545 		/* FALLTHRU */
6546 	case MCAST_BLOCK_SOURCE:
6547 		fmode = MODE_IS_EXCLUDE;
6548 		optfn = ip_opt_add_group;
6549 		break;
6550 
6551 	case IP_UNBLOCK_SOURCE:
6552 		mcast_opt = B_FALSE;
6553 		/* FALLTHRU */
6554 	case MCAST_UNBLOCK_SOURCE:
6555 		fmode = MODE_IS_EXCLUDE;
6556 		optfn = ip_opt_delete_group;
6557 		break;
6558 
6559 	case IP_ADD_SOURCE_MEMBERSHIP:
6560 		mcast_opt = B_FALSE;
6561 		/* FALLTHRU */
6562 	case MCAST_JOIN_SOURCE_GROUP:
6563 		fmode = MODE_IS_INCLUDE;
6564 		optfn = ip_opt_add_group;
6565 		break;
6566 
6567 	case IP_DROP_SOURCE_MEMBERSHIP:
6568 		mcast_opt = B_FALSE;
6569 		/* FALLTHRU */
6570 	case MCAST_LEAVE_SOURCE_GROUP:
6571 		fmode = MODE_IS_INCLUDE;
6572 		optfn = ip_opt_delete_group;
6573 		break;
6574 	default:
6575 		ASSERT(0);
6576 	}
6577 
6578 	if (mcast_opt) {
6579 		gsreqp = (struct group_source_req *)i1;
6580 		ifindex = gsreqp->gsr_interface;
6581 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6582 			struct sockaddr_in *s;
6583 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6584 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6585 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6586 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6587 		} else {
6588 			struct sockaddr_in6 *s6;
6589 
6590 			if (!inet6)
6591 				return (EINVAL);	/* Not on INET socket */
6592 
6593 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6594 			v6group = s6->sin6_addr;
6595 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6596 			v6src = s6->sin6_addr;
6597 		}
6598 		ifaddr = INADDR_ANY;
6599 	} else {
6600 		imreqp = (struct ip_mreq_source *)i1;
6601 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6602 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6603 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6604 		ifindex = 0;
6605 	}
6606 
6607 	/*
6608 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6609 	 */
6610 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6611 		v6src = ipv6_all_zeros;
6612 
6613 	/*
6614 	 * In the multirouting case, we need to replicate
6615 	 * the request as noted in the mcast cases above.
6616 	 */
6617 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6618 		ipaddr_t group;
6619 
6620 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6621 
6622 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6623 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6624 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6625 	} else {
6626 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6627 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6628 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6629 	}
6630 	if (ire != NULL) {
6631 		if (ire->ire_flags & RTF_MULTIRT) {
6632 			error = ip_multirt_apply_membership(optfn, ire, connp,
6633 			    checkonly, &v6group, fmode, &v6src);
6634 			done = B_TRUE;
6635 		}
6636 		ire_refrele(ire);
6637 	}
6638 	if (!done) {
6639 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6640 		    fmode, &v6src);
6641 	}
6642 	return (error);
6643 }
6644 
6645 /*
6646  * Given a destination address and a pointer to where to put the information
6647  * this routine fills in the mtuinfo.
6648  * The socket must be connected.
6649  * For sctp conn_faddr is the primary address.
6650  */
6651 int
6652 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6653 {
6654 	uint32_t	pmtu = IP_MAXPACKET;
6655 	uint_t		scopeid;
6656 
6657 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6658 		return (-1);
6659 
6660 	/* In case we never sent or called ip_set_destination_v4/v6 */
6661 	if (ixa->ixa_ire != NULL)
6662 		pmtu = ip_get_pmtu(ixa);
6663 
6664 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6665 		scopeid = ixa->ixa_scopeid;
6666 	else
6667 		scopeid = 0;
6668 
6669 	bzero(mtuinfo, sizeof (*mtuinfo));
6670 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6671 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6672 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6673 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6674 	mtuinfo->ip6m_mtu = pmtu;
6675 
6676 	return (sizeof (struct ip6_mtuinfo));
6677 }
6678 
6679 /* Named Dispatch routine to get a current value out of our parameter table. */
6680 /* ARGSUSED */
6681 static int
6682 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6683 {
6684 	ipparam_t *ippa = (ipparam_t *)cp;
6685 
6686 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
6687 	return (0);
6688 }
6689 
6690 /* ARGSUSED */
6691 static int
6692 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
6693 {
6694 
6695 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
6696 	return (0);
6697 }
6698 
6699 /*
6700  * Set ip{,6}_forwarding values.  This means walking through all of the
6701  * ill's and toggling their forwarding values.
6702  */
6703 /* ARGSUSED */
6704 static int
6705 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6706 {
6707 	long new_value;
6708 	int *forwarding_value = (int *)cp;
6709 	ill_t *ill;
6710 	boolean_t isv6;
6711 	ill_walk_context_t ctx;
6712 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
6713 
6714 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
6715 
6716 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6717 	    new_value < 0 || new_value > 1) {
6718 		return (EINVAL);
6719 	}
6720 
6721 	*forwarding_value = new_value;
6722 
6723 	/*
6724 	 * Regardless of the current value of ip_forwarding, set all per-ill
6725 	 * values of ip_forwarding to the value being set.
6726 	 *
6727 	 * Bring all the ill's up to date with the new global value.
6728 	 */
6729 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
6730 
6731 	if (isv6)
6732 		ill = ILL_START_WALK_V6(&ctx, ipst);
6733 	else
6734 		ill = ILL_START_WALK_V4(&ctx, ipst);
6735 
6736 	for (; ill != NULL; ill = ill_next(&ctx, ill))
6737 		(void) ill_forward_set(ill, new_value != 0);
6738 
6739 	rw_exit(&ipst->ips_ill_g_lock);
6740 	return (0);
6741 }
6742 
6743 /*
6744  * Walk through the param array specified registering each element with the
6745  * Named Dispatch handler. This is called only during init. So it is ok
6746  * not to acquire any locks
6747  */
6748 static boolean_t
6749 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
6750     ipndp_t *ipnd, size_t ipnd_cnt)
6751 {
6752 	for (; ippa_cnt-- > 0; ippa++) {
6753 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
6754 			if (!nd_load(ndp, ippa->ip_param_name,
6755 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
6756 				nd_free(ndp);
6757 				return (B_FALSE);
6758 			}
6759 		}
6760 	}
6761 
6762 	for (; ipnd_cnt-- > 0; ipnd++) {
6763 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
6764 			if (!nd_load(ndp, ipnd->ip_ndp_name,
6765 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
6766 			    ipnd->ip_ndp_data)) {
6767 				nd_free(ndp);
6768 				return (B_FALSE);
6769 			}
6770 		}
6771 	}
6772 
6773 	return (B_TRUE);
6774 }
6775 
6776 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
6777 /* ARGSUSED */
6778 static int
6779 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
6780 {
6781 	long		new_value;
6782 	ipparam_t	*ippa = (ipparam_t *)cp;
6783 
6784 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6785 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
6786 		return (EINVAL);
6787 	}
6788 	ippa->ip_param_value = new_value;
6789 	return (0);
6790 }
6791 
6792 /*
6793  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6794  * When an ipf is passed here for the first time, if
6795  * we already have in-order fragments on the queue, we convert from the fast-
6796  * path reassembly scheme to the hard-case scheme.  From then on, additional
6797  * fragments are reassembled here.  We keep track of the start and end offsets
6798  * of each piece, and the number of holes in the chain.  When the hole count
6799  * goes to zero, we are done!
6800  *
6801  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6802  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6803  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6804  * after the call to ip_reassemble().
6805  */
6806 int
6807 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6808     size_t msg_len)
6809 {
6810 	uint_t	end;
6811 	mblk_t	*next_mp;
6812 	mblk_t	*mp1;
6813 	uint_t	offset;
6814 	boolean_t incr_dups = B_TRUE;
6815 	boolean_t offset_zero_seen = B_FALSE;
6816 	boolean_t pkt_boundary_checked = B_FALSE;
6817 
6818 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6819 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6820 
6821 	/* Add in byte count */
6822 	ipf->ipf_count += msg_len;
6823 	if (ipf->ipf_end) {
6824 		/*
6825 		 * We were part way through in-order reassembly, but now there
6826 		 * is a hole.  We walk through messages already queued, and
6827 		 * mark them for hard case reassembly.  We know that up till
6828 		 * now they were in order starting from offset zero.
6829 		 */
6830 		offset = 0;
6831 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6832 			IP_REASS_SET_START(mp1, offset);
6833 			if (offset == 0) {
6834 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6835 				offset = -ipf->ipf_nf_hdr_len;
6836 			}
6837 			offset += mp1->b_wptr - mp1->b_rptr;
6838 			IP_REASS_SET_END(mp1, offset);
6839 		}
6840 		/* One hole at the end. */
6841 		ipf->ipf_hole_cnt = 1;
6842 		/* Brand it as a hard case, forever. */
6843 		ipf->ipf_end = 0;
6844 	}
6845 	/* Walk through all the new pieces. */
6846 	do {
6847 		end = start + (mp->b_wptr - mp->b_rptr);
6848 		/*
6849 		 * If start is 0, decrease 'end' only for the first mblk of
6850 		 * the fragment. Otherwise 'end' can get wrong value in the
6851 		 * second pass of the loop if first mblk is exactly the
6852 		 * size of ipf_nf_hdr_len.
6853 		 */
6854 		if (start == 0 && !offset_zero_seen) {
6855 			/* First segment */
6856 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6857 			end -= ipf->ipf_nf_hdr_len;
6858 			offset_zero_seen = B_TRUE;
6859 		}
6860 		next_mp = mp->b_cont;
6861 		/*
6862 		 * We are checking to see if there is any interesing data
6863 		 * to process.  If there isn't and the mblk isn't the
6864 		 * one which carries the unfragmentable header then we
6865 		 * drop it.  It's possible to have just the unfragmentable
6866 		 * header come through without any data.  That needs to be
6867 		 * saved.
6868 		 *
6869 		 * If the assert at the top of this function holds then the
6870 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6871 		 * is infrequently traveled enough that the test is left in
6872 		 * to protect against future code changes which break that
6873 		 * invariant.
6874 		 */
6875 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6876 			/* Empty.  Blast it. */
6877 			IP_REASS_SET_START(mp, 0);
6878 			IP_REASS_SET_END(mp, 0);
6879 			/*
6880 			 * If the ipf points to the mblk we are about to free,
6881 			 * update ipf to point to the next mblk (or NULL
6882 			 * if none).
6883 			 */
6884 			if (ipf->ipf_mp->b_cont == mp)
6885 				ipf->ipf_mp->b_cont = next_mp;
6886 			freeb(mp);
6887 			continue;
6888 		}
6889 		mp->b_cont = NULL;
6890 		IP_REASS_SET_START(mp, start);
6891 		IP_REASS_SET_END(mp, end);
6892 		if (!ipf->ipf_tail_mp) {
6893 			ipf->ipf_tail_mp = mp;
6894 			ipf->ipf_mp->b_cont = mp;
6895 			if (start == 0 || !more) {
6896 				ipf->ipf_hole_cnt = 1;
6897 				/*
6898 				 * if the first fragment comes in more than one
6899 				 * mblk, this loop will be executed for each
6900 				 * mblk. Need to adjust hole count so exiting
6901 				 * this routine will leave hole count at 1.
6902 				 */
6903 				if (next_mp)
6904 					ipf->ipf_hole_cnt++;
6905 			} else
6906 				ipf->ipf_hole_cnt = 2;
6907 			continue;
6908 		} else if (ipf->ipf_last_frag_seen && !more &&
6909 		    !pkt_boundary_checked) {
6910 			/*
6911 			 * We check datagram boundary only if this fragment
6912 			 * claims to be the last fragment and we have seen a
6913 			 * last fragment in the past too. We do this only
6914 			 * once for a given fragment.
6915 			 *
6916 			 * start cannot be 0 here as fragments with start=0
6917 			 * and MF=0 gets handled as a complete packet. These
6918 			 * fragments should not reach here.
6919 			 */
6920 
6921 			if (start + msgdsize(mp) !=
6922 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6923 				/*
6924 				 * We have two fragments both of which claim
6925 				 * to be the last fragment but gives conflicting
6926 				 * information about the whole datagram size.
6927 				 * Something fishy is going on. Drop the
6928 				 * fragment and free up the reassembly list.
6929 				 */
6930 				return (IP_REASS_FAILED);
6931 			}
6932 
6933 			/*
6934 			 * We shouldn't come to this code block again for this
6935 			 * particular fragment.
6936 			 */
6937 			pkt_boundary_checked = B_TRUE;
6938 		}
6939 
6940 		/* New stuff at or beyond tail? */
6941 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6942 		if (start >= offset) {
6943 			if (ipf->ipf_last_frag_seen) {
6944 				/* current fragment is beyond last fragment */
6945 				return (IP_REASS_FAILED);
6946 			}
6947 			/* Link it on end. */
6948 			ipf->ipf_tail_mp->b_cont = mp;
6949 			ipf->ipf_tail_mp = mp;
6950 			if (more) {
6951 				if (start != offset)
6952 					ipf->ipf_hole_cnt++;
6953 			} else if (start == offset && next_mp == NULL)
6954 					ipf->ipf_hole_cnt--;
6955 			continue;
6956 		}
6957 		mp1 = ipf->ipf_mp->b_cont;
6958 		offset = IP_REASS_START(mp1);
6959 		/* New stuff at the front? */
6960 		if (start < offset) {
6961 			if (start == 0) {
6962 				if (end >= offset) {
6963 					/* Nailed the hole at the begining. */
6964 					ipf->ipf_hole_cnt--;
6965 				}
6966 			} else if (end < offset) {
6967 				/*
6968 				 * A hole, stuff, and a hole where there used
6969 				 * to be just a hole.
6970 				 */
6971 				ipf->ipf_hole_cnt++;
6972 			}
6973 			mp->b_cont = mp1;
6974 			/* Check for overlap. */
6975 			while (end > offset) {
6976 				if (end < IP_REASS_END(mp1)) {
6977 					mp->b_wptr -= end - offset;
6978 					IP_REASS_SET_END(mp, offset);
6979 					BUMP_MIB(ill->ill_ip_mib,
6980 					    ipIfStatsReasmPartDups);
6981 					break;
6982 				}
6983 				/* Did we cover another hole? */
6984 				if ((mp1->b_cont &&
6985 				    IP_REASS_END(mp1) !=
6986 				    IP_REASS_START(mp1->b_cont) &&
6987 				    end >= IP_REASS_START(mp1->b_cont)) ||
6988 				    (!ipf->ipf_last_frag_seen && !more)) {
6989 					ipf->ipf_hole_cnt--;
6990 				}
6991 				/* Clip out mp1. */
6992 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6993 					/*
6994 					 * After clipping out mp1, this guy
6995 					 * is now hanging off the end.
6996 					 */
6997 					ipf->ipf_tail_mp = mp;
6998 				}
6999 				IP_REASS_SET_START(mp1, 0);
7000 				IP_REASS_SET_END(mp1, 0);
7001 				/* Subtract byte count */
7002 				ipf->ipf_count -= mp1->b_datap->db_lim -
7003 				    mp1->b_datap->db_base;
7004 				freeb(mp1);
7005 				BUMP_MIB(ill->ill_ip_mib,
7006 				    ipIfStatsReasmPartDups);
7007 				mp1 = mp->b_cont;
7008 				if (!mp1)
7009 					break;
7010 				offset = IP_REASS_START(mp1);
7011 			}
7012 			ipf->ipf_mp->b_cont = mp;
7013 			continue;
7014 		}
7015 		/*
7016 		 * The new piece starts somewhere between the start of the head
7017 		 * and before the end of the tail.
7018 		 */
7019 		for (; mp1; mp1 = mp1->b_cont) {
7020 			offset = IP_REASS_END(mp1);
7021 			if (start < offset) {
7022 				if (end <= offset) {
7023 					/* Nothing new. */
7024 					IP_REASS_SET_START(mp, 0);
7025 					IP_REASS_SET_END(mp, 0);
7026 					/* Subtract byte count */
7027 					ipf->ipf_count -= mp->b_datap->db_lim -
7028 					    mp->b_datap->db_base;
7029 					if (incr_dups) {
7030 						ipf->ipf_num_dups++;
7031 						incr_dups = B_FALSE;
7032 					}
7033 					freeb(mp);
7034 					BUMP_MIB(ill->ill_ip_mib,
7035 					    ipIfStatsReasmDuplicates);
7036 					break;
7037 				}
7038 				/*
7039 				 * Trim redundant stuff off beginning of new
7040 				 * piece.
7041 				 */
7042 				IP_REASS_SET_START(mp, offset);
7043 				mp->b_rptr += offset - start;
7044 				BUMP_MIB(ill->ill_ip_mib,
7045 				    ipIfStatsReasmPartDups);
7046 				start = offset;
7047 				if (!mp1->b_cont) {
7048 					/*
7049 					 * After trimming, this guy is now
7050 					 * hanging off the end.
7051 					 */
7052 					mp1->b_cont = mp;
7053 					ipf->ipf_tail_mp = mp;
7054 					if (!more) {
7055 						ipf->ipf_hole_cnt--;
7056 					}
7057 					break;
7058 				}
7059 			}
7060 			if (start >= IP_REASS_START(mp1->b_cont))
7061 				continue;
7062 			/* Fill a hole */
7063 			if (start > offset)
7064 				ipf->ipf_hole_cnt++;
7065 			mp->b_cont = mp1->b_cont;
7066 			mp1->b_cont = mp;
7067 			mp1 = mp->b_cont;
7068 			offset = IP_REASS_START(mp1);
7069 			if (end >= offset) {
7070 				ipf->ipf_hole_cnt--;
7071 				/* Check for overlap. */
7072 				while (end > offset) {
7073 					if (end < IP_REASS_END(mp1)) {
7074 						mp->b_wptr -= end - offset;
7075 						IP_REASS_SET_END(mp, offset);
7076 						/*
7077 						 * TODO we might bump
7078 						 * this up twice if there is
7079 						 * overlap at both ends.
7080 						 */
7081 						BUMP_MIB(ill->ill_ip_mib,
7082 						    ipIfStatsReasmPartDups);
7083 						break;
7084 					}
7085 					/* Did we cover another hole? */
7086 					if ((mp1->b_cont &&
7087 					    IP_REASS_END(mp1)
7088 					    != IP_REASS_START(mp1->b_cont) &&
7089 					    end >=
7090 					    IP_REASS_START(mp1->b_cont)) ||
7091 					    (!ipf->ipf_last_frag_seen &&
7092 					    !more)) {
7093 						ipf->ipf_hole_cnt--;
7094 					}
7095 					/* Clip out mp1. */
7096 					if ((mp->b_cont = mp1->b_cont) ==
7097 					    NULL) {
7098 						/*
7099 						 * After clipping out mp1,
7100 						 * this guy is now hanging
7101 						 * off the end.
7102 						 */
7103 						ipf->ipf_tail_mp = mp;
7104 					}
7105 					IP_REASS_SET_START(mp1, 0);
7106 					IP_REASS_SET_END(mp1, 0);
7107 					/* Subtract byte count */
7108 					ipf->ipf_count -=
7109 					    mp1->b_datap->db_lim -
7110 					    mp1->b_datap->db_base;
7111 					freeb(mp1);
7112 					BUMP_MIB(ill->ill_ip_mib,
7113 					    ipIfStatsReasmPartDups);
7114 					mp1 = mp->b_cont;
7115 					if (!mp1)
7116 						break;
7117 					offset = IP_REASS_START(mp1);
7118 				}
7119 			}
7120 			break;
7121 		}
7122 	} while (start = end, mp = next_mp);
7123 
7124 	/* Fragment just processed could be the last one. Remember this fact */
7125 	if (!more)
7126 		ipf->ipf_last_frag_seen = B_TRUE;
7127 
7128 	/* Still got holes? */
7129 	if (ipf->ipf_hole_cnt)
7130 		return (IP_REASS_PARTIAL);
7131 	/* Clean up overloaded fields to avoid upstream disasters. */
7132 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
7133 		IP_REASS_SET_START(mp1, 0);
7134 		IP_REASS_SET_END(mp1, 0);
7135 	}
7136 	return (IP_REASS_COMPLETE);
7137 }
7138 
7139 /*
7140  * Fragmentation reassembly.  Each ILL has a hash table for
7141  * queuing packets undergoing reassembly for all IPIFs
7142  * associated with the ILL.  The hash is based on the packet
7143  * IP ident field.  The ILL frag hash table was allocated
7144  * as a timer block at the time the ILL was created.  Whenever
7145  * there is anything on the reassembly queue, the timer will
7146  * be running.  Returns the reassembled packet if reassembly completes.
7147  */
7148 mblk_t *
7149 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7150 {
7151 	uint32_t	frag_offset_flags;
7152 	mblk_t		*t_mp;
7153 	ipaddr_t	dst;
7154 	uint8_t		proto = ipha->ipha_protocol;
7155 	uint32_t	sum_val;
7156 	uint16_t	sum_flags;
7157 	ipf_t		*ipf;
7158 	ipf_t		**ipfp;
7159 	ipfb_t		*ipfb;
7160 	uint16_t	ident;
7161 	uint32_t	offset;
7162 	ipaddr_t	src;
7163 	uint_t		hdr_length;
7164 	uint32_t	end;
7165 	mblk_t		*mp1;
7166 	mblk_t		*tail_mp;
7167 	size_t		count;
7168 	size_t		msg_len;
7169 	uint8_t		ecn_info = 0;
7170 	uint32_t	packet_size;
7171 	boolean_t	pruned = B_FALSE;
7172 	ill_t		*ill = ira->ira_ill;
7173 	ip_stack_t	*ipst = ill->ill_ipst;
7174 
7175 	/*
7176 	 * Drop the fragmented as early as possible, if
7177 	 * we don't have resource(s) to re-assemble.
7178 	 */
7179 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7180 		freemsg(mp);
7181 		return (NULL);
7182 	}
7183 
7184 	/* Check for fragmentation offset; return if there's none */
7185 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7186 	    (IPH_MF | IPH_OFFSET)) == 0)
7187 		return (mp);
7188 
7189 	/*
7190 	 * We utilize hardware computed checksum info only for UDP since
7191 	 * IP fragmentation is a normal occurrence for the protocol.  In
7192 	 * addition, checksum offload support for IP fragments carrying
7193 	 * UDP payload is commonly implemented across network adapters.
7194 	 */
7195 	ASSERT(ira->ira_rill != NULL);
7196 	if (proto == IPPROTO_UDP && dohwcksum &&
7197 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7198 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7199 		mblk_t *mp1 = mp->b_cont;
7200 		int32_t len;
7201 
7202 		/* Record checksum information from the packet */
7203 		sum_val = (uint32_t)DB_CKSUM16(mp);
7204 		sum_flags = DB_CKSUMFLAGS(mp);
7205 
7206 		/* IP payload offset from beginning of mblk */
7207 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7208 
7209 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7210 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7211 		    offset >= DB_CKSUMSTART(mp) &&
7212 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7213 			uint32_t adj;
7214 			/*
7215 			 * Partial checksum has been calculated by hardware
7216 			 * and attached to the packet; in addition, any
7217 			 * prepended extraneous data is even byte aligned.
7218 			 * If any such data exists, we adjust the checksum;
7219 			 * this would also handle any postpended data.
7220 			 */
7221 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7222 			    mp, mp1, len, adj);
7223 
7224 			/* One's complement subtract extraneous checksum */
7225 			if (adj >= sum_val)
7226 				sum_val = ~(adj - sum_val) & 0xFFFF;
7227 			else
7228 				sum_val -= adj;
7229 		}
7230 	} else {
7231 		sum_val = 0;
7232 		sum_flags = 0;
7233 	}
7234 
7235 	/* Clear hardware checksumming flag */
7236 	DB_CKSUMFLAGS(mp) = 0;
7237 
7238 	ident = ipha->ipha_ident;
7239 	offset = (frag_offset_flags << 3) & 0xFFFF;
7240 	src = ipha->ipha_src;
7241 	dst = ipha->ipha_dst;
7242 	hdr_length = IPH_HDR_LENGTH(ipha);
7243 	end = ntohs(ipha->ipha_length) - hdr_length;
7244 
7245 	/* If end == 0 then we have a packet with no data, so just free it */
7246 	if (end == 0) {
7247 		freemsg(mp);
7248 		return (NULL);
7249 	}
7250 
7251 	/* Record the ECN field info. */
7252 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7253 	if (offset != 0) {
7254 		/*
7255 		 * If this isn't the first piece, strip the header, and
7256 		 * add the offset to the end value.
7257 		 */
7258 		mp->b_rptr += hdr_length;
7259 		end += offset;
7260 	}
7261 
7262 	/* Handle vnic loopback of fragments */
7263 	if (mp->b_datap->db_ref > 2)
7264 		msg_len = 0;
7265 	else
7266 		msg_len = MBLKSIZE(mp);
7267 
7268 	tail_mp = mp;
7269 	while (tail_mp->b_cont != NULL) {
7270 		tail_mp = tail_mp->b_cont;
7271 		if (tail_mp->b_datap->db_ref <= 2)
7272 			msg_len += MBLKSIZE(tail_mp);
7273 	}
7274 
7275 	/* If the reassembly list for this ILL will get too big, prune it */
7276 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7277 	    ipst->ips_ip_reass_queue_bytes) {
7278 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7279 		    uint_t, ill->ill_frag_count,
7280 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7281 		ill_frag_prune(ill,
7282 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7283 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7284 		pruned = B_TRUE;
7285 	}
7286 
7287 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7288 	mutex_enter(&ipfb->ipfb_lock);
7289 
7290 	ipfp = &ipfb->ipfb_ipf;
7291 	/* Try to find an existing fragment queue for this packet. */
7292 	for (;;) {
7293 		ipf = ipfp[0];
7294 		if (ipf != NULL) {
7295 			/*
7296 			 * It has to match on ident and src/dst address.
7297 			 */
7298 			if (ipf->ipf_ident == ident &&
7299 			    ipf->ipf_src == src &&
7300 			    ipf->ipf_dst == dst &&
7301 			    ipf->ipf_protocol == proto) {
7302 				/*
7303 				 * If we have received too many
7304 				 * duplicate fragments for this packet
7305 				 * free it.
7306 				 */
7307 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7308 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7309 					freemsg(mp);
7310 					mutex_exit(&ipfb->ipfb_lock);
7311 					return (NULL);
7312 				}
7313 				/* Found it. */
7314 				break;
7315 			}
7316 			ipfp = &ipf->ipf_hash_next;
7317 			continue;
7318 		}
7319 
7320 		/*
7321 		 * If we pruned the list, do we want to store this new
7322 		 * fragment?. We apply an optimization here based on the
7323 		 * fact that most fragments will be received in order.
7324 		 * So if the offset of this incoming fragment is zero,
7325 		 * it is the first fragment of a new packet. We will
7326 		 * keep it.  Otherwise drop the fragment, as we have
7327 		 * probably pruned the packet already (since the
7328 		 * packet cannot be found).
7329 		 */
7330 		if (pruned && offset != 0) {
7331 			mutex_exit(&ipfb->ipfb_lock);
7332 			freemsg(mp);
7333 			return (NULL);
7334 		}
7335 
7336 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7337 			/*
7338 			 * Too many fragmented packets in this hash
7339 			 * bucket. Free the oldest.
7340 			 */
7341 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7342 		}
7343 
7344 		/* New guy.  Allocate a frag message. */
7345 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7346 		if (mp1 == NULL) {
7347 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7348 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7349 			freemsg(mp);
7350 reass_done:
7351 			mutex_exit(&ipfb->ipfb_lock);
7352 			return (NULL);
7353 		}
7354 
7355 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7356 		mp1->b_cont = mp;
7357 
7358 		/* Initialize the fragment header. */
7359 		ipf = (ipf_t *)mp1->b_rptr;
7360 		ipf->ipf_mp = mp1;
7361 		ipf->ipf_ptphn = ipfp;
7362 		ipfp[0] = ipf;
7363 		ipf->ipf_hash_next = NULL;
7364 		ipf->ipf_ident = ident;
7365 		ipf->ipf_protocol = proto;
7366 		ipf->ipf_src = src;
7367 		ipf->ipf_dst = dst;
7368 		ipf->ipf_nf_hdr_len = 0;
7369 		/* Record reassembly start time. */
7370 		ipf->ipf_timestamp = gethrestime_sec();
7371 		/* Record ipf generation and account for frag header */
7372 		ipf->ipf_gen = ill->ill_ipf_gen++;
7373 		ipf->ipf_count = MBLKSIZE(mp1);
7374 		ipf->ipf_last_frag_seen = B_FALSE;
7375 		ipf->ipf_ecn = ecn_info;
7376 		ipf->ipf_num_dups = 0;
7377 		ipfb->ipfb_frag_pkts++;
7378 		ipf->ipf_checksum = 0;
7379 		ipf->ipf_checksum_flags = 0;
7380 
7381 		/* Store checksum value in fragment header */
7382 		if (sum_flags != 0) {
7383 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7384 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7385 			ipf->ipf_checksum = sum_val;
7386 			ipf->ipf_checksum_flags = sum_flags;
7387 		}
7388 
7389 		/*
7390 		 * We handle reassembly two ways.  In the easy case,
7391 		 * where all the fragments show up in order, we do
7392 		 * minimal bookkeeping, and just clip new pieces on
7393 		 * the end.  If we ever see a hole, then we go off
7394 		 * to ip_reassemble which has to mark the pieces and
7395 		 * keep track of the number of holes, etc.  Obviously,
7396 		 * the point of having both mechanisms is so we can
7397 		 * handle the easy case as efficiently as possible.
7398 		 */
7399 		if (offset == 0) {
7400 			/* Easy case, in-order reassembly so far. */
7401 			ipf->ipf_count += msg_len;
7402 			ipf->ipf_tail_mp = tail_mp;
7403 			/*
7404 			 * Keep track of next expected offset in
7405 			 * ipf_end.
7406 			 */
7407 			ipf->ipf_end = end;
7408 			ipf->ipf_nf_hdr_len = hdr_length;
7409 		} else {
7410 			/* Hard case, hole at the beginning. */
7411 			ipf->ipf_tail_mp = NULL;
7412 			/*
7413 			 * ipf_end == 0 means that we have given up
7414 			 * on easy reassembly.
7415 			 */
7416 			ipf->ipf_end = 0;
7417 
7418 			/* Forget checksum offload from now on */
7419 			ipf->ipf_checksum_flags = 0;
7420 
7421 			/*
7422 			 * ipf_hole_cnt is set by ip_reassemble.
7423 			 * ipf_count is updated by ip_reassemble.
7424 			 * No need to check for return value here
7425 			 * as we don't expect reassembly to complete
7426 			 * or fail for the first fragment itself.
7427 			 */
7428 			(void) ip_reassemble(mp, ipf,
7429 			    (frag_offset_flags & IPH_OFFSET) << 3,
7430 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7431 		}
7432 		/* Update per ipfb and ill byte counts */
7433 		ipfb->ipfb_count += ipf->ipf_count;
7434 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7435 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7436 		/* If the frag timer wasn't already going, start it. */
7437 		mutex_enter(&ill->ill_lock);
7438 		ill_frag_timer_start(ill);
7439 		mutex_exit(&ill->ill_lock);
7440 		goto reass_done;
7441 	}
7442 
7443 	/*
7444 	 * If the packet's flag has changed (it could be coming up
7445 	 * from an interface different than the previous, therefore
7446 	 * possibly different checksum capability), then forget about
7447 	 * any stored checksum states.  Otherwise add the value to
7448 	 * the existing one stored in the fragment header.
7449 	 */
7450 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7451 		sum_val += ipf->ipf_checksum;
7452 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7453 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7454 		ipf->ipf_checksum = sum_val;
7455 	} else if (ipf->ipf_checksum_flags != 0) {
7456 		/* Forget checksum offload from now on */
7457 		ipf->ipf_checksum_flags = 0;
7458 	}
7459 
7460 	/*
7461 	 * We have a new piece of a datagram which is already being
7462 	 * reassembled.  Update the ECN info if all IP fragments
7463 	 * are ECN capable.  If there is one which is not, clear
7464 	 * all the info.  If there is at least one which has CE
7465 	 * code point, IP needs to report that up to transport.
7466 	 */
7467 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7468 		if (ecn_info == IPH_ECN_CE)
7469 			ipf->ipf_ecn = IPH_ECN_CE;
7470 	} else {
7471 		ipf->ipf_ecn = IPH_ECN_NECT;
7472 	}
7473 	if (offset && ipf->ipf_end == offset) {
7474 		/* The new fragment fits at the end */
7475 		ipf->ipf_tail_mp->b_cont = mp;
7476 		/* Update the byte count */
7477 		ipf->ipf_count += msg_len;
7478 		/* Update per ipfb and ill byte counts */
7479 		ipfb->ipfb_count += msg_len;
7480 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7481 		atomic_add_32(&ill->ill_frag_count, msg_len);
7482 		if (frag_offset_flags & IPH_MF) {
7483 			/* More to come. */
7484 			ipf->ipf_end = end;
7485 			ipf->ipf_tail_mp = tail_mp;
7486 			goto reass_done;
7487 		}
7488 	} else {
7489 		/* Go do the hard cases. */
7490 		int ret;
7491 
7492 		if (offset == 0)
7493 			ipf->ipf_nf_hdr_len = hdr_length;
7494 
7495 		/* Save current byte count */
7496 		count = ipf->ipf_count;
7497 		ret = ip_reassemble(mp, ipf,
7498 		    (frag_offset_flags & IPH_OFFSET) << 3,
7499 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7500 		/* Count of bytes added and subtracted (freeb()ed) */
7501 		count = ipf->ipf_count - count;
7502 		if (count) {
7503 			/* Update per ipfb and ill byte counts */
7504 			ipfb->ipfb_count += count;
7505 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7506 			atomic_add_32(&ill->ill_frag_count, count);
7507 		}
7508 		if (ret == IP_REASS_PARTIAL) {
7509 			goto reass_done;
7510 		} else if (ret == IP_REASS_FAILED) {
7511 			/* Reassembly failed. Free up all resources */
7512 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7513 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7514 				IP_REASS_SET_START(t_mp, 0);
7515 				IP_REASS_SET_END(t_mp, 0);
7516 			}
7517 			freemsg(mp);
7518 			goto reass_done;
7519 		}
7520 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7521 	}
7522 	/*
7523 	 * We have completed reassembly.  Unhook the frag header from
7524 	 * the reassembly list.
7525 	 *
7526 	 * Before we free the frag header, record the ECN info
7527 	 * to report back to the transport.
7528 	 */
7529 	ecn_info = ipf->ipf_ecn;
7530 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7531 	ipfp = ipf->ipf_ptphn;
7532 
7533 	/* We need to supply these to caller */
7534 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7535 		sum_val = ipf->ipf_checksum;
7536 	else
7537 		sum_val = 0;
7538 
7539 	mp1 = ipf->ipf_mp;
7540 	count = ipf->ipf_count;
7541 	ipf = ipf->ipf_hash_next;
7542 	if (ipf != NULL)
7543 		ipf->ipf_ptphn = ipfp;
7544 	ipfp[0] = ipf;
7545 	atomic_add_32(&ill->ill_frag_count, -count);
7546 	ASSERT(ipfb->ipfb_count >= count);
7547 	ipfb->ipfb_count -= count;
7548 	ipfb->ipfb_frag_pkts--;
7549 	mutex_exit(&ipfb->ipfb_lock);
7550 	/* Ditch the frag header. */
7551 	mp = mp1->b_cont;
7552 
7553 	freeb(mp1);
7554 
7555 	/* Restore original IP length in header. */
7556 	packet_size = (uint32_t)msgdsize(mp);
7557 	if (packet_size > IP_MAXPACKET) {
7558 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7559 		ip_drop_input("Reassembled packet too large", mp, ill);
7560 		freemsg(mp);
7561 		return (NULL);
7562 	}
7563 
7564 	if (DB_REF(mp) > 1) {
7565 		mblk_t *mp2 = copymsg(mp);
7566 
7567 		if (mp2 == NULL) {
7568 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7569 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7570 			freemsg(mp);
7571 			return (NULL);
7572 		}
7573 		freemsg(mp);
7574 		mp = mp2;
7575 	}
7576 	ipha = (ipha_t *)mp->b_rptr;
7577 
7578 	ipha->ipha_length = htons((uint16_t)packet_size);
7579 	/* We're now complete, zip the frag state */
7580 	ipha->ipha_fragment_offset_and_flags = 0;
7581 	/* Record the ECN info. */
7582 	ipha->ipha_type_of_service &= 0xFC;
7583 	ipha->ipha_type_of_service |= ecn_info;
7584 
7585 	/* Update the receive attributes */
7586 	ira->ira_pktlen = packet_size;
7587 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7588 
7589 	/* Reassembly is successful; set checksum information in packet */
7590 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7591 	DB_CKSUMFLAGS(mp) = sum_flags;
7592 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7593 
7594 	return (mp);
7595 }
7596 
7597 /*
7598  * Pullup function that should be used for IP input in order to
7599  * ensure we do not loose the L2 source address; we need the l2 source
7600  * address for IP_RECVSLLA and for ndp_input.
7601  *
7602  * We return either NULL or b_rptr.
7603  */
7604 void *
7605 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7606 {
7607 	ill_t		*ill = ira->ira_ill;
7608 
7609 	if (ip_rput_pullups++ == 0) {
7610 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7611 		    "ip_pullup: %s forced us to "
7612 		    " pullup pkt, hdr len %ld, hdr addr %p",
7613 		    ill->ill_name, len, (void *)mp->b_rptr);
7614 	}
7615 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7616 		ip_setl2src(mp, ira, ira->ira_rill);
7617 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7618 	if (!pullupmsg(mp, len))
7619 		return (NULL);
7620 	else
7621 		return (mp->b_rptr);
7622 }
7623 
7624 /*
7625  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7626  * When called from the ULP ira_rill will be NULL hence the caller has to
7627  * pass in the ill.
7628  */
7629 /* ARGSUSED */
7630 void
7631 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7632 {
7633 	const uchar_t *addr;
7634 	int alen;
7635 
7636 	if (ira->ira_flags & IRAF_L2SRC_SET)
7637 		return;
7638 
7639 	ASSERT(ill != NULL);
7640 	alen = ill->ill_phys_addr_length;
7641 	ASSERT(alen <= sizeof (ira->ira_l2src));
7642 	if (ira->ira_mhip != NULL &&
7643 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7644 		bcopy(addr, ira->ira_l2src, alen);
7645 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7646 	    (addr = ill->ill_phys_addr) != NULL) {
7647 		bcopy(addr, ira->ira_l2src, alen);
7648 	} else {
7649 		bzero(ira->ira_l2src, alen);
7650 	}
7651 	ira->ira_flags |= IRAF_L2SRC_SET;
7652 }
7653 
7654 /*
7655  * check ip header length and align it.
7656  */
7657 mblk_t *
7658 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7659 {
7660 	ill_t	*ill = ira->ira_ill;
7661 	ssize_t len;
7662 
7663 	len = MBLKL(mp);
7664 
7665 	if (!OK_32PTR(mp->b_rptr))
7666 		IP_STAT(ill->ill_ipst, ip_notaligned);
7667 	else
7668 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7669 
7670 	/* Guard against bogus device drivers */
7671 	if (len < 0) {
7672 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7673 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7674 		freemsg(mp);
7675 		return (NULL);
7676 	}
7677 
7678 	if (len == 0) {
7679 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7680 		mblk_t *mp1 = mp->b_cont;
7681 
7682 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7683 			ip_setl2src(mp, ira, ira->ira_rill);
7684 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7685 
7686 		freeb(mp);
7687 		mp = mp1;
7688 		if (mp == NULL)
7689 			return (NULL);
7690 
7691 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7692 			return (mp);
7693 	}
7694 	if (ip_pullup(mp, min_size, ira) == NULL) {
7695 		if (msgdsize(mp) < min_size) {
7696 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7697 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7698 		} else {
7699 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7700 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7701 		}
7702 		freemsg(mp);
7703 		return (NULL);
7704 	}
7705 	return (mp);
7706 }
7707 
7708 /*
7709  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7710  */
7711 mblk_t *
7712 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7713     uint_t min_size, ip_recv_attr_t *ira)
7714 {
7715 	ill_t	*ill = ira->ira_ill;
7716 
7717 	/*
7718 	 * Make sure we have data length consistent
7719 	 * with the IP header.
7720 	 */
7721 	if (mp->b_cont == NULL) {
7722 		/* pkt_len is based on ipha_len, not the mblk length */
7723 		if (pkt_len < min_size) {
7724 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7725 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7726 			freemsg(mp);
7727 			return (NULL);
7728 		}
7729 		if (len < 0) {
7730 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7731 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7732 			freemsg(mp);
7733 			return (NULL);
7734 		}
7735 		/* Drop any pad */
7736 		mp->b_wptr = rptr + pkt_len;
7737 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7738 		ASSERT(pkt_len >= min_size);
7739 		if (pkt_len < min_size) {
7740 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7741 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7742 			freemsg(mp);
7743 			return (NULL);
7744 		}
7745 		if (len < 0) {
7746 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7747 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7748 			freemsg(mp);
7749 			return (NULL);
7750 		}
7751 		/* Drop any pad */
7752 		(void) adjmsg(mp, -len);
7753 		/*
7754 		 * adjmsg may have freed an mblk from the chain, hence
7755 		 * invalidate any hw checksum here. This will force IP to
7756 		 * calculate the checksum in sw, but only for this packet.
7757 		 */
7758 		DB_CKSUMFLAGS(mp) = 0;
7759 		IP_STAT(ill->ill_ipst, ip_multimblk);
7760 	}
7761 	return (mp);
7762 }
7763 
7764 /*
7765  * Check that the IPv4 opt_len is consistent with the packet and pullup
7766  * the options.
7767  */
7768 mblk_t *
7769 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7770     ip_recv_attr_t *ira)
7771 {
7772 	ill_t	*ill = ira->ira_ill;
7773 	ssize_t len;
7774 
7775 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7776 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7777 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7778 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7779 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7780 		freemsg(mp);
7781 		return (NULL);
7782 	}
7783 
7784 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7785 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7786 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7787 		freemsg(mp);
7788 		return (NULL);
7789 	}
7790 	/*
7791 	 * Recompute complete header length and make sure we
7792 	 * have access to all of it.
7793 	 */
7794 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7795 	if (len > (mp->b_wptr - mp->b_rptr)) {
7796 		if (len > pkt_len) {
7797 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7798 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7799 			freemsg(mp);
7800 			return (NULL);
7801 		}
7802 		if (ip_pullup(mp, len, ira) == NULL) {
7803 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7804 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7805 			freemsg(mp);
7806 			return (NULL);
7807 		}
7808 	}
7809 	return (mp);
7810 }
7811 
7812 /*
7813  * Returns a new ire, or the same ire, or NULL.
7814  * If a different IRE is returned, then it is held; the caller
7815  * needs to release it.
7816  * In no case is there any hold/release on the ire argument.
7817  */
7818 ire_t *
7819 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7820 {
7821 	ire_t		*new_ire;
7822 	ill_t		*ire_ill;
7823 	uint_t		ifindex;
7824 	ip_stack_t	*ipst = ill->ill_ipst;
7825 	boolean_t	strict_check = B_FALSE;
7826 
7827 	/*
7828 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7829 	 * issue (e.g. packet received on an underlying interface matched an
7830 	 * IRE_LOCAL on its associated group interface).
7831 	 */
7832 	ASSERT(ire->ire_ill != NULL);
7833 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7834 		return (ire);
7835 
7836 	/*
7837 	 * Do another ire lookup here, using the ingress ill, to see if the
7838 	 * interface is in a usesrc group.
7839 	 * As long as the ills belong to the same group, we don't consider
7840 	 * them to be arriving on the wrong interface. Thus, if the switch
7841 	 * is doing inbound load spreading, we won't drop packets when the
7842 	 * ip*_strict_dst_multihoming switch is on.
7843 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7844 	 * where the local address may not be unique. In this case we were
7845 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7846 	 * actually returned. The new lookup, which is more specific, should
7847 	 * only find the IRE_LOCAL associated with the ingress ill if one
7848 	 * exists.
7849 	 */
7850 	if (ire->ire_ipversion == IPV4_VERSION) {
7851 		if (ipst->ips_ip_strict_dst_multihoming)
7852 			strict_check = B_TRUE;
7853 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7854 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7855 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7856 	} else {
7857 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7858 		if (ipst->ips_ipv6_strict_dst_multihoming)
7859 			strict_check = B_TRUE;
7860 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7861 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7862 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7863 	}
7864 	/*
7865 	 * If the same ire that was returned in ip_input() is found then this
7866 	 * is an indication that usesrc groups are in use. The packet
7867 	 * arrived on a different ill in the group than the one associated with
7868 	 * the destination address.  If a different ire was found then the same
7869 	 * IP address must be hosted on multiple ills. This is possible with
7870 	 * unnumbered point2point interfaces. We switch to use this new ire in
7871 	 * order to have accurate interface statistics.
7872 	 */
7873 	if (new_ire != NULL) {
7874 		/* Note: held in one case but not the other? Caller handles */
7875 		if (new_ire != ire)
7876 			return (new_ire);
7877 		/* Unchanged */
7878 		ire_refrele(new_ire);
7879 		return (ire);
7880 	}
7881 
7882 	/*
7883 	 * Chase pointers once and store locally.
7884 	 */
7885 	ASSERT(ire->ire_ill != NULL);
7886 	ire_ill = ire->ire_ill;
7887 	ifindex = ill->ill_usesrc_ifindex;
7888 
7889 	/*
7890 	 * Check if it's a legal address on the 'usesrc' interface.
7891 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7892 	 * can just check phyint_ifindex.
7893 	 */
7894 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7895 		return (ire);
7896 	}
7897 
7898 	/*
7899 	 * If the ip*_strict_dst_multihoming switch is on then we can
7900 	 * only accept this packet if the interface is marked as routing.
7901 	 */
7902 	if (!(strict_check))
7903 		return (ire);
7904 
7905 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7906 		return (ire);
7907 	}
7908 	return (NULL);
7909 }
7910 
7911 /*
7912  * This function is used to construct a mac_header_info_s from a
7913  * DL_UNITDATA_IND message.
7914  * The address fields in the mhi structure points into the message,
7915  * thus the caller can't use those fields after freeing the message.
7916  *
7917  * We determine whether the packet received is a non-unicast packet
7918  * and in doing so, determine whether or not it is broadcast vs multicast.
7919  * For it to be a broadcast packet, we must have the appropriate mblk_t
7920  * hanging off the ill_t.  If this is either not present or doesn't match
7921  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7922  * to be multicast.  Thus NICs that have no broadcast address (or no
7923  * capability for one, such as point to point links) cannot return as
7924  * the packet being broadcast.
7925  */
7926 void
7927 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7928 {
7929 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7930 	mblk_t *bmp;
7931 	uint_t extra_offset;
7932 
7933 	bzero(mhip, sizeof (struct mac_header_info_s));
7934 
7935 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7936 
7937 	if (ill->ill_sap_length < 0)
7938 		extra_offset = 0;
7939 	else
7940 		extra_offset = ill->ill_sap_length;
7941 
7942 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7943 	    extra_offset;
7944 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7945 	    extra_offset;
7946 
7947 	if (!ind->dl_group_address)
7948 		return;
7949 
7950 	/* Multicast or broadcast */
7951 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7952 
7953 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7954 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7955 	    (bmp = ill->ill_bcast_mp) != NULL) {
7956 		dl_unitdata_req_t *dlur;
7957 		uint8_t *bphys_addr;
7958 
7959 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7960 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7961 		    extra_offset;
7962 
7963 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7964 		    ind->dl_dest_addr_length) == 0)
7965 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7966 	}
7967 }
7968 
7969 /*
7970  * This function is used to construct a mac_header_info_s from a
7971  * M_DATA fastpath message from a DLPI driver.
7972  * The address fields in the mhi structure points into the message,
7973  * thus the caller can't use those fields after freeing the message.
7974  *
7975  * We determine whether the packet received is a non-unicast packet
7976  * and in doing so, determine whether or not it is broadcast vs multicast.
7977  * For it to be a broadcast packet, we must have the appropriate mblk_t
7978  * hanging off the ill_t.  If this is either not present or doesn't match
7979  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7980  * to be multicast.  Thus NICs that have no broadcast address (or no
7981  * capability for one, such as point to point links) cannot return as
7982  * the packet being broadcast.
7983  */
7984 void
7985 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7986 {
7987 	mblk_t *bmp;
7988 	struct ether_header *pether;
7989 
7990 	bzero(mhip, sizeof (struct mac_header_info_s));
7991 
7992 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7993 
7994 	pether = (struct ether_header *)((char *)mp->b_rptr
7995 	    - sizeof (struct ether_header));
7996 
7997 	/*
7998 	 * Make sure the interface is an ethernet type, since we don't
7999 	 * know the header format for anything but Ethernet. Also make
8000 	 * sure we are pointing correctly above db_base.
8001 	 */
8002 	if (ill->ill_type != IFT_ETHER)
8003 		return;
8004 
8005 retry:
8006 	if ((uchar_t *)pether < mp->b_datap->db_base)
8007 		return;
8008 
8009 	/* Is there a VLAN tag? */
8010 	if (ill->ill_isv6) {
8011 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
8012 			pether = (struct ether_header *)((char *)pether - 4);
8013 			goto retry;
8014 		}
8015 	} else {
8016 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
8017 			pether = (struct ether_header *)((char *)pether - 4);
8018 			goto retry;
8019 		}
8020 	}
8021 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
8022 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
8023 
8024 	if (!(mhip->mhi_daddr[0] & 0x01))
8025 		return;
8026 
8027 	/* Multicast or broadcast */
8028 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
8029 
8030 	if ((bmp = ill->ill_bcast_mp) != NULL) {
8031 		dl_unitdata_req_t *dlur;
8032 		uint8_t *bphys_addr;
8033 		uint_t	addrlen;
8034 
8035 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
8036 		addrlen = dlur->dl_dest_addr_length;
8037 		if (ill->ill_sap_length < 0) {
8038 			bphys_addr = (uchar_t *)dlur +
8039 			    dlur->dl_dest_addr_offset;
8040 			addrlen += ill->ill_sap_length;
8041 		} else {
8042 			bphys_addr = (uchar_t *)dlur +
8043 			    dlur->dl_dest_addr_offset +
8044 			    ill->ill_sap_length;
8045 			addrlen -= ill->ill_sap_length;
8046 		}
8047 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
8048 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
8049 	}
8050 }
8051 
8052 /*
8053  * Handle anything but M_DATA messages
8054  * We see the DL_UNITDATA_IND which are part
8055  * of the data path, and also the other messages from the driver.
8056  */
8057 void
8058 ip_rput_notdata(ill_t *ill, mblk_t *mp)
8059 {
8060 	mblk_t		*first_mp;
8061 	struct iocblk   *iocp;
8062 	struct mac_header_info_s mhi;
8063 
8064 	switch (DB_TYPE(mp)) {
8065 	case M_PROTO:
8066 	case M_PCPROTO: {
8067 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
8068 		    DL_UNITDATA_IND) {
8069 			/* Go handle anything other than data elsewhere. */
8070 			ip_rput_dlpi(ill, mp);
8071 			return;
8072 		}
8073 
8074 		first_mp = mp;
8075 		mp = first_mp->b_cont;
8076 		first_mp->b_cont = NULL;
8077 
8078 		if (mp == NULL) {
8079 			freeb(first_mp);
8080 			return;
8081 		}
8082 		ip_dlur_to_mhi(ill, first_mp, &mhi);
8083 		if (ill->ill_isv6)
8084 			ip_input_v6(ill, NULL, mp, &mhi);
8085 		else
8086 			ip_input(ill, NULL, mp, &mhi);
8087 
8088 		/* Ditch the DLPI header. */
8089 		freeb(first_mp);
8090 		return;
8091 	}
8092 	case M_IOCACK:
8093 		iocp = (struct iocblk *)mp->b_rptr;
8094 		switch (iocp->ioc_cmd) {
8095 		case DL_IOC_HDR_INFO:
8096 			ill_fastpath_ack(ill, mp);
8097 			return;
8098 		default:
8099 			putnext(ill->ill_rq, mp);
8100 			return;
8101 		}
8102 		/* FALLTHRU */
8103 	case M_ERROR:
8104 	case M_HANGUP:
8105 		mutex_enter(&ill->ill_lock);
8106 		if (ill->ill_state_flags & ILL_CONDEMNED) {
8107 			mutex_exit(&ill->ill_lock);
8108 			freemsg(mp);
8109 			return;
8110 		}
8111 		ill_refhold_locked(ill);
8112 		mutex_exit(&ill->ill_lock);
8113 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
8114 		    B_FALSE);
8115 		return;
8116 	case M_CTL:
8117 		putnext(ill->ill_rq, mp);
8118 		return;
8119 	case M_IOCNAK:
8120 		ip1dbg(("got iocnak "));
8121 		iocp = (struct iocblk *)mp->b_rptr;
8122 		switch (iocp->ioc_cmd) {
8123 		case DL_IOC_HDR_INFO:
8124 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
8125 			return;
8126 		default:
8127 			break;
8128 		}
8129 		/* FALLTHRU */
8130 	default:
8131 		putnext(ill->ill_rq, mp);
8132 		return;
8133 	}
8134 }
8135 
8136 /* Read side put procedure.  Packets coming from the wire arrive here. */
8137 void
8138 ip_rput(queue_t *q, mblk_t *mp)
8139 {
8140 	ill_t	*ill;
8141 	union DL_primitives *dl;
8142 
8143 	ill = (ill_t *)q->q_ptr;
8144 
8145 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8146 		/*
8147 		 * If things are opening or closing, only accept high-priority
8148 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
8149 		 * created; on close, things hanging off the ill may have been
8150 		 * freed already.)
8151 		 */
8152 		dl = (union DL_primitives *)mp->b_rptr;
8153 		if (DB_TYPE(mp) != M_PCPROTO ||
8154 		    dl->dl_primitive == DL_UNITDATA_IND) {
8155 			inet_freemsg(mp);
8156 			return;
8157 		}
8158 	}
8159 	if (DB_TYPE(mp) == M_DATA) {
8160 		struct mac_header_info_s mhi;
8161 
8162 		ip_mdata_to_mhi(ill, mp, &mhi);
8163 		ip_input(ill, NULL, mp, &mhi);
8164 	} else {
8165 		ip_rput_notdata(ill, mp);
8166 	}
8167 }
8168 
8169 /*
8170  * Move the information to a copy.
8171  */
8172 mblk_t *
8173 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8174 {
8175 	mblk_t		*mp1;
8176 	ill_t		*ill = ira->ira_ill;
8177 	ip_stack_t	*ipst = ill->ill_ipst;
8178 
8179 	IP_STAT(ipst, ip_db_ref);
8180 
8181 	/* Make sure we have ira_l2src before we loose the original mblk */
8182 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8183 		ip_setl2src(mp, ira, ira->ira_rill);
8184 
8185 	mp1 = copymsg(mp);
8186 	if (mp1 == NULL) {
8187 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8188 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8189 		freemsg(mp);
8190 		return (NULL);
8191 	}
8192 	/* preserve the hardware checksum flags and data, if present */
8193 	if (DB_CKSUMFLAGS(mp) != 0) {
8194 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8195 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8196 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8197 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8198 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8199 	}
8200 	freemsg(mp);
8201 	return (mp1);
8202 }
8203 
8204 static void
8205 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8206     t_uscalar_t err)
8207 {
8208 	if (dl_err == DL_SYSERR) {
8209 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8210 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8211 		    ill->ill_name, dl_primstr(prim), err);
8212 		return;
8213 	}
8214 
8215 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8216 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8217 	    dl_errstr(dl_err));
8218 }
8219 
8220 /*
8221  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8222  * than DL_UNITDATA_IND messages. If we need to process this message
8223  * exclusively, we call qwriter_ip, in which case we also need to call
8224  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8225  */
8226 void
8227 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8228 {
8229 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8230 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8231 	queue_t		*q = ill->ill_rq;
8232 	t_uscalar_t	prim = dloa->dl_primitive;
8233 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8234 
8235 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8236 	    char *, dl_primstr(prim), ill_t *, ill);
8237 	ip1dbg(("ip_rput_dlpi"));
8238 
8239 	/*
8240 	 * If we received an ACK but didn't send a request for it, then it
8241 	 * can't be part of any pending operation; discard up-front.
8242 	 */
8243 	switch (prim) {
8244 	case DL_ERROR_ACK:
8245 		reqprim = dlea->dl_error_primitive;
8246 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8247 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8248 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8249 		    dlea->dl_unix_errno));
8250 		break;
8251 	case DL_OK_ACK:
8252 		reqprim = dloa->dl_correct_primitive;
8253 		break;
8254 	case DL_INFO_ACK:
8255 		reqprim = DL_INFO_REQ;
8256 		break;
8257 	case DL_BIND_ACK:
8258 		reqprim = DL_BIND_REQ;
8259 		break;
8260 	case DL_PHYS_ADDR_ACK:
8261 		reqprim = DL_PHYS_ADDR_REQ;
8262 		break;
8263 	case DL_NOTIFY_ACK:
8264 		reqprim = DL_NOTIFY_REQ;
8265 		break;
8266 	case DL_CAPABILITY_ACK:
8267 		reqprim = DL_CAPABILITY_REQ;
8268 		break;
8269 	}
8270 
8271 	if (prim != DL_NOTIFY_IND) {
8272 		if (reqprim == DL_PRIM_INVAL ||
8273 		    !ill_dlpi_pending(ill, reqprim)) {
8274 			/* Not a DLPI message we support or expected */
8275 			freemsg(mp);
8276 			return;
8277 		}
8278 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8279 		    dl_primstr(reqprim)));
8280 	}
8281 
8282 	switch (reqprim) {
8283 	case DL_UNBIND_REQ:
8284 		/*
8285 		 * NOTE: we mark the unbind as complete even if we got a
8286 		 * DL_ERROR_ACK, since there's not much else we can do.
8287 		 */
8288 		mutex_enter(&ill->ill_lock);
8289 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8290 		cv_signal(&ill->ill_cv);
8291 		mutex_exit(&ill->ill_lock);
8292 		break;
8293 
8294 	case DL_ENABMULTI_REQ:
8295 		if (prim == DL_OK_ACK) {
8296 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8297 				ill->ill_dlpi_multicast_state = IDS_OK;
8298 		}
8299 		break;
8300 	}
8301 
8302 	/*
8303 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8304 	 * need to become writer to continue to process it.  Because an
8305 	 * exclusive operation doesn't complete until replies to all queued
8306 	 * DLPI messages have been received, we know we're in the middle of an
8307 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8308 	 *
8309 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8310 	 * Since this is on the ill stream we unconditionally bump up the
8311 	 * refcount without doing ILL_CAN_LOOKUP().
8312 	 */
8313 	ill_refhold(ill);
8314 	if (prim == DL_NOTIFY_IND)
8315 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8316 	else
8317 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8318 }
8319 
8320 /*
8321  * Handling of DLPI messages that require exclusive access to the ipsq.
8322  *
8323  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8324  * happen here. (along with mi_copy_done)
8325  */
8326 /* ARGSUSED */
8327 static void
8328 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8329 {
8330 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8331 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8332 	int		err = 0;
8333 	ill_t		*ill = (ill_t *)q->q_ptr;
8334 	ipif_t		*ipif = NULL;
8335 	mblk_t		*mp1 = NULL;
8336 	conn_t		*connp = NULL;
8337 	t_uscalar_t	paddrreq;
8338 	mblk_t		*mp_hw;
8339 	boolean_t	success;
8340 	boolean_t	ioctl_aborted = B_FALSE;
8341 	boolean_t	log = B_TRUE;
8342 
8343 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8344 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8345 
8346 	ip1dbg(("ip_rput_dlpi_writer .."));
8347 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8348 	ASSERT(IAM_WRITER_ILL(ill));
8349 
8350 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8351 	/*
8352 	 * The current ioctl could have been aborted by the user and a new
8353 	 * ioctl to bring up another ill could have started. We could still
8354 	 * get a response from the driver later.
8355 	 */
8356 	if (ipif != NULL && ipif->ipif_ill != ill)
8357 		ioctl_aborted = B_TRUE;
8358 
8359 	switch (dloa->dl_primitive) {
8360 	case DL_ERROR_ACK:
8361 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8362 		    dl_primstr(dlea->dl_error_primitive)));
8363 
8364 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8365 		    char *, dl_primstr(dlea->dl_error_primitive),
8366 		    ill_t *, ill);
8367 
8368 		switch (dlea->dl_error_primitive) {
8369 		case DL_DISABMULTI_REQ:
8370 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8371 			break;
8372 		case DL_PROMISCON_REQ:
8373 		case DL_PROMISCOFF_REQ:
8374 		case DL_UNBIND_REQ:
8375 		case DL_ATTACH_REQ:
8376 		case DL_INFO_REQ:
8377 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8378 			break;
8379 		case DL_NOTIFY_REQ:
8380 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8381 			log = B_FALSE;
8382 			break;
8383 		case DL_PHYS_ADDR_REQ:
8384 			/*
8385 			 * For IPv6 only, there are two additional
8386 			 * phys_addr_req's sent to the driver to get the
8387 			 * IPv6 token and lla. This allows IP to acquire
8388 			 * the hardware address format for a given interface
8389 			 * without having built in knowledge of the hardware
8390 			 * address. ill_phys_addr_pend keeps track of the last
8391 			 * DL_PAR sent so we know which response we are
8392 			 * dealing with. ill_dlpi_done will update
8393 			 * ill_phys_addr_pend when it sends the next req.
8394 			 * We don't complete the IOCTL until all three DL_PARs
8395 			 * have been attempted, so set *_len to 0 and break.
8396 			 */
8397 			paddrreq = ill->ill_phys_addr_pend;
8398 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8399 			if (paddrreq == DL_IPV6_TOKEN) {
8400 				ill->ill_token_length = 0;
8401 				log = B_FALSE;
8402 				break;
8403 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8404 				ill->ill_nd_lla_len = 0;
8405 				log = B_FALSE;
8406 				break;
8407 			}
8408 			/*
8409 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8410 			 * We presumably have an IOCTL hanging out waiting
8411 			 * for completion. Find it and complete the IOCTL
8412 			 * with the error noted.
8413 			 * However, ill_dl_phys was called on an ill queue
8414 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8415 			 * set. But the ioctl is known to be pending on ill_wq.
8416 			 */
8417 			if (!ill->ill_ifname_pending)
8418 				break;
8419 			ill->ill_ifname_pending = 0;
8420 			if (!ioctl_aborted)
8421 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8422 			if (mp1 != NULL) {
8423 				/*
8424 				 * This operation (SIOCSLIFNAME) must have
8425 				 * happened on the ill. Assert there is no conn
8426 				 */
8427 				ASSERT(connp == NULL);
8428 				q = ill->ill_wq;
8429 			}
8430 			break;
8431 		case DL_BIND_REQ:
8432 			ill_dlpi_done(ill, DL_BIND_REQ);
8433 			if (ill->ill_ifname_pending)
8434 				break;
8435 			/*
8436 			 * Something went wrong with the bind.  We presumably
8437 			 * have an IOCTL hanging out waiting for completion.
8438 			 * Find it, take down the interface that was coming
8439 			 * up, and complete the IOCTL with the error noted.
8440 			 */
8441 			if (!ioctl_aborted)
8442 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8443 			if (mp1 != NULL) {
8444 				/*
8445 				 * This might be a result of a DL_NOTE_REPLUMB
8446 				 * notification. In that case, connp is NULL.
8447 				 */
8448 				if (connp != NULL)
8449 					q = CONNP_TO_WQ(connp);
8450 
8451 				(void) ipif_down(ipif, NULL, NULL);
8452 				/* error is set below the switch */
8453 			}
8454 			break;
8455 		case DL_ENABMULTI_REQ:
8456 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8457 
8458 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8459 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8460 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8461 
8462 				printf("ip: joining multicasts failed (%d)"
8463 				    " on %s - will use link layer "
8464 				    "broadcasts for multicast\n",
8465 				    dlea->dl_errno, ill->ill_name);
8466 
8467 				/*
8468 				 * Set up for multi_bcast; We are the
8469 				 * writer, so ok to access ill->ill_ipif
8470 				 * without any lock.
8471 				 */
8472 				mutex_enter(&ill->ill_phyint->phyint_lock);
8473 				ill->ill_phyint->phyint_flags |=
8474 				    PHYI_MULTI_BCAST;
8475 				mutex_exit(&ill->ill_phyint->phyint_lock);
8476 
8477 			}
8478 			freemsg(mp);	/* Don't want to pass this up */
8479 			return;
8480 		case DL_CAPABILITY_REQ:
8481 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8482 			    "DL_CAPABILITY REQ\n"));
8483 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8484 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8485 			ill_capability_done(ill);
8486 			freemsg(mp);
8487 			return;
8488 		}
8489 		/*
8490 		 * Note the error for IOCTL completion (mp1 is set when
8491 		 * ready to complete ioctl). If ill_ifname_pending_err is
8492 		 * set, an error occured during plumbing (ill_ifname_pending),
8493 		 * so we want to report that error.
8494 		 *
8495 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8496 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8497 		 * expected to get errack'd if the driver doesn't support
8498 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8499 		 * if these error conditions are encountered.
8500 		 */
8501 		if (mp1 != NULL) {
8502 			if (ill->ill_ifname_pending_err != 0)  {
8503 				err = ill->ill_ifname_pending_err;
8504 				ill->ill_ifname_pending_err = 0;
8505 			} else {
8506 				err = dlea->dl_unix_errno ?
8507 				    dlea->dl_unix_errno : ENXIO;
8508 			}
8509 		/*
8510 		 * If we're plumbing an interface and an error hasn't already
8511 		 * been saved, set ill_ifname_pending_err to the error passed
8512 		 * up. Ignore the error if log is B_FALSE (see comment above).
8513 		 */
8514 		} else if (log && ill->ill_ifname_pending &&
8515 		    ill->ill_ifname_pending_err == 0) {
8516 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8517 			    dlea->dl_unix_errno : ENXIO;
8518 		}
8519 
8520 		if (log)
8521 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8522 			    dlea->dl_errno, dlea->dl_unix_errno);
8523 		break;
8524 	case DL_CAPABILITY_ACK:
8525 		ill_capability_ack(ill, mp);
8526 		/*
8527 		 * The message has been handed off to ill_capability_ack
8528 		 * and must not be freed below
8529 		 */
8530 		mp = NULL;
8531 		break;
8532 
8533 	case DL_INFO_ACK:
8534 		/* Call a routine to handle this one. */
8535 		ill_dlpi_done(ill, DL_INFO_REQ);
8536 		ip_ll_subnet_defaults(ill, mp);
8537 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8538 		return;
8539 	case DL_BIND_ACK:
8540 		/*
8541 		 * We should have an IOCTL waiting on this unless
8542 		 * sent by ill_dl_phys, in which case just return
8543 		 */
8544 		ill_dlpi_done(ill, DL_BIND_REQ);
8545 		if (ill->ill_ifname_pending) {
8546 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8547 			    ill_t *, ill, mblk_t *, mp);
8548 			break;
8549 		}
8550 		if (!ioctl_aborted)
8551 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8552 		if (mp1 == NULL) {
8553 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8554 			break;
8555 		}
8556 		/*
8557 		 * mp1 was added by ill_dl_up(). if that is a result of
8558 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8559 		 */
8560 		if (connp != NULL)
8561 			q = CONNP_TO_WQ(connp);
8562 		/*
8563 		 * We are exclusive. So nothing can change even after
8564 		 * we get the pending mp.
8565 		 */
8566 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8567 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8568 
8569 		mutex_enter(&ill->ill_lock);
8570 		ill->ill_dl_up = 1;
8571 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8572 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8573 		mutex_exit(&ill->ill_lock);
8574 
8575 		/*
8576 		 * Now bring up the resolver; when that is complete, we'll
8577 		 * create IREs.  Note that we intentionally mirror what
8578 		 * ipif_up() would have done, because we got here by way of
8579 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8580 		 */
8581 		if (ill->ill_isv6) {
8582 			/*
8583 			 * v6 interfaces.
8584 			 * Unlike ARP which has to do another bind
8585 			 * and attach, once we get here we are
8586 			 * done with NDP
8587 			 */
8588 			(void) ipif_resolver_up(ipif, Res_act_initial);
8589 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8590 				err = ipif_up_done_v6(ipif);
8591 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8592 			/*
8593 			 * ARP and other v4 external resolvers.
8594 			 * Leave the pending mblk intact so that
8595 			 * the ioctl completes in ip_rput().
8596 			 */
8597 			if (connp != NULL)
8598 				mutex_enter(&connp->conn_lock);
8599 			mutex_enter(&ill->ill_lock);
8600 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8601 			mutex_exit(&ill->ill_lock);
8602 			if (connp != NULL)
8603 				mutex_exit(&connp->conn_lock);
8604 			if (success) {
8605 				err = ipif_resolver_up(ipif, Res_act_initial);
8606 				if (err == EINPROGRESS) {
8607 					freemsg(mp);
8608 					return;
8609 				}
8610 				ASSERT(arp_no_defense || err != 0);
8611 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8612 			} else {
8613 				/* The conn has started closing */
8614 				err = EINTR;
8615 			}
8616 		} else {
8617 			/*
8618 			 * This one is complete. Reply to pending ioctl.
8619 			 */
8620 			(void) ipif_resolver_up(ipif, Res_act_initial);
8621 			err = ipif_up_done(ipif);
8622 		}
8623 
8624 		if ((err == 0) && (ill->ill_up_ipifs)) {
8625 			err = ill_up_ipifs(ill, q, mp1);
8626 			if (err == EINPROGRESS) {
8627 				freemsg(mp);
8628 				return;
8629 			}
8630 		}
8631 
8632 		/*
8633 		 * If we have a moved ipif to bring up, and everything has
8634 		 * succeeded to this point, bring it up on the IPMP ill.
8635 		 * Otherwise, leave it down -- the admin can try to bring it
8636 		 * up by hand if need be.
8637 		 */
8638 		if (ill->ill_move_ipif != NULL) {
8639 			if (err != 0) {
8640 				ill->ill_move_ipif = NULL;
8641 			} else {
8642 				ipif = ill->ill_move_ipif;
8643 				ill->ill_move_ipif = NULL;
8644 				err = ipif_up(ipif, q, mp1);
8645 				if (err == EINPROGRESS) {
8646 					freemsg(mp);
8647 					return;
8648 				}
8649 			}
8650 		}
8651 		break;
8652 
8653 	case DL_NOTIFY_IND: {
8654 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8655 		uint_t orig_mtu;
8656 
8657 		switch (notify->dl_notification) {
8658 		case DL_NOTE_PHYS_ADDR:
8659 			err = ill_set_phys_addr(ill, mp);
8660 			break;
8661 
8662 		case DL_NOTE_REPLUMB:
8663 			/*
8664 			 * Directly return after calling ill_replumb().
8665 			 * Note that we should not free mp as it is reused
8666 			 * in the ill_replumb() function.
8667 			 */
8668 			err = ill_replumb(ill, mp);
8669 			return;
8670 
8671 		case DL_NOTE_FASTPATH_FLUSH:
8672 			nce_flush(ill, B_FALSE);
8673 			break;
8674 
8675 		case DL_NOTE_SDU_SIZE:
8676 			/*
8677 			 * The dce and fragmentation code can cope with
8678 			 * this changing while packets are being sent.
8679 			 * When packets are sent ip_output will discover
8680 			 * a change.
8681 			 *
8682 			 * Change the MTU size of the interface.
8683 			 */
8684 			mutex_enter(&ill->ill_lock);
8685 			ill->ill_current_frag = (uint_t)notify->dl_data;
8686 			if (ill->ill_current_frag > ill->ill_max_frag)
8687 				ill->ill_max_frag = ill->ill_current_frag;
8688 
8689 			orig_mtu = ill->ill_mtu;
8690 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8691 				ill->ill_mtu = ill->ill_current_frag;
8692 
8693 				/*
8694 				 * If ill_user_mtu was set (via
8695 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8696 				 */
8697 				if (ill->ill_user_mtu != 0 &&
8698 				    ill->ill_user_mtu < ill->ill_mtu)
8699 					ill->ill_mtu = ill->ill_user_mtu;
8700 
8701 				if (ill->ill_isv6) {
8702 					if (ill->ill_mtu < IPV6_MIN_MTU)
8703 						ill->ill_mtu = IPV6_MIN_MTU;
8704 				} else {
8705 					if (ill->ill_mtu < IP_MIN_MTU)
8706 						ill->ill_mtu = IP_MIN_MTU;
8707 				}
8708 			}
8709 			mutex_exit(&ill->ill_lock);
8710 			/*
8711 			 * Make sure all dce_generation checks find out
8712 			 * that ill_mtu has changed.
8713 			 */
8714 			if (orig_mtu != ill->ill_mtu) {
8715 				dce_increment_all_generations(ill->ill_isv6,
8716 				    ill->ill_ipst);
8717 			}
8718 
8719 			/*
8720 			 * Refresh IPMP meta-interface MTU if necessary.
8721 			 */
8722 			if (IS_UNDER_IPMP(ill))
8723 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8724 			break;
8725 
8726 		case DL_NOTE_LINK_UP:
8727 		case DL_NOTE_LINK_DOWN: {
8728 			/*
8729 			 * We are writer. ill / phyint / ipsq assocs stable.
8730 			 * The RUNNING flag reflects the state of the link.
8731 			 */
8732 			phyint_t *phyint = ill->ill_phyint;
8733 			uint64_t new_phyint_flags;
8734 			boolean_t changed = B_FALSE;
8735 			boolean_t went_up;
8736 
8737 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8738 			mutex_enter(&phyint->phyint_lock);
8739 
8740 			new_phyint_flags = went_up ?
8741 			    phyint->phyint_flags | PHYI_RUNNING :
8742 			    phyint->phyint_flags & ~PHYI_RUNNING;
8743 
8744 			if (IS_IPMP(ill)) {
8745 				new_phyint_flags = went_up ?
8746 				    new_phyint_flags & ~PHYI_FAILED :
8747 				    new_phyint_flags | PHYI_FAILED;
8748 			}
8749 
8750 			if (new_phyint_flags != phyint->phyint_flags) {
8751 				phyint->phyint_flags = new_phyint_flags;
8752 				changed = B_TRUE;
8753 			}
8754 			mutex_exit(&phyint->phyint_lock);
8755 			/*
8756 			 * ill_restart_dad handles the DAD restart and routing
8757 			 * socket notification logic.
8758 			 */
8759 			if (changed) {
8760 				ill_restart_dad(phyint->phyint_illv4, went_up);
8761 				ill_restart_dad(phyint->phyint_illv6, went_up);
8762 			}
8763 			break;
8764 		}
8765 		case DL_NOTE_PROMISC_ON_PHYS: {
8766 			phyint_t *phyint = ill->ill_phyint;
8767 
8768 			mutex_enter(&phyint->phyint_lock);
8769 			phyint->phyint_flags |= PHYI_PROMISC;
8770 			mutex_exit(&phyint->phyint_lock);
8771 			break;
8772 		}
8773 		case DL_NOTE_PROMISC_OFF_PHYS: {
8774 			phyint_t *phyint = ill->ill_phyint;
8775 
8776 			mutex_enter(&phyint->phyint_lock);
8777 			phyint->phyint_flags &= ~PHYI_PROMISC;
8778 			mutex_exit(&phyint->phyint_lock);
8779 			break;
8780 		}
8781 		case DL_NOTE_CAPAB_RENEG:
8782 			/*
8783 			 * Something changed on the driver side.
8784 			 * It wants us to renegotiate the capabilities
8785 			 * on this ill. One possible cause is the aggregation
8786 			 * interface under us where a port got added or
8787 			 * went away.
8788 			 *
8789 			 * If the capability negotiation is already done
8790 			 * or is in progress, reset the capabilities and
8791 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8792 			 * so that when the ack comes back, we can start
8793 			 * the renegotiation process.
8794 			 *
8795 			 * Note that if ill_capab_reneg is already B_TRUE
8796 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8797 			 * the capability resetting request has been sent
8798 			 * and the renegotiation has not been started yet;
8799 			 * nothing needs to be done in this case.
8800 			 */
8801 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8802 			ill_capability_reset(ill, B_TRUE);
8803 			ipsq_current_finish(ipsq);
8804 			break;
8805 		default:
8806 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8807 			    "type 0x%x for DL_NOTIFY_IND\n",
8808 			    notify->dl_notification));
8809 			break;
8810 		}
8811 
8812 		/*
8813 		 * As this is an asynchronous operation, we
8814 		 * should not call ill_dlpi_done
8815 		 */
8816 		break;
8817 	}
8818 	case DL_NOTIFY_ACK: {
8819 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8820 
8821 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8822 			ill->ill_note_link = 1;
8823 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8824 		break;
8825 	}
8826 	case DL_PHYS_ADDR_ACK: {
8827 		/*
8828 		 * As part of plumbing the interface via SIOCSLIFNAME,
8829 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8830 		 * whose answers we receive here.  As each answer is received,
8831 		 * we call ill_dlpi_done() to dispatch the next request as
8832 		 * we're processing the current one.  Once all answers have
8833 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8834 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8835 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8836 		 * available, but we know the ioctl is pending on ill_wq.)
8837 		 */
8838 		uint_t	paddrlen, paddroff;
8839 		uint8_t	*addr;
8840 
8841 		paddrreq = ill->ill_phys_addr_pend;
8842 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8843 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8844 		addr = mp->b_rptr + paddroff;
8845 
8846 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8847 		if (paddrreq == DL_IPV6_TOKEN) {
8848 			/*
8849 			 * bcopy to low-order bits of ill_token
8850 			 *
8851 			 * XXX Temporary hack - currently, all known tokens
8852 			 * are 64 bits, so I'll cheat for the moment.
8853 			 */
8854 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8855 			ill->ill_token_length = paddrlen;
8856 			break;
8857 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8858 			ASSERT(ill->ill_nd_lla_mp == NULL);
8859 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8860 			mp = NULL;
8861 			break;
8862 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8863 			ASSERT(ill->ill_dest_addr_mp == NULL);
8864 			ill->ill_dest_addr_mp = mp;
8865 			ill->ill_dest_addr = addr;
8866 			mp = NULL;
8867 			if (ill->ill_isv6) {
8868 				ill_setdesttoken(ill);
8869 				ipif_setdestlinklocal(ill->ill_ipif);
8870 			}
8871 			break;
8872 		}
8873 
8874 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8875 		ASSERT(ill->ill_phys_addr_mp == NULL);
8876 		if (!ill->ill_ifname_pending)
8877 			break;
8878 		ill->ill_ifname_pending = 0;
8879 		if (!ioctl_aborted)
8880 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8881 		if (mp1 != NULL) {
8882 			ASSERT(connp == NULL);
8883 			q = ill->ill_wq;
8884 		}
8885 		/*
8886 		 * If any error acks received during the plumbing sequence,
8887 		 * ill_ifname_pending_err will be set. Break out and send up
8888 		 * the error to the pending ioctl.
8889 		 */
8890 		if (ill->ill_ifname_pending_err != 0) {
8891 			err = ill->ill_ifname_pending_err;
8892 			ill->ill_ifname_pending_err = 0;
8893 			break;
8894 		}
8895 
8896 		ill->ill_phys_addr_mp = mp;
8897 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8898 		mp = NULL;
8899 
8900 		/*
8901 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8902 		 * provider doesn't support physical addresses.  We check both
8903 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8904 		 * not have physical addresses, but historically adversises a
8905 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8906 		 * its DL_PHYS_ADDR_ACK.
8907 		 */
8908 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8909 			ill->ill_phys_addr = NULL;
8910 		} else if (paddrlen != ill->ill_phys_addr_length) {
8911 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8912 			    paddrlen, ill->ill_phys_addr_length));
8913 			err = EINVAL;
8914 			break;
8915 		}
8916 
8917 		if (ill->ill_nd_lla_mp == NULL) {
8918 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8919 				err = ENOMEM;
8920 				break;
8921 			}
8922 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8923 		}
8924 
8925 		if (ill->ill_isv6) {
8926 			ill_setdefaulttoken(ill);
8927 			ipif_setlinklocal(ill->ill_ipif);
8928 		}
8929 		break;
8930 	}
8931 	case DL_OK_ACK:
8932 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8933 		    dl_primstr((int)dloa->dl_correct_primitive),
8934 		    dloa->dl_correct_primitive));
8935 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8936 		    char *, dl_primstr(dloa->dl_correct_primitive),
8937 		    ill_t *, ill);
8938 
8939 		switch (dloa->dl_correct_primitive) {
8940 		case DL_ENABMULTI_REQ:
8941 		case DL_DISABMULTI_REQ:
8942 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8943 			break;
8944 		case DL_PROMISCON_REQ:
8945 		case DL_PROMISCOFF_REQ:
8946 		case DL_UNBIND_REQ:
8947 		case DL_ATTACH_REQ:
8948 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8949 			break;
8950 		}
8951 		break;
8952 	default:
8953 		break;
8954 	}
8955 
8956 	freemsg(mp);
8957 	if (mp1 == NULL)
8958 		return;
8959 
8960 	/*
8961 	 * The operation must complete without EINPROGRESS since
8962 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8963 	 * the operation will be stuck forever inside the IPSQ.
8964 	 */
8965 	ASSERT(err != EINPROGRESS);
8966 
8967 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8968 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8969 	    ipif_t *, NULL);
8970 
8971 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8972 	case 0:
8973 		ipsq_current_finish(ipsq);
8974 		break;
8975 
8976 	case SIOCSLIFNAME:
8977 	case IF_UNITSEL: {
8978 		ill_t *ill_other = ILL_OTHER(ill);
8979 
8980 		/*
8981 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8982 		 * ill has a peer which is in an IPMP group, then place ill
8983 		 * into the same group.  One catch: although ifconfig plumbs
8984 		 * the appropriate IPMP meta-interface prior to plumbing this
8985 		 * ill, it is possible for multiple ifconfig applications to
8986 		 * race (or for another application to adjust plumbing), in
8987 		 * which case the IPMP meta-interface we need will be missing.
8988 		 * If so, kick the phyint out of the group.
8989 		 */
8990 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8991 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8992 			ipmp_illgrp_t	*illg;
8993 
8994 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8995 			if (illg == NULL)
8996 				ipmp_phyint_leave_grp(ill->ill_phyint);
8997 			else
8998 				ipmp_ill_join_illgrp(ill, illg);
8999 		}
9000 
9001 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
9002 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9003 		else
9004 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9005 		break;
9006 	}
9007 	case SIOCLIFADDIF:
9008 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
9009 		break;
9010 
9011 	default:
9012 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
9013 		break;
9014 	}
9015 }
9016 
9017 /*
9018  * ip_rput_other is called by ip_rput to handle messages modifying the global
9019  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
9020  */
9021 /* ARGSUSED */
9022 void
9023 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
9024 {
9025 	ill_t		*ill = q->q_ptr;
9026 	struct iocblk	*iocp;
9027 
9028 	ip1dbg(("ip_rput_other "));
9029 	if (ipsq != NULL) {
9030 		ASSERT(IAM_WRITER_IPSQ(ipsq));
9031 		ASSERT(ipsq->ipsq_xop ==
9032 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
9033 	}
9034 
9035 	switch (mp->b_datap->db_type) {
9036 	case M_ERROR:
9037 	case M_HANGUP:
9038 		/*
9039 		 * The device has a problem.  We force the ILL down.  It can
9040 		 * be brought up again manually using SIOCSIFFLAGS (via
9041 		 * ifconfig or equivalent).
9042 		 */
9043 		ASSERT(ipsq != NULL);
9044 		if (mp->b_rptr < mp->b_wptr)
9045 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
9046 		if (ill->ill_error == 0)
9047 			ill->ill_error = ENXIO;
9048 		if (!ill_down_start(q, mp))
9049 			return;
9050 		ipif_all_down_tail(ipsq, q, mp, NULL);
9051 		break;
9052 	case M_IOCNAK: {
9053 		iocp = (struct iocblk *)mp->b_rptr;
9054 
9055 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
9056 		/*
9057 		 * If this was the first attempt, turn off the fastpath
9058 		 * probing.
9059 		 */
9060 		mutex_enter(&ill->ill_lock);
9061 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
9062 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
9063 			mutex_exit(&ill->ill_lock);
9064 			/*
9065 			 * don't flush the nce_t entries: we use them
9066 			 * as an index to the ncec itself.
9067 			 */
9068 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
9069 			    ill->ill_name));
9070 		} else {
9071 			mutex_exit(&ill->ill_lock);
9072 		}
9073 		freemsg(mp);
9074 		break;
9075 	}
9076 	default:
9077 		ASSERT(0);
9078 		break;
9079 	}
9080 }
9081 
9082 /*
9083  * Update any source route, record route or timestamp options
9084  * When it fails it has consumed the message and BUMPed the MIB.
9085  */
9086 boolean_t
9087 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
9088     ip_recv_attr_t *ira)
9089 {
9090 	ipoptp_t	opts;
9091 	uchar_t		*opt;
9092 	uint8_t		optval;
9093 	uint8_t		optlen;
9094 	ipaddr_t	dst;
9095 	ipaddr_t	ifaddr;
9096 	uint32_t	ts;
9097 	timestruc_t	now;
9098 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9099 
9100 	ip2dbg(("ip_forward_options\n"));
9101 	dst = ipha->ipha_dst;
9102 	for (optval = ipoptp_first(&opts, ipha);
9103 	    optval != IPOPT_EOL;
9104 	    optval = ipoptp_next(&opts)) {
9105 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9106 		opt = opts.ipoptp_cur;
9107 		optlen = opts.ipoptp_len;
9108 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
9109 		    optval, opts.ipoptp_len));
9110 		switch (optval) {
9111 			uint32_t off;
9112 		case IPOPT_SSRR:
9113 		case IPOPT_LSRR:
9114 			/* Check if adminstratively disabled */
9115 			if (!ipst->ips_ip_forward_src_routed) {
9116 				BUMP_MIB(dst_ill->ill_ip_mib,
9117 				    ipIfStatsForwProhibits);
9118 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9119 				    mp, dst_ill);
9120 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9121 				    ira);
9122 				return (B_FALSE);
9123 			}
9124 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9125 				/*
9126 				 * Must be partial since ip_input_options
9127 				 * checked for strict.
9128 				 */
9129 				break;
9130 			}
9131 			off = opt[IPOPT_OFFSET];
9132 			off--;
9133 		redo_srr:
9134 			if (optlen < IP_ADDR_LEN ||
9135 			    off > optlen - IP_ADDR_LEN) {
9136 				/* End of source route */
9137 				ip1dbg((
9138 				    "ip_forward_options: end of SR\n"));
9139 				break;
9140 			}
9141 			/* Pick a reasonable address on the outbound if */
9142 			ASSERT(dst_ill != NULL);
9143 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9144 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9145 			    NULL) != 0) {
9146 				/* No source! Shouldn't happen */
9147 				ifaddr = INADDR_ANY;
9148 			}
9149 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9150 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9151 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9152 			    ntohl(dst)));
9153 
9154 			/*
9155 			 * Check if our address is present more than
9156 			 * once as consecutive hops in source route.
9157 			 */
9158 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9159 				off += IP_ADDR_LEN;
9160 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9161 				goto redo_srr;
9162 			}
9163 			ipha->ipha_dst = dst;
9164 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9165 			break;
9166 		case IPOPT_RR:
9167 			off = opt[IPOPT_OFFSET];
9168 			off--;
9169 			if (optlen < IP_ADDR_LEN ||
9170 			    off > optlen - IP_ADDR_LEN) {
9171 				/* No more room - ignore */
9172 				ip1dbg((
9173 				    "ip_forward_options: end of RR\n"));
9174 				break;
9175 			}
9176 			/* Pick a reasonable address on the outbound if */
9177 			ASSERT(dst_ill != NULL);
9178 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9179 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9180 			    NULL) != 0) {
9181 				/* No source! Shouldn't happen */
9182 				ifaddr = INADDR_ANY;
9183 			}
9184 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9185 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9186 			break;
9187 		case IPOPT_TS:
9188 			/* Insert timestamp if there is room */
9189 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9190 			case IPOPT_TS_TSONLY:
9191 				off = IPOPT_TS_TIMELEN;
9192 				break;
9193 			case IPOPT_TS_PRESPEC:
9194 			case IPOPT_TS_PRESPEC_RFC791:
9195 				/* Verify that the address matched */
9196 				off = opt[IPOPT_OFFSET] - 1;
9197 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9198 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9199 					/* Not for us */
9200 					break;
9201 				}
9202 				/* FALLTHRU */
9203 			case IPOPT_TS_TSANDADDR:
9204 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9205 				break;
9206 			default:
9207 				/*
9208 				 * ip_*put_options should have already
9209 				 * dropped this packet.
9210 				 */
9211 				cmn_err(CE_PANIC, "ip_forward_options: "
9212 				    "unknown IT - bug in ip_input_options?\n");
9213 				return (B_TRUE);	/* Keep "lint" happy */
9214 			}
9215 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9216 				/* Increase overflow counter */
9217 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9218 				opt[IPOPT_POS_OV_FLG] =
9219 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9220 				    (off << 4));
9221 				break;
9222 			}
9223 			off = opt[IPOPT_OFFSET] - 1;
9224 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9225 			case IPOPT_TS_PRESPEC:
9226 			case IPOPT_TS_PRESPEC_RFC791:
9227 			case IPOPT_TS_TSANDADDR:
9228 				/* Pick a reasonable addr on the outbound if */
9229 				ASSERT(dst_ill != NULL);
9230 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9231 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9232 				    NULL, NULL) != 0) {
9233 					/* No source! Shouldn't happen */
9234 					ifaddr = INADDR_ANY;
9235 				}
9236 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9237 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9238 				/* FALLTHRU */
9239 			case IPOPT_TS_TSONLY:
9240 				off = opt[IPOPT_OFFSET] - 1;
9241 				/* Compute # of milliseconds since midnight */
9242 				gethrestime(&now);
9243 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9244 				    now.tv_nsec / (NANOSEC / MILLISEC);
9245 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9246 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9247 				break;
9248 			}
9249 			break;
9250 		}
9251 	}
9252 	return (B_TRUE);
9253 }
9254 
9255 /*
9256  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9257  * returns 'true' if there are still fragments left on the queue, in
9258  * which case we restart the timer.
9259  */
9260 void
9261 ill_frag_timer(void *arg)
9262 {
9263 	ill_t	*ill = (ill_t *)arg;
9264 	boolean_t frag_pending;
9265 	ip_stack_t	*ipst = ill->ill_ipst;
9266 	time_t	timeout;
9267 
9268 	mutex_enter(&ill->ill_lock);
9269 	ASSERT(!ill->ill_fragtimer_executing);
9270 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9271 		ill->ill_frag_timer_id = 0;
9272 		mutex_exit(&ill->ill_lock);
9273 		return;
9274 	}
9275 	ill->ill_fragtimer_executing = 1;
9276 	mutex_exit(&ill->ill_lock);
9277 
9278 	if (ill->ill_isv6)
9279 		timeout = ipst->ips_ipv6_frag_timeout;
9280 	else
9281 		timeout = ipst->ips_ip_g_frag_timeout;
9282 
9283 	frag_pending = ill_frag_timeout(ill, timeout);
9284 
9285 	/*
9286 	 * Restart the timer, if we have fragments pending or if someone
9287 	 * wanted us to be scheduled again.
9288 	 */
9289 	mutex_enter(&ill->ill_lock);
9290 	ill->ill_fragtimer_executing = 0;
9291 	ill->ill_frag_timer_id = 0;
9292 	if (frag_pending || ill->ill_fragtimer_needrestart)
9293 		ill_frag_timer_start(ill);
9294 	mutex_exit(&ill->ill_lock);
9295 }
9296 
9297 void
9298 ill_frag_timer_start(ill_t *ill)
9299 {
9300 	ip_stack_t	*ipst = ill->ill_ipst;
9301 	clock_t	timeo_ms;
9302 
9303 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9304 
9305 	/* If the ill is closing or opening don't proceed */
9306 	if (ill->ill_state_flags & ILL_CONDEMNED)
9307 		return;
9308 
9309 	if (ill->ill_fragtimer_executing) {
9310 		/*
9311 		 * ill_frag_timer is currently executing. Just record the
9312 		 * the fact that we want the timer to be restarted.
9313 		 * ill_frag_timer will post a timeout before it returns,
9314 		 * ensuring it will be called again.
9315 		 */
9316 		ill->ill_fragtimer_needrestart = 1;
9317 		return;
9318 	}
9319 
9320 	if (ill->ill_frag_timer_id == 0) {
9321 		if (ill->ill_isv6)
9322 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
9323 		else
9324 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
9325 		/*
9326 		 * The timer is neither running nor is the timeout handler
9327 		 * executing. Post a timeout so that ill_frag_timer will be
9328 		 * called
9329 		 */
9330 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9331 		    MSEC_TO_TICK(timeo_ms >> 1));
9332 		ill->ill_fragtimer_needrestart = 0;
9333 	}
9334 }
9335 
9336 /*
9337  * Update any source route, record route or timestamp options.
9338  * Check that we are at end of strict source route.
9339  * The options have already been checked for sanity in ip_input_options().
9340  */
9341 boolean_t
9342 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9343 {
9344 	ipoptp_t	opts;
9345 	uchar_t		*opt;
9346 	uint8_t		optval;
9347 	uint8_t		optlen;
9348 	ipaddr_t	dst;
9349 	ipaddr_t	ifaddr;
9350 	uint32_t	ts;
9351 	timestruc_t	now;
9352 	ill_t		*ill = ira->ira_ill;
9353 	ip_stack_t	*ipst = ill->ill_ipst;
9354 
9355 	ip2dbg(("ip_input_local_options\n"));
9356 
9357 	for (optval = ipoptp_first(&opts, ipha);
9358 	    optval != IPOPT_EOL;
9359 	    optval = ipoptp_next(&opts)) {
9360 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9361 		opt = opts.ipoptp_cur;
9362 		optlen = opts.ipoptp_len;
9363 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9364 		    optval, optlen));
9365 		switch (optval) {
9366 			uint32_t off;
9367 		case IPOPT_SSRR:
9368 		case IPOPT_LSRR:
9369 			off = opt[IPOPT_OFFSET];
9370 			off--;
9371 			if (optlen < IP_ADDR_LEN ||
9372 			    off > optlen - IP_ADDR_LEN) {
9373 				/* End of source route */
9374 				ip1dbg(("ip_input_local_options: end of SR\n"));
9375 				break;
9376 			}
9377 			/*
9378 			 * This will only happen if two consecutive entries
9379 			 * in the source route contains our address or if
9380 			 * it is a packet with a loose source route which
9381 			 * reaches us before consuming the whole source route
9382 			 */
9383 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9384 			if (optval == IPOPT_SSRR) {
9385 				goto bad_src_route;
9386 			}
9387 			/*
9388 			 * Hack: instead of dropping the packet truncate the
9389 			 * source route to what has been used by filling the
9390 			 * rest with IPOPT_NOP.
9391 			 */
9392 			opt[IPOPT_OLEN] = (uint8_t)off;
9393 			while (off < optlen) {
9394 				opt[off++] = IPOPT_NOP;
9395 			}
9396 			break;
9397 		case IPOPT_RR:
9398 			off = opt[IPOPT_OFFSET];
9399 			off--;
9400 			if (optlen < IP_ADDR_LEN ||
9401 			    off > optlen - IP_ADDR_LEN) {
9402 				/* No more room - ignore */
9403 				ip1dbg((
9404 				    "ip_input_local_options: end of RR\n"));
9405 				break;
9406 			}
9407 			/* Pick a reasonable address on the outbound if */
9408 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9409 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9410 			    NULL) != 0) {
9411 				/* No source! Shouldn't happen */
9412 				ifaddr = INADDR_ANY;
9413 			}
9414 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9415 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9416 			break;
9417 		case IPOPT_TS:
9418 			/* Insert timestamp if there is romm */
9419 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9420 			case IPOPT_TS_TSONLY:
9421 				off = IPOPT_TS_TIMELEN;
9422 				break;
9423 			case IPOPT_TS_PRESPEC:
9424 			case IPOPT_TS_PRESPEC_RFC791:
9425 				/* Verify that the address matched */
9426 				off = opt[IPOPT_OFFSET] - 1;
9427 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9428 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9429 					/* Not for us */
9430 					break;
9431 				}
9432 				/* FALLTHRU */
9433 			case IPOPT_TS_TSANDADDR:
9434 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9435 				break;
9436 			default:
9437 				/*
9438 				 * ip_*put_options should have already
9439 				 * dropped this packet.
9440 				 */
9441 				cmn_err(CE_PANIC, "ip_input_local_options: "
9442 				    "unknown IT - bug in ip_input_options?\n");
9443 				return (B_TRUE);	/* Keep "lint" happy */
9444 			}
9445 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9446 				/* Increase overflow counter */
9447 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9448 				opt[IPOPT_POS_OV_FLG] =
9449 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9450 				    (off << 4));
9451 				break;
9452 			}
9453 			off = opt[IPOPT_OFFSET] - 1;
9454 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9455 			case IPOPT_TS_PRESPEC:
9456 			case IPOPT_TS_PRESPEC_RFC791:
9457 			case IPOPT_TS_TSANDADDR:
9458 				/* Pick a reasonable addr on the outbound if */
9459 				if (ip_select_source_v4(ill, INADDR_ANY,
9460 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9461 				    &ifaddr, NULL, NULL) != 0) {
9462 					/* No source! Shouldn't happen */
9463 					ifaddr = INADDR_ANY;
9464 				}
9465 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9466 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9467 				/* FALLTHRU */
9468 			case IPOPT_TS_TSONLY:
9469 				off = opt[IPOPT_OFFSET] - 1;
9470 				/* Compute # of milliseconds since midnight */
9471 				gethrestime(&now);
9472 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9473 				    now.tv_nsec / (NANOSEC / MILLISEC);
9474 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9475 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9476 				break;
9477 			}
9478 			break;
9479 		}
9480 	}
9481 	return (B_TRUE);
9482 
9483 bad_src_route:
9484 	/* make sure we clear any indication of a hardware checksum */
9485 	DB_CKSUMFLAGS(mp) = 0;
9486 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9487 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9488 	return (B_FALSE);
9489 
9490 }
9491 
9492 /*
9493  * Process IP options in an inbound packet.  Always returns the nexthop.
9494  * Normally this is the passed in nexthop, but if there is an option
9495  * that effects the nexthop (such as a source route) that will be returned.
9496  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9497  * and mp freed.
9498  */
9499 ipaddr_t
9500 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9501     ip_recv_attr_t *ira, int *errorp)
9502 {
9503 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9504 	ipoptp_t	opts;
9505 	uchar_t		*opt;
9506 	uint8_t		optval;
9507 	uint8_t		optlen;
9508 	intptr_t	code = 0;
9509 	ire_t		*ire;
9510 
9511 	ip2dbg(("ip_input_options\n"));
9512 	*errorp = 0;
9513 	for (optval = ipoptp_first(&opts, ipha);
9514 	    optval != IPOPT_EOL;
9515 	    optval = ipoptp_next(&opts)) {
9516 		opt = opts.ipoptp_cur;
9517 		optlen = opts.ipoptp_len;
9518 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9519 		    optval, optlen));
9520 		/*
9521 		 * Note: we need to verify the checksum before we
9522 		 * modify anything thus this routine only extracts the next
9523 		 * hop dst from any source route.
9524 		 */
9525 		switch (optval) {
9526 			uint32_t off;
9527 		case IPOPT_SSRR:
9528 		case IPOPT_LSRR:
9529 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9530 				if (optval == IPOPT_SSRR) {
9531 					ip1dbg(("ip_input_options: not next"
9532 					    " strict source route 0x%x\n",
9533 					    ntohl(dst)));
9534 					code = (char *)&ipha->ipha_dst -
9535 					    (char *)ipha;
9536 					goto param_prob; /* RouterReq's */
9537 				}
9538 				ip2dbg(("ip_input_options: "
9539 				    "not next source route 0x%x\n",
9540 				    ntohl(dst)));
9541 				break;
9542 			}
9543 
9544 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9545 				ip1dbg((
9546 				    "ip_input_options: bad option offset\n"));
9547 				code = (char *)&opt[IPOPT_OLEN] -
9548 				    (char *)ipha;
9549 				goto param_prob;
9550 			}
9551 			off = opt[IPOPT_OFFSET];
9552 			off--;
9553 		redo_srr:
9554 			if (optlen < IP_ADDR_LEN ||
9555 			    off > optlen - IP_ADDR_LEN) {
9556 				/* End of source route */
9557 				ip1dbg(("ip_input_options: end of SR\n"));
9558 				break;
9559 			}
9560 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9561 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9562 			    ntohl(dst)));
9563 
9564 			/*
9565 			 * Check if our address is present more than
9566 			 * once as consecutive hops in source route.
9567 			 * XXX verify per-interface ip_forwarding
9568 			 * for source route?
9569 			 */
9570 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9571 				off += IP_ADDR_LEN;
9572 				goto redo_srr;
9573 			}
9574 
9575 			if (dst == htonl(INADDR_LOOPBACK)) {
9576 				ip1dbg(("ip_input_options: loopback addr in "
9577 				    "source route!\n"));
9578 				goto bad_src_route;
9579 			}
9580 			/*
9581 			 * For strict: verify that dst is directly
9582 			 * reachable.
9583 			 */
9584 			if (optval == IPOPT_SSRR) {
9585 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9586 				    IRE_IF_ALL, NULL, ALL_ZONES,
9587 				    ira->ira_tsl,
9588 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9589 				    NULL);
9590 				if (ire == NULL) {
9591 					ip1dbg(("ip_input_options: SSRR not "
9592 					    "directly reachable: 0x%x\n",
9593 					    ntohl(dst)));
9594 					goto bad_src_route;
9595 				}
9596 				ire_refrele(ire);
9597 			}
9598 			/*
9599 			 * Defer update of the offset and the record route
9600 			 * until the packet is forwarded.
9601 			 */
9602 			break;
9603 		case IPOPT_RR:
9604 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9605 				ip1dbg((
9606 				    "ip_input_options: bad option offset\n"));
9607 				code = (char *)&opt[IPOPT_OLEN] -
9608 				    (char *)ipha;
9609 				goto param_prob;
9610 			}
9611 			break;
9612 		case IPOPT_TS:
9613 			/*
9614 			 * Verify that length >= 5 and that there is either
9615 			 * room for another timestamp or that the overflow
9616 			 * counter is not maxed out.
9617 			 */
9618 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9619 			if (optlen < IPOPT_MINLEN_IT) {
9620 				goto param_prob;
9621 			}
9622 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9623 				ip1dbg((
9624 				    "ip_input_options: bad option offset\n"));
9625 				code = (char *)&opt[IPOPT_OFFSET] -
9626 				    (char *)ipha;
9627 				goto param_prob;
9628 			}
9629 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9630 			case IPOPT_TS_TSONLY:
9631 				off = IPOPT_TS_TIMELEN;
9632 				break;
9633 			case IPOPT_TS_TSANDADDR:
9634 			case IPOPT_TS_PRESPEC:
9635 			case IPOPT_TS_PRESPEC_RFC791:
9636 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9637 				break;
9638 			default:
9639 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9640 				    (char *)ipha;
9641 				goto param_prob;
9642 			}
9643 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9644 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9645 				/*
9646 				 * No room and the overflow counter is 15
9647 				 * already.
9648 				 */
9649 				goto param_prob;
9650 			}
9651 			break;
9652 		}
9653 	}
9654 
9655 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9656 		return (dst);
9657 	}
9658 
9659 	ip1dbg(("ip_input_options: error processing IP options."));
9660 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9661 
9662 param_prob:
9663 	/* make sure we clear any indication of a hardware checksum */
9664 	DB_CKSUMFLAGS(mp) = 0;
9665 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9666 	icmp_param_problem(mp, (uint8_t)code, ira);
9667 	*errorp = -1;
9668 	return (dst);
9669 
9670 bad_src_route:
9671 	/* make sure we clear any indication of a hardware checksum */
9672 	DB_CKSUMFLAGS(mp) = 0;
9673 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9674 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9675 	*errorp = -1;
9676 	return (dst);
9677 }
9678 
9679 /*
9680  * IP & ICMP info in >=14 msg's ...
9681  *  - ip fixed part (mib2_ip_t)
9682  *  - icmp fixed part (mib2_icmp_t)
9683  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9684  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9685  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9686  *  - ipRouteAttributeTable (ip 102)	labeled routes
9687  *  - ip multicast membership (ip_member_t)
9688  *  - ip multicast source filtering (ip_grpsrc_t)
9689  *  - igmp fixed part (struct igmpstat)
9690  *  - multicast routing stats (struct mrtstat)
9691  *  - multicast routing vifs (array of struct vifctl)
9692  *  - multicast routing routes (array of struct mfcctl)
9693  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9694  *					One per ill plus one generic
9695  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9696  *					One per ill plus one generic
9697  *  - ipv6RouteEntry			all IPv6 IREs
9698  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9699  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9700  *  - ipv6AddrEntry			all IPv6 ipifs
9701  *  - ipv6 multicast membership (ipv6_member_t)
9702  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9703  *
9704  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9705  * already filled in by the caller.
9706  * Return value of 0 indicates that no messages were sent and caller
9707  * should free mpctl.
9708  */
9709 int
9710 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
9711 {
9712 	ip_stack_t *ipst;
9713 	sctp_stack_t *sctps;
9714 
9715 	if (q->q_next != NULL) {
9716 		ipst = ILLQ_TO_IPST(q);
9717 	} else {
9718 		ipst = CONNQ_TO_IPST(q);
9719 	}
9720 	ASSERT(ipst != NULL);
9721 	sctps = ipst->ips_netstack->netstack_sctp;
9722 
9723 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9724 		return (0);
9725 	}
9726 
9727 	/*
9728 	 * For the purposes of the (broken) packet shell use
9729 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9730 	 * to make TCP and UDP appear first in the list of mib items.
9731 	 * TBD: We could expand this and use it in netstat so that
9732 	 * the kernel doesn't have to produce large tables (connections,
9733 	 * routes, etc) when netstat only wants the statistics or a particular
9734 	 * table.
9735 	 */
9736 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9737 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9738 			return (1);
9739 		}
9740 	}
9741 
9742 	if (level != MIB2_TCP) {
9743 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
9744 			return (1);
9745 		}
9746 	}
9747 
9748 	if (level != MIB2_UDP) {
9749 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
9750 			return (1);
9751 		}
9752 	}
9753 
9754 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9755 	    ipst)) == NULL) {
9756 		return (1);
9757 	}
9758 
9759 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
9760 		return (1);
9761 	}
9762 
9763 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9764 		return (1);
9765 	}
9766 
9767 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9768 		return (1);
9769 	}
9770 
9771 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9772 		return (1);
9773 	}
9774 
9775 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9776 		return (1);
9777 	}
9778 
9779 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
9780 		return (1);
9781 	}
9782 
9783 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
9784 		return (1);
9785 	}
9786 
9787 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9788 		return (1);
9789 	}
9790 
9791 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9792 		return (1);
9793 	}
9794 
9795 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9796 		return (1);
9797 	}
9798 
9799 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9800 		return (1);
9801 	}
9802 
9803 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9804 		return (1);
9805 	}
9806 
9807 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9808 		return (1);
9809 	}
9810 
9811 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9812 	if (mpctl == NULL)
9813 		return (1);
9814 
9815 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9816 	if (mpctl == NULL)
9817 		return (1);
9818 
9819 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9820 		return (1);
9821 	}
9822 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9823 		return (1);
9824 	}
9825 	freemsg(mpctl);
9826 	return (1);
9827 }
9828 
9829 /* Get global (legacy) IPv4 statistics */
9830 static mblk_t *
9831 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9832     ip_stack_t *ipst)
9833 {
9834 	mib2_ip_t		old_ip_mib;
9835 	struct opthdr		*optp;
9836 	mblk_t			*mp2ctl;
9837 
9838 	/*
9839 	 * make a copy of the original message
9840 	 */
9841 	mp2ctl = copymsg(mpctl);
9842 
9843 	/* fixed length IP structure... */
9844 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9845 	optp->level = MIB2_IP;
9846 	optp->name = 0;
9847 	SET_MIB(old_ip_mib.ipForwarding,
9848 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9849 	SET_MIB(old_ip_mib.ipDefaultTTL,
9850 	    (uint32_t)ipst->ips_ip_def_ttl);
9851 	SET_MIB(old_ip_mib.ipReasmTimeout,
9852 	    ipst->ips_ip_g_frag_timeout);
9853 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9854 	    sizeof (mib2_ipAddrEntry_t));
9855 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9856 	    sizeof (mib2_ipRouteEntry_t));
9857 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9858 	    sizeof (mib2_ipNetToMediaEntry_t));
9859 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9860 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9861 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9862 	    sizeof (mib2_ipAttributeEntry_t));
9863 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9864 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9865 
9866 	/*
9867 	 * Grab the statistics from the new IP MIB
9868 	 */
9869 	SET_MIB(old_ip_mib.ipInReceives,
9870 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9871 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9872 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9873 	SET_MIB(old_ip_mib.ipForwDatagrams,
9874 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9875 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9876 	    ipmib->ipIfStatsInUnknownProtos);
9877 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9878 	SET_MIB(old_ip_mib.ipInDelivers,
9879 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9880 	SET_MIB(old_ip_mib.ipOutRequests,
9881 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9882 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9883 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9884 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9885 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9886 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9887 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9888 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9889 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9890 
9891 	/* ipRoutingDiscards is not being used */
9892 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9893 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9894 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9895 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9896 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9897 	    ipmib->ipIfStatsReasmDuplicates);
9898 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9899 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9900 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9901 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9902 	SET_MIB(old_ip_mib.rawipInOverflows,
9903 	    ipmib->rawipIfStatsInOverflows);
9904 
9905 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9906 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9907 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9908 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9909 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9910 	    ipmib->ipIfStatsOutSwitchIPVersion);
9911 
9912 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9913 	    (int)sizeof (old_ip_mib))) {
9914 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9915 		    (uint_t)sizeof (old_ip_mib)));
9916 	}
9917 
9918 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9919 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9920 	    (int)optp->level, (int)optp->name, (int)optp->len));
9921 	qreply(q, mpctl);
9922 	return (mp2ctl);
9923 }
9924 
9925 /* Per interface IPv4 statistics */
9926 static mblk_t *
9927 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9928 {
9929 	struct opthdr		*optp;
9930 	mblk_t			*mp2ctl;
9931 	ill_t			*ill;
9932 	ill_walk_context_t	ctx;
9933 	mblk_t			*mp_tail = NULL;
9934 	mib2_ipIfStatsEntry_t	global_ip_mib;
9935 
9936 	/*
9937 	 * Make a copy of the original message
9938 	 */
9939 	mp2ctl = copymsg(mpctl);
9940 
9941 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9942 	optp->level = MIB2_IP;
9943 	optp->name = MIB2_IP_TRAFFIC_STATS;
9944 	/* Include "unknown interface" ip_mib */
9945 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9946 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9947 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9948 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9949 	    (ipst->ips_ip_g_forward ? 1 : 2));
9950 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9951 	    (uint32_t)ipst->ips_ip_def_ttl);
9952 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9953 	    sizeof (mib2_ipIfStatsEntry_t));
9954 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9955 	    sizeof (mib2_ipAddrEntry_t));
9956 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9957 	    sizeof (mib2_ipRouteEntry_t));
9958 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9959 	    sizeof (mib2_ipNetToMediaEntry_t));
9960 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9961 	    sizeof (ip_member_t));
9962 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9963 	    sizeof (ip_grpsrc_t));
9964 
9965 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9966 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
9967 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9968 		    "failed to allocate %u bytes\n",
9969 		    (uint_t)sizeof (ipst->ips_ip_mib)));
9970 	}
9971 
9972 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9973 
9974 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9975 	ill = ILL_START_WALK_V4(&ctx, ipst);
9976 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9977 		ill->ill_ip_mib->ipIfStatsIfIndex =
9978 		    ill->ill_phyint->phyint_ifindex;
9979 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9980 		    (ipst->ips_ip_g_forward ? 1 : 2));
9981 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9982 		    (uint32_t)ipst->ips_ip_def_ttl);
9983 
9984 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9985 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9986 		    (char *)ill->ill_ip_mib,
9987 		    (int)sizeof (*ill->ill_ip_mib))) {
9988 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9989 			    "failed to allocate %u bytes\n",
9990 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9991 		}
9992 	}
9993 	rw_exit(&ipst->ips_ill_g_lock);
9994 
9995 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9996 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9997 	    "level %d, name %d, len %d\n",
9998 	    (int)optp->level, (int)optp->name, (int)optp->len));
9999 	qreply(q, mpctl);
10000 
10001 	if (mp2ctl == NULL)
10002 		return (NULL);
10003 
10004 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
10005 }
10006 
10007 /* Global IPv4 ICMP statistics */
10008 static mblk_t *
10009 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10010 {
10011 	struct opthdr		*optp;
10012 	mblk_t			*mp2ctl;
10013 
10014 	/*
10015 	 * Make a copy of the original message
10016 	 */
10017 	mp2ctl = copymsg(mpctl);
10018 
10019 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10020 	optp->level = MIB2_ICMP;
10021 	optp->name = 0;
10022 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
10023 	    (int)sizeof (ipst->ips_icmp_mib))) {
10024 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
10025 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
10026 	}
10027 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10028 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
10029 	    (int)optp->level, (int)optp->name, (int)optp->len));
10030 	qreply(q, mpctl);
10031 	return (mp2ctl);
10032 }
10033 
10034 /* Global IPv4 IGMP statistics */
10035 static mblk_t *
10036 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10037 {
10038 	struct opthdr		*optp;
10039 	mblk_t			*mp2ctl;
10040 
10041 	/*
10042 	 * make a copy of the original message
10043 	 */
10044 	mp2ctl = copymsg(mpctl);
10045 
10046 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10047 	optp->level = EXPER_IGMP;
10048 	optp->name = 0;
10049 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
10050 	    (int)sizeof (ipst->ips_igmpstat))) {
10051 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
10052 		    (uint_t)sizeof (ipst->ips_igmpstat)));
10053 	}
10054 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10055 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
10056 	    (int)optp->level, (int)optp->name, (int)optp->len));
10057 	qreply(q, mpctl);
10058 	return (mp2ctl);
10059 }
10060 
10061 /* Global IPv4 Multicast Routing statistics */
10062 static mblk_t *
10063 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10064 {
10065 	struct opthdr		*optp;
10066 	mblk_t			*mp2ctl;
10067 
10068 	/*
10069 	 * make a copy of the original message
10070 	 */
10071 	mp2ctl = copymsg(mpctl);
10072 
10073 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10074 	optp->level = EXPER_DVMRP;
10075 	optp->name = 0;
10076 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
10077 		ip0dbg(("ip_mroute_stats: failed\n"));
10078 	}
10079 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10080 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
10081 	    (int)optp->level, (int)optp->name, (int)optp->len));
10082 	qreply(q, mpctl);
10083 	return (mp2ctl);
10084 }
10085 
10086 /* IPv4 address information */
10087 static mblk_t *
10088 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10089 {
10090 	struct opthdr		*optp;
10091 	mblk_t			*mp2ctl;
10092 	mblk_t			*mp_tail = NULL;
10093 	ill_t			*ill;
10094 	ipif_t			*ipif;
10095 	uint_t			bitval;
10096 	mib2_ipAddrEntry_t	mae;
10097 	zoneid_t		zoneid;
10098 	ill_walk_context_t ctx;
10099 
10100 	/*
10101 	 * make a copy of the original message
10102 	 */
10103 	mp2ctl = copymsg(mpctl);
10104 
10105 	/* ipAddrEntryTable */
10106 
10107 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10108 	optp->level = MIB2_IP;
10109 	optp->name = MIB2_IP_ADDR;
10110 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10111 
10112 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10113 	ill = ILL_START_WALK_V4(&ctx, ipst);
10114 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10115 		for (ipif = ill->ill_ipif; ipif != NULL;
10116 		    ipif = ipif->ipif_next) {
10117 			if (ipif->ipif_zoneid != zoneid &&
10118 			    ipif->ipif_zoneid != ALL_ZONES)
10119 				continue;
10120 			/* Sum of count from dead IRE_LO* and our current */
10121 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10122 			if (ipif->ipif_ire_local != NULL) {
10123 				mae.ipAdEntInfo.ae_ibcnt +=
10124 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10125 			}
10126 			mae.ipAdEntInfo.ae_obcnt = 0;
10127 			mae.ipAdEntInfo.ae_focnt = 0;
10128 
10129 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10130 			    OCTET_LENGTH);
10131 			mae.ipAdEntIfIndex.o_length =
10132 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10133 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10134 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10135 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10136 			mae.ipAdEntInfo.ae_subnet_len =
10137 			    ip_mask_to_plen(ipif->ipif_net_mask);
10138 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10139 			for (bitval = 1;
10140 			    bitval &&
10141 			    !(bitval & ipif->ipif_brd_addr);
10142 			    bitval <<= 1)
10143 				noop;
10144 			mae.ipAdEntBcastAddr = bitval;
10145 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10146 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10147 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
10148 			mae.ipAdEntInfo.ae_broadcast_addr =
10149 			    ipif->ipif_brd_addr;
10150 			mae.ipAdEntInfo.ae_pp_dst_addr =
10151 			    ipif->ipif_pp_dst_addr;
10152 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10153 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10154 			mae.ipAdEntRetransmitTime =
10155 			    ill->ill_reachable_retrans_time;
10156 
10157 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10158 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
10159 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10160 				    "allocate %u bytes\n",
10161 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
10162 			}
10163 		}
10164 	}
10165 	rw_exit(&ipst->ips_ill_g_lock);
10166 
10167 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10168 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10169 	    (int)optp->level, (int)optp->name, (int)optp->len));
10170 	qreply(q, mpctl);
10171 	return (mp2ctl);
10172 }
10173 
10174 /* IPv6 address information */
10175 static mblk_t *
10176 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10177 {
10178 	struct opthdr		*optp;
10179 	mblk_t			*mp2ctl;
10180 	mblk_t			*mp_tail = NULL;
10181 	ill_t			*ill;
10182 	ipif_t			*ipif;
10183 	mib2_ipv6AddrEntry_t	mae6;
10184 	zoneid_t		zoneid;
10185 	ill_walk_context_t	ctx;
10186 
10187 	/*
10188 	 * make a copy of the original message
10189 	 */
10190 	mp2ctl = copymsg(mpctl);
10191 
10192 	/* ipv6AddrEntryTable */
10193 
10194 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10195 	optp->level = MIB2_IP6;
10196 	optp->name = MIB2_IP6_ADDR;
10197 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10198 
10199 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10200 	ill = ILL_START_WALK_V6(&ctx, ipst);
10201 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10202 		for (ipif = ill->ill_ipif; ipif != NULL;
10203 		    ipif = ipif->ipif_next) {
10204 			if (ipif->ipif_zoneid != zoneid &&
10205 			    ipif->ipif_zoneid != ALL_ZONES)
10206 				continue;
10207 			/* Sum of count from dead IRE_LO* and our current */
10208 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10209 			if (ipif->ipif_ire_local != NULL) {
10210 				mae6.ipv6AddrInfo.ae_ibcnt +=
10211 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10212 			}
10213 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10214 			mae6.ipv6AddrInfo.ae_focnt = 0;
10215 
10216 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10217 			    OCTET_LENGTH);
10218 			mae6.ipv6AddrIfIndex.o_length =
10219 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10220 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10221 			mae6.ipv6AddrPfxLength =
10222 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10223 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10224 			mae6.ipv6AddrInfo.ae_subnet_len =
10225 			    mae6.ipv6AddrPfxLength;
10226 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10227 
10228 			/* Type: stateless(1), stateful(2), unknown(3) */
10229 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10230 				mae6.ipv6AddrType = 1;
10231 			else
10232 				mae6.ipv6AddrType = 2;
10233 			/* Anycast: true(1), false(2) */
10234 			if (ipif->ipif_flags & IPIF_ANYCAST)
10235 				mae6.ipv6AddrAnycastFlag = 1;
10236 			else
10237 				mae6.ipv6AddrAnycastFlag = 2;
10238 
10239 			/*
10240 			 * Address status: preferred(1), deprecated(2),
10241 			 * invalid(3), inaccessible(4), unknown(5)
10242 			 */
10243 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10244 				mae6.ipv6AddrStatus = 3;
10245 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10246 				mae6.ipv6AddrStatus = 2;
10247 			else
10248 				mae6.ipv6AddrStatus = 1;
10249 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10250 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
10251 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10252 			    ipif->ipif_v6pp_dst_addr;
10253 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10254 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10255 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10256 			mae6.ipv6AddrIdentifier = ill->ill_token;
10257 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10258 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10259 			mae6.ipv6AddrRetransmitTime =
10260 			    ill->ill_reachable_retrans_time;
10261 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10262 			    (char *)&mae6,
10263 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
10264 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10265 				    "allocate %u bytes\n",
10266 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
10267 			}
10268 		}
10269 	}
10270 	rw_exit(&ipst->ips_ill_g_lock);
10271 
10272 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10273 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10274 	    (int)optp->level, (int)optp->name, (int)optp->len));
10275 	qreply(q, mpctl);
10276 	return (mp2ctl);
10277 }
10278 
10279 /* IPv4 multicast group membership. */
10280 static mblk_t *
10281 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10282 {
10283 	struct opthdr		*optp;
10284 	mblk_t			*mp2ctl;
10285 	ill_t			*ill;
10286 	ipif_t			*ipif;
10287 	ilm_t			*ilm;
10288 	ip_member_t		ipm;
10289 	mblk_t			*mp_tail = NULL;
10290 	ill_walk_context_t	ctx;
10291 	zoneid_t		zoneid;
10292 
10293 	/*
10294 	 * make a copy of the original message
10295 	 */
10296 	mp2ctl = copymsg(mpctl);
10297 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10298 
10299 	/* ipGroupMember table */
10300 	optp = (struct opthdr *)&mpctl->b_rptr[
10301 	    sizeof (struct T_optmgmt_ack)];
10302 	optp->level = MIB2_IP;
10303 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10304 
10305 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10306 	ill = ILL_START_WALK_V4(&ctx, ipst);
10307 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10308 		/* Make sure the ill isn't going away. */
10309 		if (!ill_check_and_refhold(ill))
10310 			continue;
10311 		rw_exit(&ipst->ips_ill_g_lock);
10312 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10313 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10314 			if (ilm->ilm_zoneid != zoneid &&
10315 			    ilm->ilm_zoneid != ALL_ZONES)
10316 				continue;
10317 
10318 			/* Is there an ipif for ilm_ifaddr? */
10319 			for (ipif = ill->ill_ipif; ipif != NULL;
10320 			    ipif = ipif->ipif_next) {
10321 				if (!IPIF_IS_CONDEMNED(ipif) &&
10322 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10323 				    ilm->ilm_ifaddr != INADDR_ANY)
10324 					break;
10325 			}
10326 			if (ipif != NULL) {
10327 				ipif_get_name(ipif,
10328 				    ipm.ipGroupMemberIfIndex.o_bytes,
10329 				    OCTET_LENGTH);
10330 			} else {
10331 				ill_get_name(ill,
10332 				    ipm.ipGroupMemberIfIndex.o_bytes,
10333 				    OCTET_LENGTH);
10334 			}
10335 			ipm.ipGroupMemberIfIndex.o_length =
10336 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10337 
10338 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10339 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10340 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10341 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10342 			    (char *)&ipm, (int)sizeof (ipm))) {
10343 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10344 				    "failed to allocate %u bytes\n",
10345 				    (uint_t)sizeof (ipm)));
10346 			}
10347 		}
10348 		rw_exit(&ill->ill_mcast_lock);
10349 		ill_refrele(ill);
10350 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10351 	}
10352 	rw_exit(&ipst->ips_ill_g_lock);
10353 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10354 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10355 	    (int)optp->level, (int)optp->name, (int)optp->len));
10356 	qreply(q, mpctl);
10357 	return (mp2ctl);
10358 }
10359 
10360 /* IPv6 multicast group membership. */
10361 static mblk_t *
10362 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10363 {
10364 	struct opthdr		*optp;
10365 	mblk_t			*mp2ctl;
10366 	ill_t			*ill;
10367 	ilm_t			*ilm;
10368 	ipv6_member_t		ipm6;
10369 	mblk_t			*mp_tail = NULL;
10370 	ill_walk_context_t	ctx;
10371 	zoneid_t		zoneid;
10372 
10373 	/*
10374 	 * make a copy of the original message
10375 	 */
10376 	mp2ctl = copymsg(mpctl);
10377 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10378 
10379 	/* ip6GroupMember table */
10380 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10381 	optp->level = MIB2_IP6;
10382 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10383 
10384 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10385 	ill = ILL_START_WALK_V6(&ctx, ipst);
10386 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10387 		/* Make sure the ill isn't going away. */
10388 		if (!ill_check_and_refhold(ill))
10389 			continue;
10390 		rw_exit(&ipst->ips_ill_g_lock);
10391 		/*
10392 		 * Normally we don't have any members on under IPMP interfaces.
10393 		 * We report them as a debugging aid.
10394 		 */
10395 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10396 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10397 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10398 			if (ilm->ilm_zoneid != zoneid &&
10399 			    ilm->ilm_zoneid != ALL_ZONES)
10400 				continue;	/* not this zone */
10401 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10402 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10403 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10404 			if (!snmp_append_data2(mpctl->b_cont,
10405 			    &mp_tail,
10406 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10407 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10408 				    "failed to allocate %u bytes\n",
10409 				    (uint_t)sizeof (ipm6)));
10410 			}
10411 		}
10412 		rw_exit(&ill->ill_mcast_lock);
10413 		ill_refrele(ill);
10414 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10415 	}
10416 	rw_exit(&ipst->ips_ill_g_lock);
10417 
10418 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10419 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10420 	    (int)optp->level, (int)optp->name, (int)optp->len));
10421 	qreply(q, mpctl);
10422 	return (mp2ctl);
10423 }
10424 
10425 /* IP multicast filtered sources */
10426 static mblk_t *
10427 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10428 {
10429 	struct opthdr		*optp;
10430 	mblk_t			*mp2ctl;
10431 	ill_t			*ill;
10432 	ipif_t			*ipif;
10433 	ilm_t			*ilm;
10434 	ip_grpsrc_t		ips;
10435 	mblk_t			*mp_tail = NULL;
10436 	ill_walk_context_t	ctx;
10437 	zoneid_t		zoneid;
10438 	int			i;
10439 	slist_t			*sl;
10440 
10441 	/*
10442 	 * make a copy of the original message
10443 	 */
10444 	mp2ctl = copymsg(mpctl);
10445 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10446 
10447 	/* ipGroupSource table */
10448 	optp = (struct opthdr *)&mpctl->b_rptr[
10449 	    sizeof (struct T_optmgmt_ack)];
10450 	optp->level = MIB2_IP;
10451 	optp->name = EXPER_IP_GROUP_SOURCES;
10452 
10453 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10454 	ill = ILL_START_WALK_V4(&ctx, ipst);
10455 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10456 		/* Make sure the ill isn't going away. */
10457 		if (!ill_check_and_refhold(ill))
10458 			continue;
10459 		rw_exit(&ipst->ips_ill_g_lock);
10460 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10461 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10462 			sl = ilm->ilm_filter;
10463 			if (ilm->ilm_zoneid != zoneid &&
10464 			    ilm->ilm_zoneid != ALL_ZONES)
10465 				continue;
10466 			if (SLIST_IS_EMPTY(sl))
10467 				continue;
10468 
10469 			/* Is there an ipif for ilm_ifaddr? */
10470 			for (ipif = ill->ill_ipif; ipif != NULL;
10471 			    ipif = ipif->ipif_next) {
10472 				if (!IPIF_IS_CONDEMNED(ipif) &&
10473 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10474 				    ilm->ilm_ifaddr != INADDR_ANY)
10475 					break;
10476 			}
10477 			if (ipif != NULL) {
10478 				ipif_get_name(ipif,
10479 				    ips.ipGroupSourceIfIndex.o_bytes,
10480 				    OCTET_LENGTH);
10481 			} else {
10482 				ill_get_name(ill,
10483 				    ips.ipGroupSourceIfIndex.o_bytes,
10484 				    OCTET_LENGTH);
10485 			}
10486 			ips.ipGroupSourceIfIndex.o_length =
10487 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10488 
10489 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10490 			for (i = 0; i < sl->sl_numsrc; i++) {
10491 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10492 					continue;
10493 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10494 				    ips.ipGroupSourceAddress);
10495 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10496 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10497 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10498 					    " failed to allocate %u bytes\n",
10499 					    (uint_t)sizeof (ips)));
10500 				}
10501 			}
10502 		}
10503 		rw_exit(&ill->ill_mcast_lock);
10504 		ill_refrele(ill);
10505 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10506 	}
10507 	rw_exit(&ipst->ips_ill_g_lock);
10508 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10509 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10510 	    (int)optp->level, (int)optp->name, (int)optp->len));
10511 	qreply(q, mpctl);
10512 	return (mp2ctl);
10513 }
10514 
10515 /* IPv6 multicast filtered sources. */
10516 static mblk_t *
10517 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10518 {
10519 	struct opthdr		*optp;
10520 	mblk_t			*mp2ctl;
10521 	ill_t			*ill;
10522 	ilm_t			*ilm;
10523 	ipv6_grpsrc_t		ips6;
10524 	mblk_t			*mp_tail = NULL;
10525 	ill_walk_context_t	ctx;
10526 	zoneid_t		zoneid;
10527 	int			i;
10528 	slist_t			*sl;
10529 
10530 	/*
10531 	 * make a copy of the original message
10532 	 */
10533 	mp2ctl = copymsg(mpctl);
10534 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10535 
10536 	/* ip6GroupMember table */
10537 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10538 	optp->level = MIB2_IP6;
10539 	optp->name = EXPER_IP6_GROUP_SOURCES;
10540 
10541 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10542 	ill = ILL_START_WALK_V6(&ctx, ipst);
10543 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10544 		/* Make sure the ill isn't going away. */
10545 		if (!ill_check_and_refhold(ill))
10546 			continue;
10547 		rw_exit(&ipst->ips_ill_g_lock);
10548 		/*
10549 		 * Normally we don't have any members on under IPMP interfaces.
10550 		 * We report them as a debugging aid.
10551 		 */
10552 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10553 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10554 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10555 			sl = ilm->ilm_filter;
10556 			if (ilm->ilm_zoneid != zoneid &&
10557 			    ilm->ilm_zoneid != ALL_ZONES)
10558 				continue;
10559 			if (SLIST_IS_EMPTY(sl))
10560 				continue;
10561 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10562 			for (i = 0; i < sl->sl_numsrc; i++) {
10563 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10564 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10565 				    (char *)&ips6, (int)sizeof (ips6))) {
10566 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10567 					    "group_src: failed to allocate "
10568 					    "%u bytes\n",
10569 					    (uint_t)sizeof (ips6)));
10570 				}
10571 			}
10572 		}
10573 		rw_exit(&ill->ill_mcast_lock);
10574 		ill_refrele(ill);
10575 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10576 	}
10577 	rw_exit(&ipst->ips_ill_g_lock);
10578 
10579 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10580 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10581 	    (int)optp->level, (int)optp->name, (int)optp->len));
10582 	qreply(q, mpctl);
10583 	return (mp2ctl);
10584 }
10585 
10586 /* Multicast routing virtual interface table. */
10587 static mblk_t *
10588 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10589 {
10590 	struct opthdr		*optp;
10591 	mblk_t			*mp2ctl;
10592 
10593 	/*
10594 	 * make a copy of the original message
10595 	 */
10596 	mp2ctl = copymsg(mpctl);
10597 
10598 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10599 	optp->level = EXPER_DVMRP;
10600 	optp->name = EXPER_DVMRP_VIF;
10601 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10602 		ip0dbg(("ip_mroute_vif: failed\n"));
10603 	}
10604 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10605 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10606 	    (int)optp->level, (int)optp->name, (int)optp->len));
10607 	qreply(q, mpctl);
10608 	return (mp2ctl);
10609 }
10610 
10611 /* Multicast routing table. */
10612 static mblk_t *
10613 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10614 {
10615 	struct opthdr		*optp;
10616 	mblk_t			*mp2ctl;
10617 
10618 	/*
10619 	 * make a copy of the original message
10620 	 */
10621 	mp2ctl = copymsg(mpctl);
10622 
10623 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10624 	optp->level = EXPER_DVMRP;
10625 	optp->name = EXPER_DVMRP_MRT;
10626 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10627 		ip0dbg(("ip_mroute_mrt: failed\n"));
10628 	}
10629 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10630 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10631 	    (int)optp->level, (int)optp->name, (int)optp->len));
10632 	qreply(q, mpctl);
10633 	return (mp2ctl);
10634 }
10635 
10636 /*
10637  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10638  * in one IRE walk.
10639  */
10640 static mblk_t *
10641 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10642     ip_stack_t *ipst)
10643 {
10644 	struct opthdr	*optp;
10645 	mblk_t		*mp2ctl;	/* Returned */
10646 	mblk_t		*mp3ctl;	/* nettomedia */
10647 	mblk_t		*mp4ctl;	/* routeattrs */
10648 	iproutedata_t	ird;
10649 	zoneid_t	zoneid;
10650 
10651 	/*
10652 	 * make copies of the original message
10653 	 *	- mp2ctl is returned unchanged to the caller for his use
10654 	 *	- mpctl is sent upstream as ipRouteEntryTable
10655 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10656 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10657 	 */
10658 	mp2ctl = copymsg(mpctl);
10659 	mp3ctl = copymsg(mpctl);
10660 	mp4ctl = copymsg(mpctl);
10661 	if (mp3ctl == NULL || mp4ctl == NULL) {
10662 		freemsg(mp4ctl);
10663 		freemsg(mp3ctl);
10664 		freemsg(mp2ctl);
10665 		freemsg(mpctl);
10666 		return (NULL);
10667 	}
10668 
10669 	bzero(&ird, sizeof (ird));
10670 
10671 	ird.ird_route.lp_head = mpctl->b_cont;
10672 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10673 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10674 	/*
10675 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10676 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10677 	 * intended a temporary solution until a proper MIB API is provided
10678 	 * that provides complete filtering/caller-opt-in.
10679 	 */
10680 	if (level == EXPER_IP_AND_ALL_IRES)
10681 		ird.ird_flags |= IRD_REPORT_ALL;
10682 
10683 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10684 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10685 
10686 	/* ipRouteEntryTable in mpctl */
10687 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10688 	optp->level = MIB2_IP;
10689 	optp->name = MIB2_IP_ROUTE;
10690 	optp->len = msgdsize(ird.ird_route.lp_head);
10691 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10692 	    (int)optp->level, (int)optp->name, (int)optp->len));
10693 	qreply(q, mpctl);
10694 
10695 	/* ipNetToMediaEntryTable in mp3ctl */
10696 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10697 
10698 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10699 	optp->level = MIB2_IP;
10700 	optp->name = MIB2_IP_MEDIA;
10701 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10702 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10703 	    (int)optp->level, (int)optp->name, (int)optp->len));
10704 	qreply(q, mp3ctl);
10705 
10706 	/* ipRouteAttributeTable in mp4ctl */
10707 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10708 	optp->level = MIB2_IP;
10709 	optp->name = EXPER_IP_RTATTR;
10710 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10711 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10712 	    (int)optp->level, (int)optp->name, (int)optp->len));
10713 	if (optp->len == 0)
10714 		freemsg(mp4ctl);
10715 	else
10716 		qreply(q, mp4ctl);
10717 
10718 	return (mp2ctl);
10719 }
10720 
10721 /*
10722  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10723  * ipv6NetToMediaEntryTable in an NDP walk.
10724  */
10725 static mblk_t *
10726 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10727     ip_stack_t *ipst)
10728 {
10729 	struct opthdr	*optp;
10730 	mblk_t		*mp2ctl;	/* Returned */
10731 	mblk_t		*mp3ctl;	/* nettomedia */
10732 	mblk_t		*mp4ctl;	/* routeattrs */
10733 	iproutedata_t	ird;
10734 	zoneid_t	zoneid;
10735 
10736 	/*
10737 	 * make copies of the original message
10738 	 *	- mp2ctl is returned unchanged to the caller for his use
10739 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10740 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10741 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10742 	 */
10743 	mp2ctl = copymsg(mpctl);
10744 	mp3ctl = copymsg(mpctl);
10745 	mp4ctl = copymsg(mpctl);
10746 	if (mp3ctl == NULL || mp4ctl == NULL) {
10747 		freemsg(mp4ctl);
10748 		freemsg(mp3ctl);
10749 		freemsg(mp2ctl);
10750 		freemsg(mpctl);
10751 		return (NULL);
10752 	}
10753 
10754 	bzero(&ird, sizeof (ird));
10755 
10756 	ird.ird_route.lp_head = mpctl->b_cont;
10757 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10758 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10759 	/*
10760 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10761 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10762 	 * intended a temporary solution until a proper MIB API is provided
10763 	 * that provides complete filtering/caller-opt-in.
10764 	 */
10765 	if (level == EXPER_IP_AND_ALL_IRES)
10766 		ird.ird_flags |= IRD_REPORT_ALL;
10767 
10768 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10769 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10770 
10771 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10772 	optp->level = MIB2_IP6;
10773 	optp->name = MIB2_IP6_ROUTE;
10774 	optp->len = msgdsize(ird.ird_route.lp_head);
10775 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10776 	    (int)optp->level, (int)optp->name, (int)optp->len));
10777 	qreply(q, mpctl);
10778 
10779 	/* ipv6NetToMediaEntryTable in mp3ctl */
10780 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10781 
10782 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10783 	optp->level = MIB2_IP6;
10784 	optp->name = MIB2_IP6_MEDIA;
10785 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10786 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10787 	    (int)optp->level, (int)optp->name, (int)optp->len));
10788 	qreply(q, mp3ctl);
10789 
10790 	/* ipv6RouteAttributeTable in mp4ctl */
10791 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10792 	optp->level = MIB2_IP6;
10793 	optp->name = EXPER_IP_RTATTR;
10794 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10795 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10796 	    (int)optp->level, (int)optp->name, (int)optp->len));
10797 	if (optp->len == 0)
10798 		freemsg(mp4ctl);
10799 	else
10800 		qreply(q, mp4ctl);
10801 
10802 	return (mp2ctl);
10803 }
10804 
10805 /*
10806  * IPv6 mib: One per ill
10807  */
10808 static mblk_t *
10809 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10810 {
10811 	struct opthdr		*optp;
10812 	mblk_t			*mp2ctl;
10813 	ill_t			*ill;
10814 	ill_walk_context_t	ctx;
10815 	mblk_t			*mp_tail = NULL;
10816 
10817 	/*
10818 	 * Make a copy of the original message
10819 	 */
10820 	mp2ctl = copymsg(mpctl);
10821 
10822 	/* fixed length IPv6 structure ... */
10823 
10824 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10825 	optp->level = MIB2_IP6;
10826 	optp->name = 0;
10827 	/* Include "unknown interface" ip6_mib */
10828 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10829 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10830 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10831 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10832 	    ipst->ips_ipv6_forward ? 1 : 2);
10833 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10834 	    ipst->ips_ipv6_def_hops);
10835 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10836 	    sizeof (mib2_ipIfStatsEntry_t));
10837 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10838 	    sizeof (mib2_ipv6AddrEntry_t));
10839 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10840 	    sizeof (mib2_ipv6RouteEntry_t));
10841 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10842 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10843 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10844 	    sizeof (ipv6_member_t));
10845 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10846 	    sizeof (ipv6_grpsrc_t));
10847 
10848 	/*
10849 	 * Synchronize 64- and 32-bit counters
10850 	 */
10851 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10852 	    ipIfStatsHCInReceives);
10853 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10854 	    ipIfStatsHCInDelivers);
10855 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10856 	    ipIfStatsHCOutRequests);
10857 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10858 	    ipIfStatsHCOutForwDatagrams);
10859 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10860 	    ipIfStatsHCOutMcastPkts);
10861 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10862 	    ipIfStatsHCInMcastPkts);
10863 
10864 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10865 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
10866 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10867 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
10868 	}
10869 
10870 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10871 	ill = ILL_START_WALK_V6(&ctx, ipst);
10872 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10873 		ill->ill_ip_mib->ipIfStatsIfIndex =
10874 		    ill->ill_phyint->phyint_ifindex;
10875 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10876 		    ipst->ips_ipv6_forward ? 1 : 2);
10877 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10878 		    ill->ill_max_hops);
10879 
10880 		/*
10881 		 * Synchronize 64- and 32-bit counters
10882 		 */
10883 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10884 		    ipIfStatsHCInReceives);
10885 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10886 		    ipIfStatsHCInDelivers);
10887 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10888 		    ipIfStatsHCOutRequests);
10889 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10890 		    ipIfStatsHCOutForwDatagrams);
10891 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10892 		    ipIfStatsHCOutMcastPkts);
10893 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10894 		    ipIfStatsHCInMcastPkts);
10895 
10896 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10897 		    (char *)ill->ill_ip_mib,
10898 		    (int)sizeof (*ill->ill_ip_mib))) {
10899 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10900 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
10901 		}
10902 	}
10903 	rw_exit(&ipst->ips_ill_g_lock);
10904 
10905 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10906 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10907 	    (int)optp->level, (int)optp->name, (int)optp->len));
10908 	qreply(q, mpctl);
10909 	return (mp2ctl);
10910 }
10911 
10912 /*
10913  * ICMPv6 mib: One per ill
10914  */
10915 static mblk_t *
10916 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10917 {
10918 	struct opthdr		*optp;
10919 	mblk_t			*mp2ctl;
10920 	ill_t			*ill;
10921 	ill_walk_context_t	ctx;
10922 	mblk_t			*mp_tail = NULL;
10923 	/*
10924 	 * Make a copy of the original message
10925 	 */
10926 	mp2ctl = copymsg(mpctl);
10927 
10928 	/* fixed length ICMPv6 structure ... */
10929 
10930 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10931 	optp->level = MIB2_ICMP6;
10932 	optp->name = 0;
10933 	/* Include "unknown interface" icmp6_mib */
10934 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10935 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10936 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10937 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10938 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10939 	    (char *)&ipst->ips_icmp6_mib,
10940 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10941 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10942 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10943 	}
10944 
10945 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10946 	ill = ILL_START_WALK_V6(&ctx, ipst);
10947 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10948 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10949 		    ill->ill_phyint->phyint_ifindex;
10950 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10951 		    (char *)ill->ill_icmp6_mib,
10952 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10953 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10954 			    "%u bytes\n",
10955 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10956 		}
10957 	}
10958 	rw_exit(&ipst->ips_ill_g_lock);
10959 
10960 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10961 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10962 	    (int)optp->level, (int)optp->name, (int)optp->len));
10963 	qreply(q, mpctl);
10964 	return (mp2ctl);
10965 }
10966 
10967 /*
10968  * ire_walk routine to create both ipRouteEntryTable and
10969  * ipRouteAttributeTable in one IRE walk
10970  */
10971 static void
10972 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10973 {
10974 	ill_t				*ill;
10975 	mib2_ipRouteEntry_t		*re;
10976 	mib2_ipAttributeEntry_t		iaes;
10977 	tsol_ire_gw_secattr_t		*attrp;
10978 	tsol_gc_t			*gc = NULL;
10979 	tsol_gcgrp_t			*gcgrp = NULL;
10980 	ip_stack_t			*ipst = ire->ire_ipst;
10981 
10982 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10983 
10984 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10985 		if (ire->ire_testhidden)
10986 			return;
10987 		if (ire->ire_type & IRE_IF_CLONE)
10988 			return;
10989 	}
10990 
10991 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10992 		return;
10993 
10994 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10995 		mutex_enter(&attrp->igsa_lock);
10996 		if ((gc = attrp->igsa_gc) != NULL) {
10997 			gcgrp = gc->gc_grp;
10998 			ASSERT(gcgrp != NULL);
10999 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11000 		}
11001 		mutex_exit(&attrp->igsa_lock);
11002 	}
11003 	/*
11004 	 * Return all IRE types for route table... let caller pick and choose
11005 	 */
11006 	re->ipRouteDest = ire->ire_addr;
11007 	ill = ire->ire_ill;
11008 	re->ipRouteIfIndex.o_length = 0;
11009 	if (ill != NULL) {
11010 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
11011 		re->ipRouteIfIndex.o_length =
11012 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
11013 	}
11014 	re->ipRouteMetric1 = -1;
11015 	re->ipRouteMetric2 = -1;
11016 	re->ipRouteMetric3 = -1;
11017 	re->ipRouteMetric4 = -1;
11018 
11019 	re->ipRouteNextHop = ire->ire_gateway_addr;
11020 	/* indirect(4), direct(3), or invalid(2) */
11021 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11022 		re->ipRouteType = 2;
11023 	else if (ire->ire_type & IRE_ONLINK)
11024 		re->ipRouteType = 3;
11025 	else
11026 		re->ipRouteType = 4;
11027 
11028 	re->ipRouteProto = -1;
11029 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
11030 	re->ipRouteMask = ire->ire_mask;
11031 	re->ipRouteMetric5 = -1;
11032 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11033 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
11034 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11035 
11036 	re->ipRouteInfo.re_frag_flag	= 0;
11037 	re->ipRouteInfo.re_rtt		= 0;
11038 	re->ipRouteInfo.re_src_addr	= 0;
11039 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
11040 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11041 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11042 	re->ipRouteInfo.re_flags	= ire->ire_flags;
11043 
11044 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11045 	if (ire->ire_type & IRE_INTERFACE) {
11046 		ire_t *child;
11047 
11048 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11049 		child = ire->ire_dep_children;
11050 		while (child != NULL) {
11051 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
11052 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11053 			child = child->ire_dep_sib_next;
11054 		}
11055 		rw_exit(&ipst->ips_ire_dep_lock);
11056 	}
11057 
11058 	if (ire->ire_flags & RTF_DYNAMIC) {
11059 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11060 	} else {
11061 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
11062 	}
11063 
11064 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11065 	    (char *)re, (int)sizeof (*re))) {
11066 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11067 		    (uint_t)sizeof (*re)));
11068 	}
11069 
11070 	if (gc != NULL) {
11071 		iaes.iae_routeidx = ird->ird_idx;
11072 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11073 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11074 
11075 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11076 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11077 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11078 			    "bytes\n", (uint_t)sizeof (iaes)));
11079 		}
11080 	}
11081 
11082 	/* bump route index for next pass */
11083 	ird->ird_idx++;
11084 
11085 	kmem_free(re, sizeof (*re));
11086 	if (gcgrp != NULL)
11087 		rw_exit(&gcgrp->gcgrp_rwlock);
11088 }
11089 
11090 /*
11091  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11092  */
11093 static void
11094 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11095 {
11096 	ill_t				*ill;
11097 	mib2_ipv6RouteEntry_t		*re;
11098 	mib2_ipAttributeEntry_t		iaes;
11099 	tsol_ire_gw_secattr_t		*attrp;
11100 	tsol_gc_t			*gc = NULL;
11101 	tsol_gcgrp_t			*gcgrp = NULL;
11102 	ip_stack_t			*ipst = ire->ire_ipst;
11103 
11104 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11105 
11106 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11107 		if (ire->ire_testhidden)
11108 			return;
11109 		if (ire->ire_type & IRE_IF_CLONE)
11110 			return;
11111 	}
11112 
11113 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11114 		return;
11115 
11116 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11117 		mutex_enter(&attrp->igsa_lock);
11118 		if ((gc = attrp->igsa_gc) != NULL) {
11119 			gcgrp = gc->gc_grp;
11120 			ASSERT(gcgrp != NULL);
11121 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11122 		}
11123 		mutex_exit(&attrp->igsa_lock);
11124 	}
11125 	/*
11126 	 * Return all IRE types for route table... let caller pick and choose
11127 	 */
11128 	re->ipv6RouteDest = ire->ire_addr_v6;
11129 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11130 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11131 	re->ipv6RouteIfIndex.o_length = 0;
11132 	ill = ire->ire_ill;
11133 	if (ill != NULL) {
11134 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11135 		re->ipv6RouteIfIndex.o_length =
11136 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11137 	}
11138 
11139 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11140 
11141 	mutex_enter(&ire->ire_lock);
11142 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11143 	mutex_exit(&ire->ire_lock);
11144 
11145 	/* remote(4), local(3), or discard(2) */
11146 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11147 		re->ipv6RouteType = 2;
11148 	else if (ire->ire_type & IRE_ONLINK)
11149 		re->ipv6RouteType = 3;
11150 	else
11151 		re->ipv6RouteType = 4;
11152 
11153 	re->ipv6RouteProtocol	= -1;
11154 	re->ipv6RoutePolicy	= 0;
11155 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11156 	re->ipv6RouteNextHopRDI	= 0;
11157 	re->ipv6RouteWeight	= 0;
11158 	re->ipv6RouteMetric	= 0;
11159 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11160 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11161 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11162 
11163 	re->ipv6RouteInfo.re_frag_flag	= 0;
11164 	re->ipv6RouteInfo.re_rtt	= 0;
11165 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11166 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11167 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11168 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11169 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11170 
11171 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11172 	if (ire->ire_type & IRE_INTERFACE) {
11173 		ire_t *child;
11174 
11175 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11176 		child = ire->ire_dep_children;
11177 		while (child != NULL) {
11178 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11179 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11180 			child = child->ire_dep_sib_next;
11181 		}
11182 		rw_exit(&ipst->ips_ire_dep_lock);
11183 	}
11184 	if (ire->ire_flags & RTF_DYNAMIC) {
11185 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11186 	} else {
11187 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11188 	}
11189 
11190 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11191 	    (char *)re, (int)sizeof (*re))) {
11192 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11193 		    (uint_t)sizeof (*re)));
11194 	}
11195 
11196 	if (gc != NULL) {
11197 		iaes.iae_routeidx = ird->ird_idx;
11198 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11199 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11200 
11201 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11202 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11203 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11204 			    "bytes\n", (uint_t)sizeof (iaes)));
11205 		}
11206 	}
11207 
11208 	/* bump route index for next pass */
11209 	ird->ird_idx++;
11210 
11211 	kmem_free(re, sizeof (*re));
11212 	if (gcgrp != NULL)
11213 		rw_exit(&gcgrp->gcgrp_rwlock);
11214 }
11215 
11216 /*
11217  * ncec_walk routine to create ipv6NetToMediaEntryTable
11218  */
11219 static int
11220 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11221 {
11222 	ill_t				*ill;
11223 	mib2_ipv6NetToMediaEntry_t	ntme;
11224 
11225 	ill = ncec->ncec_ill;
11226 	/* skip arpce entries, and loopback ncec entries */
11227 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11228 		return (0);
11229 	/*
11230 	 * Neighbor cache entry attached to IRE with on-link
11231 	 * destination.
11232 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11233 	 */
11234 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11235 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11236 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11237 	if (ncec->ncec_lladdr != NULL) {
11238 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11239 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11240 	}
11241 	/*
11242 	 * Note: Returns ND_* states. Should be:
11243 	 * reachable(1), stale(2), delay(3), probe(4),
11244 	 * invalid(5), unknown(6)
11245 	 */
11246 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11247 	ntme.ipv6NetToMediaLastUpdated = 0;
11248 
11249 	/* other(1), dynamic(2), static(3), local(4) */
11250 	if (NCE_MYADDR(ncec)) {
11251 		ntme.ipv6NetToMediaType = 4;
11252 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11253 		ntme.ipv6NetToMediaType = 1; /* proxy */
11254 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11255 		ntme.ipv6NetToMediaType = 3;
11256 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11257 		ntme.ipv6NetToMediaType = 1;
11258 	} else {
11259 		ntme.ipv6NetToMediaType = 2;
11260 	}
11261 
11262 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11263 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11264 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11265 		    (uint_t)sizeof (ntme)));
11266 	}
11267 	return (0);
11268 }
11269 
11270 int
11271 nce2ace(ncec_t *ncec)
11272 {
11273 	int flags = 0;
11274 
11275 	if (NCE_ISREACHABLE(ncec))
11276 		flags |= ACE_F_RESOLVED;
11277 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11278 		flags |= ACE_F_AUTHORITY;
11279 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11280 		flags |= ACE_F_PUBLISH;
11281 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11282 		flags |= ACE_F_PERMANENT;
11283 	if (NCE_MYADDR(ncec))
11284 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11285 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11286 		flags |= ACE_F_UNVERIFIED;
11287 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11288 		flags |= ACE_F_AUTHORITY;
11289 	if (ncec->ncec_flags & NCE_F_DELAYED)
11290 		flags |= ACE_F_DELAYED;
11291 	return (flags);
11292 }
11293 
11294 /*
11295  * ncec_walk routine to create ipNetToMediaEntryTable
11296  */
11297 static int
11298 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11299 {
11300 	ill_t				*ill;
11301 	mib2_ipNetToMediaEntry_t	ntme;
11302 	const char			*name = "unknown";
11303 	ipaddr_t			ncec_addr;
11304 
11305 	ill = ncec->ncec_ill;
11306 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11307 	    ill->ill_net_type == IRE_LOOPBACK)
11308 		return (0);
11309 
11310 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11311 	name = ill->ill_name;
11312 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11313 	if (NCE_MYADDR(ncec)) {
11314 		ntme.ipNetToMediaType = 4;
11315 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11316 		ntme.ipNetToMediaType = 1;
11317 	} else {
11318 		ntme.ipNetToMediaType = 3;
11319 	}
11320 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11321 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11322 	    ntme.ipNetToMediaIfIndex.o_length);
11323 
11324 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11325 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11326 
11327 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11328 	ncec_addr = INADDR_BROADCAST;
11329 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11330 	    sizeof (ncec_addr));
11331 	/*
11332 	 * map all the flags to the ACE counterpart.
11333 	 */
11334 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11335 
11336 	ntme.ipNetToMediaPhysAddress.o_length =
11337 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11338 
11339 	if (!NCE_ISREACHABLE(ncec))
11340 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11341 	else {
11342 		if (ncec->ncec_lladdr != NULL) {
11343 			bcopy(ncec->ncec_lladdr,
11344 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11345 			    ntme.ipNetToMediaPhysAddress.o_length);
11346 		}
11347 	}
11348 
11349 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11350 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11351 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11352 		    (uint_t)sizeof (ntme)));
11353 	}
11354 	return (0);
11355 }
11356 
11357 /*
11358  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11359  */
11360 /* ARGSUSED */
11361 int
11362 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11363 {
11364 	switch (level) {
11365 	case MIB2_IP:
11366 	case MIB2_ICMP:
11367 		switch (name) {
11368 		default:
11369 			break;
11370 		}
11371 		return (1);
11372 	default:
11373 		return (1);
11374 	}
11375 }
11376 
11377 /*
11378  * When there exists both a 64- and 32-bit counter of a particular type
11379  * (i.e., InReceives), only the 64-bit counters are added.
11380  */
11381 void
11382 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11383 {
11384 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11385 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11386 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11387 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11388 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11389 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11390 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11391 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11392 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11393 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11394 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11395 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11396 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11397 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11398 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11399 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11400 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11401 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11402 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11403 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11404 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11405 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11406 	    o2->ipIfStatsInWrongIPVersion);
11407 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11408 	    o2->ipIfStatsInWrongIPVersion);
11409 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11410 	    o2->ipIfStatsOutSwitchIPVersion);
11411 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11412 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11413 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11414 	    o2->ipIfStatsHCInForwDatagrams);
11415 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11416 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11417 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11418 	    o2->ipIfStatsHCOutForwDatagrams);
11419 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11420 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11421 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11422 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11423 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11424 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11425 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11426 	    o2->ipIfStatsHCOutMcastOctets);
11427 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11428 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11429 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11430 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11431 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11432 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11433 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11434 }
11435 
11436 void
11437 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11438 {
11439 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11440 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11441 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11442 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11443 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11444 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11445 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11446 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11447 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11448 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11449 	    o2->ipv6IfIcmpInRouterSolicits);
11450 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11451 	    o2->ipv6IfIcmpInRouterAdvertisements);
11452 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11453 	    o2->ipv6IfIcmpInNeighborSolicits);
11454 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11455 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11456 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11457 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11458 	    o2->ipv6IfIcmpInGroupMembQueries);
11459 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11460 	    o2->ipv6IfIcmpInGroupMembResponses);
11461 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11462 	    o2->ipv6IfIcmpInGroupMembReductions);
11463 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11464 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11465 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11466 	    o2->ipv6IfIcmpOutDestUnreachs);
11467 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11468 	    o2->ipv6IfIcmpOutAdminProhibs);
11469 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11470 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11471 	    o2->ipv6IfIcmpOutParmProblems);
11472 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11473 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11474 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11475 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11476 	    o2->ipv6IfIcmpOutRouterSolicits);
11477 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11478 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11479 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11480 	    o2->ipv6IfIcmpOutNeighborSolicits);
11481 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11482 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11483 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11484 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11485 	    o2->ipv6IfIcmpOutGroupMembQueries);
11486 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11487 	    o2->ipv6IfIcmpOutGroupMembResponses);
11488 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11489 	    o2->ipv6IfIcmpOutGroupMembReductions);
11490 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11491 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11492 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11493 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11494 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11495 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11496 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11497 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11498 	    o2->ipv6IfIcmpInGroupMembTotal);
11499 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11500 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11501 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11502 	    o2->ipv6IfIcmpInGroupMembBadReports);
11503 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11504 	    o2->ipv6IfIcmpInGroupMembOurReports);
11505 }
11506 
11507 /*
11508  * Called before the options are updated to check if this packet will
11509  * be source routed from here.
11510  * This routine assumes that the options are well formed i.e. that they
11511  * have already been checked.
11512  */
11513 boolean_t
11514 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11515 {
11516 	ipoptp_t	opts;
11517 	uchar_t		*opt;
11518 	uint8_t		optval;
11519 	uint8_t		optlen;
11520 	ipaddr_t	dst;
11521 
11522 	if (IS_SIMPLE_IPH(ipha)) {
11523 		ip2dbg(("not source routed\n"));
11524 		return (B_FALSE);
11525 	}
11526 	dst = ipha->ipha_dst;
11527 	for (optval = ipoptp_first(&opts, ipha);
11528 	    optval != IPOPT_EOL;
11529 	    optval = ipoptp_next(&opts)) {
11530 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11531 		opt = opts.ipoptp_cur;
11532 		optlen = opts.ipoptp_len;
11533 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11534 		    optval, optlen));
11535 		switch (optval) {
11536 			uint32_t off;
11537 		case IPOPT_SSRR:
11538 		case IPOPT_LSRR:
11539 			/*
11540 			 * If dst is one of our addresses and there are some
11541 			 * entries left in the source route return (true).
11542 			 */
11543 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11544 				ip2dbg(("ip_source_routed: not next"
11545 				    " source route 0x%x\n",
11546 				    ntohl(dst)));
11547 				return (B_FALSE);
11548 			}
11549 			off = opt[IPOPT_OFFSET];
11550 			off--;
11551 			if (optlen < IP_ADDR_LEN ||
11552 			    off > optlen - IP_ADDR_LEN) {
11553 				/* End of source route */
11554 				ip1dbg(("ip_source_routed: end of SR\n"));
11555 				return (B_FALSE);
11556 			}
11557 			return (B_TRUE);
11558 		}
11559 	}
11560 	ip2dbg(("not source routed\n"));
11561 	return (B_FALSE);
11562 }
11563 
11564 /*
11565  * ip_unbind is called by the transports to remove a conn from
11566  * the fanout table.
11567  */
11568 void
11569 ip_unbind(conn_t *connp)
11570 {
11571 
11572 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11573 
11574 	if (is_system_labeled() && connp->conn_anon_port) {
11575 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11576 		    connp->conn_mlp_type, connp->conn_proto,
11577 		    ntohs(connp->conn_lport), B_FALSE);
11578 		connp->conn_anon_port = 0;
11579 	}
11580 	connp->conn_mlp_type = mlptSingle;
11581 
11582 	ipcl_hash_remove(connp);
11583 }
11584 
11585 /*
11586  * Used for deciding the MSS size for the upper layer. Thus
11587  * we need to check the outbound policy values in the conn.
11588  */
11589 int
11590 conn_ipsec_length(conn_t *connp)
11591 {
11592 	ipsec_latch_t *ipl;
11593 
11594 	ipl = connp->conn_latch;
11595 	if (ipl == NULL)
11596 		return (0);
11597 
11598 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11599 		return (0);
11600 
11601 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11602 }
11603 
11604 /*
11605  * Returns an estimate of the IPsec headers size. This is used if
11606  * we don't want to call into IPsec to get the exact size.
11607  */
11608 int
11609 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11610 {
11611 	ipsec_action_t *a;
11612 
11613 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11614 		return (0);
11615 
11616 	a = ixa->ixa_ipsec_action;
11617 	if (a == NULL) {
11618 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11619 		a = ixa->ixa_ipsec_policy->ipsp_act;
11620 	}
11621 	ASSERT(a != NULL);
11622 
11623 	return (a->ipa_ovhd);
11624 }
11625 
11626 /*
11627  * If there are any source route options, return the true final
11628  * destination. Otherwise, return the destination.
11629  */
11630 ipaddr_t
11631 ip_get_dst(ipha_t *ipha)
11632 {
11633 	ipoptp_t	opts;
11634 	uchar_t		*opt;
11635 	uint8_t		optval;
11636 	uint8_t		optlen;
11637 	ipaddr_t	dst;
11638 	uint32_t off;
11639 
11640 	dst = ipha->ipha_dst;
11641 
11642 	if (IS_SIMPLE_IPH(ipha))
11643 		return (dst);
11644 
11645 	for (optval = ipoptp_first(&opts, ipha);
11646 	    optval != IPOPT_EOL;
11647 	    optval = ipoptp_next(&opts)) {
11648 		opt = opts.ipoptp_cur;
11649 		optlen = opts.ipoptp_len;
11650 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11651 		switch (optval) {
11652 		case IPOPT_SSRR:
11653 		case IPOPT_LSRR:
11654 			off = opt[IPOPT_OFFSET];
11655 			/*
11656 			 * If one of the conditions is true, it means
11657 			 * end of options and dst already has the right
11658 			 * value.
11659 			 */
11660 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11661 				off = optlen - IP_ADDR_LEN;
11662 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11663 			}
11664 			return (dst);
11665 		default:
11666 			break;
11667 		}
11668 	}
11669 
11670 	return (dst);
11671 }
11672 
11673 /*
11674  * Outbound IP fragmentation routine.
11675  * Assumes the caller has checked whether or not fragmentation should
11676  * be allowed. Here we copy the DF bit from the header to all the generated
11677  * fragments.
11678  */
11679 int
11680 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11681     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11682     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11683 {
11684 	int		i1;
11685 	int		hdr_len;
11686 	mblk_t		*hdr_mp;
11687 	ipha_t		*ipha;
11688 	int		ip_data_end;
11689 	int		len;
11690 	mblk_t		*mp = mp_orig;
11691 	int		offset;
11692 	ill_t		*ill = nce->nce_ill;
11693 	ip_stack_t	*ipst = ill->ill_ipst;
11694 	mblk_t		*carve_mp;
11695 	uint32_t	frag_flag;
11696 	uint_t		priority = mp->b_band;
11697 	int		error = 0;
11698 
11699 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11700 
11701 	if (pkt_len != msgdsize(mp)) {
11702 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11703 		    pkt_len, msgdsize(mp)));
11704 		freemsg(mp);
11705 		return (EINVAL);
11706 	}
11707 
11708 	if (max_frag == 0) {
11709 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11710 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11711 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11712 		freemsg(mp);
11713 		return (EINVAL);
11714 	}
11715 
11716 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11717 	ipha = (ipha_t *)mp->b_rptr;
11718 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11719 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11720 
11721 	/*
11722 	 * Establish the starting offset.  May not be zero if we are fragging
11723 	 * a fragment that is being forwarded.
11724 	 */
11725 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11726 
11727 	/* TODO why is this test needed? */
11728 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11729 		/* TODO: notify ulp somehow */
11730 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11731 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11732 		freemsg(mp);
11733 		return (EINVAL);
11734 	}
11735 
11736 	hdr_len = IPH_HDR_LENGTH(ipha);
11737 	ipha->ipha_hdr_checksum = 0;
11738 
11739 	/*
11740 	 * Establish the number of bytes maximum per frag, after putting
11741 	 * in the header.
11742 	 */
11743 	len = (max_frag - hdr_len) & ~7;
11744 
11745 	/* Get a copy of the header for the trailing frags */
11746 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11747 	    mp);
11748 	if (hdr_mp == NULL) {
11749 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11750 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11751 		freemsg(mp);
11752 		return (ENOBUFS);
11753 	}
11754 
11755 	/* Store the starting offset, with the MoreFrags flag. */
11756 	i1 = offset | IPH_MF | frag_flag;
11757 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11758 
11759 	/* Establish the ending byte offset, based on the starting offset. */
11760 	offset <<= 3;
11761 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11762 
11763 	/* Store the length of the first fragment in the IP header. */
11764 	i1 = len + hdr_len;
11765 	ASSERT(i1 <= IP_MAXPACKET);
11766 	ipha->ipha_length = htons((uint16_t)i1);
11767 
11768 	/*
11769 	 * Compute the IP header checksum for the first frag.  We have to
11770 	 * watch out that we stop at the end of the header.
11771 	 */
11772 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11773 
11774 	/*
11775 	 * Now carve off the first frag.  Note that this will include the
11776 	 * original IP header.
11777 	 */
11778 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11779 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11780 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11781 		freeb(hdr_mp);
11782 		freemsg(mp_orig);
11783 		return (ENOBUFS);
11784 	}
11785 
11786 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11787 
11788 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11789 	    ixa_cookie);
11790 	if (error != 0 && error != EWOULDBLOCK) {
11791 		/* No point in sending the other fragments */
11792 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11793 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11794 		freeb(hdr_mp);
11795 		freemsg(mp_orig);
11796 		return (error);
11797 	}
11798 
11799 	/* No need to redo state machine in loop */
11800 	ixaflags &= ~IXAF_REACH_CONF;
11801 
11802 	/* Advance the offset to the second frag starting point. */
11803 	offset += len;
11804 	/*
11805 	 * Update hdr_len from the copied header - there might be less options
11806 	 * in the later fragments.
11807 	 */
11808 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11809 	/* Loop until done. */
11810 	for (;;) {
11811 		uint16_t	offset_and_flags;
11812 		uint16_t	ip_len;
11813 
11814 		if (ip_data_end - offset > len) {
11815 			/*
11816 			 * Carve off the appropriate amount from the original
11817 			 * datagram.
11818 			 */
11819 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11820 				mp = NULL;
11821 				break;
11822 			}
11823 			/*
11824 			 * More frags after this one.  Get another copy
11825 			 * of the header.
11826 			 */
11827 			if (carve_mp->b_datap->db_ref == 1 &&
11828 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11829 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11830 				/* Inline IP header */
11831 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11832 				    hdr_mp->b_rptr;
11833 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11834 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11835 				mp = carve_mp;
11836 			} else {
11837 				if (!(mp = copyb(hdr_mp))) {
11838 					freemsg(carve_mp);
11839 					break;
11840 				}
11841 				/* Get priority marking, if any. */
11842 				mp->b_band = priority;
11843 				mp->b_cont = carve_mp;
11844 			}
11845 			ipha = (ipha_t *)mp->b_rptr;
11846 			offset_and_flags = IPH_MF;
11847 		} else {
11848 			/*
11849 			 * Last frag.  Consume the header. Set len to
11850 			 * the length of this last piece.
11851 			 */
11852 			len = ip_data_end - offset;
11853 
11854 			/*
11855 			 * Carve off the appropriate amount from the original
11856 			 * datagram.
11857 			 */
11858 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11859 				mp = NULL;
11860 				break;
11861 			}
11862 			if (carve_mp->b_datap->db_ref == 1 &&
11863 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11864 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11865 				/* Inline IP header */
11866 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11867 				    hdr_mp->b_rptr;
11868 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11869 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11870 				mp = carve_mp;
11871 				freeb(hdr_mp);
11872 				hdr_mp = mp;
11873 			} else {
11874 				mp = hdr_mp;
11875 				/* Get priority marking, if any. */
11876 				mp->b_band = priority;
11877 				mp->b_cont = carve_mp;
11878 			}
11879 			ipha = (ipha_t *)mp->b_rptr;
11880 			/* A frag of a frag might have IPH_MF non-zero */
11881 			offset_and_flags =
11882 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11883 			    IPH_MF;
11884 		}
11885 		offset_and_flags |= (uint16_t)(offset >> 3);
11886 		offset_and_flags |= (uint16_t)frag_flag;
11887 		/* Store the offset and flags in the IP header. */
11888 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11889 
11890 		/* Store the length in the IP header. */
11891 		ip_len = (uint16_t)(len + hdr_len);
11892 		ipha->ipha_length = htons(ip_len);
11893 
11894 		/*
11895 		 * Set the IP header checksum.	Note that mp is just
11896 		 * the header, so this is easy to pass to ip_csum.
11897 		 */
11898 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11899 
11900 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11901 
11902 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11903 		    nolzid, ixa_cookie);
11904 		/* All done if we just consumed the hdr_mp. */
11905 		if (mp == hdr_mp) {
11906 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11907 			return (error);
11908 		}
11909 		if (error != 0 && error != EWOULDBLOCK) {
11910 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11911 			    mblk_t *, hdr_mp);
11912 			/* No point in sending the other fragments */
11913 			break;
11914 		}
11915 
11916 		/* Otherwise, advance and loop. */
11917 		offset += len;
11918 	}
11919 	/* Clean up following allocation failure. */
11920 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11921 	ip_drop_output("FragFails: loop ended", NULL, ill);
11922 	if (mp != hdr_mp)
11923 		freeb(hdr_mp);
11924 	if (mp != mp_orig)
11925 		freemsg(mp_orig);
11926 	return (error);
11927 }
11928 
11929 /*
11930  * Copy the header plus those options which have the copy bit set
11931  */
11932 static mblk_t *
11933 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11934     mblk_t *src)
11935 {
11936 	mblk_t	*mp;
11937 	uchar_t	*up;
11938 
11939 	/*
11940 	 * Quick check if we need to look for options without the copy bit
11941 	 * set
11942 	 */
11943 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11944 	if (!mp)
11945 		return (mp);
11946 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11947 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11948 		bcopy(rptr, mp->b_rptr, hdr_len);
11949 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11950 		return (mp);
11951 	}
11952 	up  = mp->b_rptr;
11953 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11954 	up += IP_SIMPLE_HDR_LENGTH;
11955 	rptr += IP_SIMPLE_HDR_LENGTH;
11956 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11957 	while (hdr_len > 0) {
11958 		uint32_t optval;
11959 		uint32_t optlen;
11960 
11961 		optval = *rptr;
11962 		if (optval == IPOPT_EOL)
11963 			break;
11964 		if (optval == IPOPT_NOP)
11965 			optlen = 1;
11966 		else
11967 			optlen = rptr[1];
11968 		if (optval & IPOPT_COPY) {
11969 			bcopy(rptr, up, optlen);
11970 			up += optlen;
11971 		}
11972 		rptr += optlen;
11973 		hdr_len -= optlen;
11974 	}
11975 	/*
11976 	 * Make sure that we drop an even number of words by filling
11977 	 * with EOL to the next word boundary.
11978 	 */
11979 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11980 	    hdr_len & 0x3; hdr_len++)
11981 		*up++ = IPOPT_EOL;
11982 	mp->b_wptr = up;
11983 	/* Update header length */
11984 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11985 	return (mp);
11986 }
11987 
11988 /*
11989  * Update any source route, record route, or timestamp options when
11990  * sending a packet back to ourselves.
11991  * Check that we are at end of strict source route.
11992  * The options have been sanity checked by ip_output_options().
11993  */
11994 void
11995 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11996 {
11997 	ipoptp_t	opts;
11998 	uchar_t		*opt;
11999 	uint8_t		optval;
12000 	uint8_t		optlen;
12001 	ipaddr_t	dst;
12002 	uint32_t	ts;
12003 	timestruc_t	now;
12004 
12005 	for (optval = ipoptp_first(&opts, ipha);
12006 	    optval != IPOPT_EOL;
12007 	    optval = ipoptp_next(&opts)) {
12008 		opt = opts.ipoptp_cur;
12009 		optlen = opts.ipoptp_len;
12010 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
12011 		switch (optval) {
12012 			uint32_t off;
12013 		case IPOPT_SSRR:
12014 		case IPOPT_LSRR:
12015 			off = opt[IPOPT_OFFSET];
12016 			off--;
12017 			if (optlen < IP_ADDR_LEN ||
12018 			    off > optlen - IP_ADDR_LEN) {
12019 				/* End of source route */
12020 				break;
12021 			}
12022 			/*
12023 			 * This will only happen if two consecutive entries
12024 			 * in the source route contains our address or if
12025 			 * it is a packet with a loose source route which
12026 			 * reaches us before consuming the whole source route
12027 			 */
12028 
12029 			if (optval == IPOPT_SSRR) {
12030 				return;
12031 			}
12032 			/*
12033 			 * Hack: instead of dropping the packet truncate the
12034 			 * source route to what has been used by filling the
12035 			 * rest with IPOPT_NOP.
12036 			 */
12037 			opt[IPOPT_OLEN] = (uint8_t)off;
12038 			while (off < optlen) {
12039 				opt[off++] = IPOPT_NOP;
12040 			}
12041 			break;
12042 		case IPOPT_RR:
12043 			off = opt[IPOPT_OFFSET];
12044 			off--;
12045 			if (optlen < IP_ADDR_LEN ||
12046 			    off > optlen - IP_ADDR_LEN) {
12047 				/* No more room - ignore */
12048 				ip1dbg((
12049 				    "ip_output_local_options: end of RR\n"));
12050 				break;
12051 			}
12052 			dst = htonl(INADDR_LOOPBACK);
12053 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12054 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12055 			break;
12056 		case IPOPT_TS:
12057 			/* Insert timestamp if there is romm */
12058 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12059 			case IPOPT_TS_TSONLY:
12060 				off = IPOPT_TS_TIMELEN;
12061 				break;
12062 			case IPOPT_TS_PRESPEC:
12063 			case IPOPT_TS_PRESPEC_RFC791:
12064 				/* Verify that the address matched */
12065 				off = opt[IPOPT_OFFSET] - 1;
12066 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12067 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12068 					/* Not for us */
12069 					break;
12070 				}
12071 				/* FALLTHRU */
12072 			case IPOPT_TS_TSANDADDR:
12073 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12074 				break;
12075 			default:
12076 				/*
12077 				 * ip_*put_options should have already
12078 				 * dropped this packet.
12079 				 */
12080 				cmn_err(CE_PANIC, "ip_output_local_options: "
12081 				    "unknown IT - bug in ip_output_options?\n");
12082 				return;	/* Keep "lint" happy */
12083 			}
12084 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12085 				/* Increase overflow counter */
12086 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12087 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12088 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12089 				    (off << 4);
12090 				break;
12091 			}
12092 			off = opt[IPOPT_OFFSET] - 1;
12093 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12094 			case IPOPT_TS_PRESPEC:
12095 			case IPOPT_TS_PRESPEC_RFC791:
12096 			case IPOPT_TS_TSANDADDR:
12097 				dst = htonl(INADDR_LOOPBACK);
12098 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12099 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12100 				/* FALLTHRU */
12101 			case IPOPT_TS_TSONLY:
12102 				off = opt[IPOPT_OFFSET] - 1;
12103 				/* Compute # of milliseconds since midnight */
12104 				gethrestime(&now);
12105 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12106 				    now.tv_nsec / (NANOSEC / MILLISEC);
12107 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12108 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12109 				break;
12110 			}
12111 			break;
12112 		}
12113 	}
12114 }
12115 
12116 /*
12117  * Prepend an M_DATA fastpath header, and if none present prepend a
12118  * DL_UNITDATA_REQ. Frees the mblk on failure.
12119  *
12120  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12121  * If there is a change to them, the nce will be deleted (condemned) and
12122  * a new nce_t will be created when packets are sent. Thus we need no locks
12123  * to access those fields.
12124  *
12125  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12126  * we place b_band in dl_priority.dl_max.
12127  */
12128 static mblk_t *
12129 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12130 {
12131 	uint_t	hlen;
12132 	mblk_t *mp1;
12133 	uint_t	priority;
12134 	uchar_t *rptr;
12135 
12136 	rptr = mp->b_rptr;
12137 
12138 	ASSERT(DB_TYPE(mp) == M_DATA);
12139 	priority = mp->b_band;
12140 
12141 	ASSERT(nce != NULL);
12142 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12143 		hlen = MBLKL(mp1);
12144 		/*
12145 		 * Check if we have enough room to prepend fastpath
12146 		 * header
12147 		 */
12148 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12149 			rptr -= hlen;
12150 			bcopy(mp1->b_rptr, rptr, hlen);
12151 			/*
12152 			 * Set the b_rptr to the start of the link layer
12153 			 * header
12154 			 */
12155 			mp->b_rptr = rptr;
12156 			return (mp);
12157 		}
12158 		mp1 = copyb(mp1);
12159 		if (mp1 == NULL) {
12160 			ill_t *ill = nce->nce_ill;
12161 
12162 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12163 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12164 			freemsg(mp);
12165 			return (NULL);
12166 		}
12167 		mp1->b_band = priority;
12168 		mp1->b_cont = mp;
12169 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12170 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12171 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12172 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12173 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12174 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12175 		/*
12176 		 * XXX disable ICK_VALID and compute checksum
12177 		 * here; can happen if nce_fp_mp changes and
12178 		 * it can't be copied now due to insufficient
12179 		 * space. (unlikely, fp mp can change, but it
12180 		 * does not increase in length)
12181 		 */
12182 		return (mp1);
12183 	}
12184 	mp1 = copyb(nce->nce_dlur_mp);
12185 
12186 	if (mp1 == NULL) {
12187 		ill_t *ill = nce->nce_ill;
12188 
12189 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12190 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12191 		freemsg(mp);
12192 		return (NULL);
12193 	}
12194 	mp1->b_cont = mp;
12195 	if (priority != 0) {
12196 		mp1->b_band = priority;
12197 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12198 		    priority;
12199 	}
12200 	return (mp1);
12201 #undef rptr
12202 }
12203 
12204 /*
12205  * Finish the outbound IPsec processing. This function is called from
12206  * ipsec_out_process() if the IPsec packet was processed
12207  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12208  * asynchronously.
12209  *
12210  * This is common to IPv4 and IPv6.
12211  */
12212 int
12213 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12214 {
12215 	iaflags_t	ixaflags = ixa->ixa_flags;
12216 	uint_t		pktlen;
12217 
12218 
12219 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12220 	if (ixaflags & IXAF_IS_IPV4) {
12221 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12222 
12223 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12224 		pktlen = ntohs(ipha->ipha_length);
12225 	} else {
12226 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12227 
12228 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12229 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12230 	}
12231 
12232 	/*
12233 	 * We release any hard reference on the SAs here to make
12234 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12235 	 * on the SAs.
12236 	 * If in the future we want the hard latching of the SAs in the
12237 	 * ip_xmit_attr_t then we should remove this.
12238 	 */
12239 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12240 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12241 		ixa->ixa_ipsec_esp_sa = NULL;
12242 	}
12243 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12244 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12245 		ixa->ixa_ipsec_ah_sa = NULL;
12246 	}
12247 
12248 	/* Do we need to fragment? */
12249 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12250 	    pktlen > ixa->ixa_fragsize) {
12251 		if (ixaflags & IXAF_IS_IPV4) {
12252 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12253 			/*
12254 			 * We check for the DF case in ipsec_out_process
12255 			 * hence this only handles the non-DF case.
12256 			 */
12257 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12258 			    pktlen, ixa->ixa_fragsize,
12259 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12260 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12261 			    &ixa->ixa_cookie));
12262 		} else {
12263 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12264 			if (mp == NULL) {
12265 				/* MIB and ip_drop_output already done */
12266 				return (ENOMEM);
12267 			}
12268 			pktlen += sizeof (ip6_frag_t);
12269 			if (pktlen > ixa->ixa_fragsize) {
12270 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12271 				    ixa->ixa_flags, pktlen,
12272 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12273 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12274 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12275 			}
12276 		}
12277 	}
12278 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12279 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12280 	    ixa->ixa_no_loop_zoneid, NULL));
12281 }
12282 
12283 /*
12284  * Finish the inbound IPsec processing. This function is called from
12285  * ipsec_out_process() if the IPsec packet was processed
12286  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12287  * asynchronously.
12288  *
12289  * This is common to IPv4 and IPv6.
12290  */
12291 void
12292 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12293 {
12294 	iaflags_t	iraflags = ira->ira_flags;
12295 
12296 	/* Length might have changed */
12297 	if (iraflags & IRAF_IS_IPV4) {
12298 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12299 
12300 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12301 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12302 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12303 		ira->ira_protocol = ipha->ipha_protocol;
12304 
12305 		ip_fanout_v4(mp, ipha, ira);
12306 	} else {
12307 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12308 		uint8_t		*nexthdrp;
12309 
12310 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12311 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12312 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12313 		    &nexthdrp)) {
12314 			/* Malformed packet */
12315 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12316 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12317 			freemsg(mp);
12318 			return;
12319 		}
12320 		ira->ira_protocol = *nexthdrp;
12321 		ip_fanout_v6(mp, ip6h, ira);
12322 	}
12323 }
12324 
12325 /*
12326  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12327  *
12328  * If this function returns B_TRUE, the requested SA's have been filled
12329  * into the ixa_ipsec_*_sa pointers.
12330  *
12331  * If the function returns B_FALSE, the packet has been "consumed", most
12332  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12333  *
12334  * The SA references created by the protocol-specific "select"
12335  * function will be released in ip_output_post_ipsec.
12336  */
12337 static boolean_t
12338 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12339 {
12340 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12341 	ipsec_policy_t *pp;
12342 	ipsec_action_t *ap;
12343 
12344 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12345 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12346 	    (ixa->ixa_ipsec_action != NULL));
12347 
12348 	ap = ixa->ixa_ipsec_action;
12349 	if (ap == NULL) {
12350 		pp = ixa->ixa_ipsec_policy;
12351 		ASSERT(pp != NULL);
12352 		ap = pp->ipsp_act;
12353 		ASSERT(ap != NULL);
12354 	}
12355 
12356 	/*
12357 	 * We have an action.  now, let's select SA's.
12358 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12359 	 * be cached in the conn_t.
12360 	 */
12361 	if (ap->ipa_want_esp) {
12362 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12363 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12364 			    IPPROTO_ESP);
12365 		}
12366 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12367 	}
12368 
12369 	if (ap->ipa_want_ah) {
12370 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12371 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12372 			    IPPROTO_AH);
12373 		}
12374 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12375 		/*
12376 		 * The ESP and AH processing order needs to be preserved
12377 		 * when both protocols are required (ESP should be applied
12378 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12379 		 * when both ESP and AH are required, and an AH ACQUIRE
12380 		 * is needed.
12381 		 */
12382 		if (ap->ipa_want_esp && need_ah_acquire)
12383 			need_esp_acquire = B_TRUE;
12384 	}
12385 
12386 	/*
12387 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12388 	 * Release SAs that got referenced, but will not be used until we
12389 	 * acquire _all_ of the SAs we need.
12390 	 */
12391 	if (need_ah_acquire || need_esp_acquire) {
12392 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12393 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12394 			ixa->ixa_ipsec_ah_sa = NULL;
12395 		}
12396 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12397 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12398 			ixa->ixa_ipsec_esp_sa = NULL;
12399 		}
12400 
12401 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12402 		return (B_FALSE);
12403 	}
12404 
12405 	return (B_TRUE);
12406 }
12407 
12408 /*
12409  * Handle IPsec output processing.
12410  * This function is only entered once for a given packet.
12411  * We try to do things synchronously, but if we need to have user-level
12412  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12413  * will be completed
12414  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12415  *  - when asynchronous ESP is done it will do AH
12416  *
12417  * In all cases we come back in ip_output_post_ipsec() to fragment and
12418  * send out the packet.
12419  */
12420 int
12421 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12422 {
12423 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12424 	ip_stack_t	*ipst = ixa->ixa_ipst;
12425 	ipsec_stack_t	*ipss;
12426 	ipsec_policy_t	*pp;
12427 	ipsec_action_t	*ap;
12428 
12429 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12430 
12431 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12432 	    (ixa->ixa_ipsec_action != NULL));
12433 
12434 	ipss = ipst->ips_netstack->netstack_ipsec;
12435 	if (!ipsec_loaded(ipss)) {
12436 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12437 		ip_drop_packet(mp, B_TRUE, ill,
12438 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12439 		    &ipss->ipsec_dropper);
12440 		return (ENOTSUP);
12441 	}
12442 
12443 	ap = ixa->ixa_ipsec_action;
12444 	if (ap == NULL) {
12445 		pp = ixa->ixa_ipsec_policy;
12446 		ASSERT(pp != NULL);
12447 		ap = pp->ipsp_act;
12448 		ASSERT(ap != NULL);
12449 	}
12450 
12451 	/* Handle explicit drop action and bypass. */
12452 	switch (ap->ipa_act.ipa_type) {
12453 	case IPSEC_ACT_DISCARD:
12454 	case IPSEC_ACT_REJECT:
12455 		ip_drop_packet(mp, B_FALSE, ill,
12456 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12457 		return (EHOSTUNREACH);	/* IPsec policy failure */
12458 	case IPSEC_ACT_BYPASS:
12459 		return (ip_output_post_ipsec(mp, ixa));
12460 	}
12461 
12462 	/*
12463 	 * The order of processing is first insert a IP header if needed.
12464 	 * Then insert the ESP header and then the AH header.
12465 	 */
12466 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12467 		/*
12468 		 * First get the outer IP header before sending
12469 		 * it to ESP.
12470 		 */
12471 		ipha_t *oipha, *iipha;
12472 		mblk_t *outer_mp, *inner_mp;
12473 
12474 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12475 			(void) mi_strlog(ill->ill_rq, 0,
12476 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12477 			    "ipsec_out_process: "
12478 			    "Self-Encapsulation failed: Out of memory\n");
12479 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12480 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12481 			freemsg(mp);
12482 			return (ENOBUFS);
12483 		}
12484 		inner_mp = mp;
12485 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12486 		oipha = (ipha_t *)outer_mp->b_rptr;
12487 		iipha = (ipha_t *)inner_mp->b_rptr;
12488 		*oipha = *iipha;
12489 		outer_mp->b_wptr += sizeof (ipha_t);
12490 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12491 		    sizeof (ipha_t));
12492 		oipha->ipha_protocol = IPPROTO_ENCAP;
12493 		oipha->ipha_version_and_hdr_length =
12494 		    IP_SIMPLE_HDR_VERSION;
12495 		oipha->ipha_hdr_checksum = 0;
12496 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12497 		outer_mp->b_cont = inner_mp;
12498 		mp = outer_mp;
12499 
12500 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12501 	}
12502 
12503 	/* If we need to wait for a SA then we can't return any errno */
12504 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12505 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12506 	    !ipsec_out_select_sa(mp, ixa))
12507 		return (0);
12508 
12509 	/*
12510 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12511 	 * to do the heavy lifting.
12512 	 */
12513 	if (ap->ipa_want_esp) {
12514 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12515 
12516 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12517 		if (mp == NULL) {
12518 			/*
12519 			 * Either it failed or is pending. In the former case
12520 			 * ipIfStatsInDiscards was increased.
12521 			 */
12522 			return (0);
12523 		}
12524 	}
12525 
12526 	if (ap->ipa_want_ah) {
12527 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12528 
12529 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12530 		if (mp == NULL) {
12531 			/*
12532 			 * Either it failed or is pending. In the former case
12533 			 * ipIfStatsInDiscards was increased.
12534 			 */
12535 			return (0);
12536 		}
12537 	}
12538 	/*
12539 	 * We are done with IPsec processing. Send it over
12540 	 * the wire.
12541 	 */
12542 	return (ip_output_post_ipsec(mp, ixa));
12543 }
12544 
12545 /*
12546  * ioctls that go through a down/up sequence may need to wait for the down
12547  * to complete. This involves waiting for the ire and ipif refcnts to go down
12548  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12549  */
12550 /* ARGSUSED */
12551 void
12552 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12553 {
12554 	struct iocblk *iocp;
12555 	mblk_t *mp1;
12556 	ip_ioctl_cmd_t *ipip;
12557 	int err;
12558 	sin_t	*sin;
12559 	struct lifreq *lifr;
12560 	struct ifreq *ifr;
12561 
12562 	iocp = (struct iocblk *)mp->b_rptr;
12563 	ASSERT(ipsq != NULL);
12564 	/* Existence of mp1 verified in ip_wput_nondata */
12565 	mp1 = mp->b_cont->b_cont;
12566 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12567 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12568 		/*
12569 		 * Special case where ipx_current_ipif is not set:
12570 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12571 		 * We are here as were not able to complete the operation in
12572 		 * ipif_set_values because we could not become exclusive on
12573 		 * the new ipsq.
12574 		 */
12575 		ill_t *ill = q->q_ptr;
12576 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12577 	}
12578 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12579 
12580 	if (ipip->ipi_cmd_type == IF_CMD) {
12581 		/* This a old style SIOC[GS]IF* command */
12582 		ifr = (struct ifreq *)mp1->b_rptr;
12583 		sin = (sin_t *)&ifr->ifr_addr;
12584 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12585 		/* This a new style SIOC[GS]LIF* command */
12586 		lifr = (struct lifreq *)mp1->b_rptr;
12587 		sin = (sin_t *)&lifr->lifr_addr;
12588 	} else {
12589 		sin = NULL;
12590 	}
12591 
12592 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12593 	    q, mp, ipip, mp1->b_rptr);
12594 
12595 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12596 	    int, ipip->ipi_cmd,
12597 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12598 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12599 
12600 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12601 }
12602 
12603 /*
12604  * ioctl processing
12605  *
12606  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12607  * the ioctl command in the ioctl tables, determines the copyin data size
12608  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12609  *
12610  * ioctl processing then continues when the M_IOCDATA makes its way down to
12611  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12612  * associated 'conn' is refheld till the end of the ioctl and the general
12613  * ioctl processing function ip_process_ioctl() is called to extract the
12614  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12615  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12616  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12617  * is used to extract the ioctl's arguments.
12618  *
12619  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12620  * so goes thru the serialization primitive ipsq_try_enter. Then the
12621  * appropriate function to handle the ioctl is called based on the entry in
12622  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12623  * which also refreleases the 'conn' that was refheld at the start of the
12624  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12625  *
12626  * Many exclusive ioctls go thru an internal down up sequence as part of
12627  * the operation. For example an attempt to change the IP address of an
12628  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12629  * does all the cleanup such as deleting all ires that use this address.
12630  * Then we need to wait till all references to the interface go away.
12631  */
12632 void
12633 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12634 {
12635 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12636 	ip_ioctl_cmd_t *ipip = arg;
12637 	ip_extract_func_t *extract_funcp;
12638 	cmd_info_t ci;
12639 	int err;
12640 	boolean_t entered_ipsq = B_FALSE;
12641 
12642 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12643 
12644 	if (ipip == NULL)
12645 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12646 
12647 	/*
12648 	 * SIOCLIFADDIF needs to go thru a special path since the
12649 	 * ill may not exist yet. This happens in the case of lo0
12650 	 * which is created using this ioctl.
12651 	 */
12652 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12653 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12654 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12655 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12656 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12657 		return;
12658 	}
12659 
12660 	ci.ci_ipif = NULL;
12661 	switch (ipip->ipi_cmd_type) {
12662 	case MISC_CMD:
12663 	case MSFILT_CMD:
12664 		/*
12665 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12666 		 */
12667 		if (ipip->ipi_cmd == IF_UNITSEL) {
12668 			/* ioctl comes down the ill */
12669 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12670 			ipif_refhold(ci.ci_ipif);
12671 		}
12672 		err = 0;
12673 		ci.ci_sin = NULL;
12674 		ci.ci_sin6 = NULL;
12675 		ci.ci_lifr = NULL;
12676 		extract_funcp = NULL;
12677 		break;
12678 
12679 	case IF_CMD:
12680 	case LIF_CMD:
12681 		extract_funcp = ip_extract_lifreq;
12682 		break;
12683 
12684 	case ARP_CMD:
12685 	case XARP_CMD:
12686 		extract_funcp = ip_extract_arpreq;
12687 		break;
12688 
12689 	default:
12690 		ASSERT(0);
12691 	}
12692 
12693 	if (extract_funcp != NULL) {
12694 		err = (*extract_funcp)(q, mp, ipip, &ci);
12695 		if (err != 0) {
12696 			DTRACE_PROBE4(ipif__ioctl,
12697 			    char *, "ip_process_ioctl finish err",
12698 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12699 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12700 			return;
12701 		}
12702 
12703 		/*
12704 		 * All of the extraction functions return a refheld ipif.
12705 		 */
12706 		ASSERT(ci.ci_ipif != NULL);
12707 	}
12708 
12709 	if (!(ipip->ipi_flags & IPI_WR)) {
12710 		/*
12711 		 * A return value of EINPROGRESS means the ioctl is
12712 		 * either queued and waiting for some reason or has
12713 		 * already completed.
12714 		 */
12715 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12716 		    ci.ci_lifr);
12717 		if (ci.ci_ipif != NULL) {
12718 			DTRACE_PROBE4(ipif__ioctl,
12719 			    char *, "ip_process_ioctl finish RD",
12720 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12721 			    ipif_t *, ci.ci_ipif);
12722 			ipif_refrele(ci.ci_ipif);
12723 		} else {
12724 			DTRACE_PROBE4(ipif__ioctl,
12725 			    char *, "ip_process_ioctl finish RD",
12726 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12727 		}
12728 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12729 		return;
12730 	}
12731 
12732 	ASSERT(ci.ci_ipif != NULL);
12733 
12734 	/*
12735 	 * If ipsq is non-NULL, we are already being called exclusively
12736 	 */
12737 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12738 	if (ipsq == NULL) {
12739 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12740 		    NEW_OP, B_TRUE);
12741 		if (ipsq == NULL) {
12742 			ipif_refrele(ci.ci_ipif);
12743 			return;
12744 		}
12745 		entered_ipsq = B_TRUE;
12746 	}
12747 	/*
12748 	 * Release the ipif so that ipif_down and friends that wait for
12749 	 * references to go away are not misled about the current ipif_refcnt
12750 	 * values. We are writer so we can access the ipif even after releasing
12751 	 * the ipif.
12752 	 */
12753 	ipif_refrele(ci.ci_ipif);
12754 
12755 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12756 
12757 	/*
12758 	 * A return value of EINPROGRESS means the ioctl is
12759 	 * either queued and waiting for some reason or has
12760 	 * already completed.
12761 	 */
12762 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12763 
12764 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12765 	    int, ipip->ipi_cmd,
12766 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12767 	    ipif_t *, ci.ci_ipif);
12768 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12769 
12770 	if (entered_ipsq)
12771 		ipsq_exit(ipsq);
12772 }
12773 
12774 /*
12775  * Complete the ioctl. Typically ioctls use the mi package and need to
12776  * do mi_copyout/mi_copy_done.
12777  */
12778 void
12779 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12780 {
12781 	conn_t	*connp = NULL;
12782 
12783 	if (err == EINPROGRESS)
12784 		return;
12785 
12786 	if (CONN_Q(q)) {
12787 		connp = Q_TO_CONN(q);
12788 		ASSERT(connp->conn_ref >= 2);
12789 	}
12790 
12791 	switch (mode) {
12792 	case COPYOUT:
12793 		if (err == 0)
12794 			mi_copyout(q, mp);
12795 		else
12796 			mi_copy_done(q, mp, err);
12797 		break;
12798 
12799 	case NO_COPYOUT:
12800 		mi_copy_done(q, mp, err);
12801 		break;
12802 
12803 	default:
12804 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12805 		break;
12806 	}
12807 
12808 	/*
12809 	 * The refhold placed at the start of the ioctl is released here.
12810 	 */
12811 	if (connp != NULL)
12812 		CONN_OPER_PENDING_DONE(connp);
12813 
12814 	if (ipsq != NULL)
12815 		ipsq_current_finish(ipsq);
12816 }
12817 
12818 /* Handles all non data messages */
12819 void
12820 ip_wput_nondata(queue_t *q, mblk_t *mp)
12821 {
12822 	mblk_t		*mp1;
12823 	struct iocblk	*iocp;
12824 	ip_ioctl_cmd_t	*ipip;
12825 	conn_t		*connp;
12826 	cred_t		*cr;
12827 	char		*proto_str;
12828 
12829 	if (CONN_Q(q))
12830 		connp = Q_TO_CONN(q);
12831 	else
12832 		connp = NULL;
12833 
12834 	switch (DB_TYPE(mp)) {
12835 	case M_IOCTL:
12836 		/*
12837 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12838 		 * will arrange to copy in associated control structures.
12839 		 */
12840 		ip_sioctl_copyin_setup(q, mp);
12841 		return;
12842 	case M_IOCDATA:
12843 		/*
12844 		 * Ensure that this is associated with one of our trans-
12845 		 * parent ioctls.  If it's not ours, discard it if we're
12846 		 * running as a driver, or pass it on if we're a module.
12847 		 */
12848 		iocp = (struct iocblk *)mp->b_rptr;
12849 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12850 		if (ipip == NULL) {
12851 			if (q->q_next == NULL) {
12852 				goto nak;
12853 			} else {
12854 				putnext(q, mp);
12855 			}
12856 			return;
12857 		}
12858 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12859 			/*
12860 			 * The ioctl is one we recognise, but is not consumed
12861 			 * by IP as a module and we are a module, so we drop
12862 			 */
12863 			goto nak;
12864 		}
12865 
12866 		/* IOCTL continuation following copyin or copyout. */
12867 		if (mi_copy_state(q, mp, NULL) == -1) {
12868 			/*
12869 			 * The copy operation failed.  mi_copy_state already
12870 			 * cleaned up, so we're out of here.
12871 			 */
12872 			return;
12873 		}
12874 		/*
12875 		 * If we just completed a copy in, we become writer and
12876 		 * continue processing in ip_sioctl_copyin_done.  If it
12877 		 * was a copy out, we call mi_copyout again.  If there is
12878 		 * nothing more to copy out, it will complete the IOCTL.
12879 		 */
12880 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12881 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12882 				mi_copy_done(q, mp, EPROTO);
12883 				return;
12884 			}
12885 			/*
12886 			 * Check for cases that need more copying.  A return
12887 			 * value of 0 means a second copyin has been started,
12888 			 * so we return; a return value of 1 means no more
12889 			 * copying is needed, so we continue.
12890 			 */
12891 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12892 			    MI_COPY_COUNT(mp) == 1) {
12893 				if (ip_copyin_msfilter(q, mp) == 0)
12894 					return;
12895 			}
12896 			/*
12897 			 * Refhold the conn, till the ioctl completes. This is
12898 			 * needed in case the ioctl ends up in the pending mp
12899 			 * list. Every mp in the ipx_pending_mp list
12900 			 * must have a refhold on the conn
12901 			 * to resume processing. The refhold is released when
12902 			 * the ioctl completes. (normally or abnormally)
12903 			 * In all cases ip_ioctl_finish is called to finish
12904 			 * the ioctl.
12905 			 */
12906 			if (connp != NULL) {
12907 				/* This is not a reentry */
12908 				CONN_INC_REF(connp);
12909 			} else {
12910 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12911 					mi_copy_done(q, mp, EINVAL);
12912 					return;
12913 				}
12914 			}
12915 
12916 			ip_process_ioctl(NULL, q, mp, ipip);
12917 
12918 		} else {
12919 			mi_copyout(q, mp);
12920 		}
12921 		return;
12922 
12923 	case M_IOCNAK:
12924 		/*
12925 		 * The only way we could get here is if a resolver didn't like
12926 		 * an IOCTL we sent it.	 This shouldn't happen.
12927 		 */
12928 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12929 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12930 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12931 		freemsg(mp);
12932 		return;
12933 	case M_IOCACK:
12934 		/* /dev/ip shouldn't see this */
12935 		goto nak;
12936 	case M_FLUSH:
12937 		if (*mp->b_rptr & FLUSHW)
12938 			flushq(q, FLUSHALL);
12939 		if (q->q_next) {
12940 			putnext(q, mp);
12941 			return;
12942 		}
12943 		if (*mp->b_rptr & FLUSHR) {
12944 			*mp->b_rptr &= ~FLUSHW;
12945 			qreply(q, mp);
12946 			return;
12947 		}
12948 		freemsg(mp);
12949 		return;
12950 	case M_CTL:
12951 		break;
12952 	case M_PROTO:
12953 	case M_PCPROTO:
12954 		/*
12955 		 * The only PROTO messages we expect are SNMP-related.
12956 		 */
12957 		switch (((union T_primitives *)mp->b_rptr)->type) {
12958 		case T_SVR4_OPTMGMT_REQ:
12959 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12960 			    "flags %x\n",
12961 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12962 
12963 			if (connp == NULL) {
12964 				proto_str = "T_SVR4_OPTMGMT_REQ";
12965 				goto protonak;
12966 			}
12967 
12968 			/*
12969 			 * All Solaris components should pass a db_credp
12970 			 * for this TPI message, hence we ASSERT.
12971 			 * But in case there is some other M_PROTO that looks
12972 			 * like a TPI message sent by some other kernel
12973 			 * component, we check and return an error.
12974 			 */
12975 			cr = msg_getcred(mp, NULL);
12976 			ASSERT(cr != NULL);
12977 			if (cr == NULL) {
12978 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12979 				if (mp != NULL)
12980 					qreply(q, mp);
12981 				return;
12982 			}
12983 
12984 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12985 				proto_str = "Bad SNMPCOM request?";
12986 				goto protonak;
12987 			}
12988 			return;
12989 		default:
12990 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12991 			    (int)*(uint_t *)mp->b_rptr));
12992 			freemsg(mp);
12993 			return;
12994 		}
12995 	default:
12996 		break;
12997 	}
12998 	if (q->q_next) {
12999 		putnext(q, mp);
13000 	} else
13001 		freemsg(mp);
13002 	return;
13003 
13004 nak:
13005 	iocp->ioc_error = EINVAL;
13006 	mp->b_datap->db_type = M_IOCNAK;
13007 	iocp->ioc_count = 0;
13008 	qreply(q, mp);
13009 	return;
13010 
13011 protonak:
13012 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
13013 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
13014 		qreply(q, mp);
13015 }
13016 
13017 /*
13018  * Process IP options in an outbound packet.  Verify that the nexthop in a
13019  * strict source route is onlink.
13020  * Returns non-zero if something fails in which case an ICMP error has been
13021  * sent and mp freed.
13022  *
13023  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
13024  */
13025 int
13026 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
13027 {
13028 	ipoptp_t	opts;
13029 	uchar_t		*opt;
13030 	uint8_t		optval;
13031 	uint8_t		optlen;
13032 	ipaddr_t	dst;
13033 	intptr_t	code = 0;
13034 	ire_t		*ire;
13035 	ip_stack_t	*ipst = ixa->ixa_ipst;
13036 	ip_recv_attr_t	iras;
13037 
13038 	ip2dbg(("ip_output_options\n"));
13039 
13040 	dst = ipha->ipha_dst;
13041 	for (optval = ipoptp_first(&opts, ipha);
13042 	    optval != IPOPT_EOL;
13043 	    optval = ipoptp_next(&opts)) {
13044 		opt = opts.ipoptp_cur;
13045 		optlen = opts.ipoptp_len;
13046 		ip2dbg(("ip_output_options: opt %d, len %d\n",
13047 		    optval, optlen));
13048 		switch (optval) {
13049 			uint32_t off;
13050 		case IPOPT_SSRR:
13051 		case IPOPT_LSRR:
13052 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13053 				ip1dbg((
13054 				    "ip_output_options: bad option offset\n"));
13055 				code = (char *)&opt[IPOPT_OLEN] -
13056 				    (char *)ipha;
13057 				goto param_prob;
13058 			}
13059 			off = opt[IPOPT_OFFSET];
13060 			ip1dbg(("ip_output_options: next hop 0x%x\n",
13061 			    ntohl(dst)));
13062 			/*
13063 			 * For strict: verify that dst is directly
13064 			 * reachable.
13065 			 */
13066 			if (optval == IPOPT_SSRR) {
13067 				ire = ire_ftable_lookup_v4(dst, 0, 0,
13068 				    IRE_IF_ALL, NULL, ALL_ZONES, ixa->ixa_tsl,
13069 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13070 				    NULL);
13071 				if (ire == NULL) {
13072 					ip1dbg(("ip_output_options: SSRR not"
13073 					    " directly reachable: 0x%x\n",
13074 					    ntohl(dst)));
13075 					goto bad_src_route;
13076 				}
13077 				ire_refrele(ire);
13078 			}
13079 			break;
13080 		case IPOPT_RR:
13081 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13082 				ip1dbg((
13083 				    "ip_output_options: bad option offset\n"));
13084 				code = (char *)&opt[IPOPT_OLEN] -
13085 				    (char *)ipha;
13086 				goto param_prob;
13087 			}
13088 			break;
13089 		case IPOPT_TS:
13090 			/*
13091 			 * Verify that length >=5 and that there is either
13092 			 * room for another timestamp or that the overflow
13093 			 * counter is not maxed out.
13094 			 */
13095 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13096 			if (optlen < IPOPT_MINLEN_IT) {
13097 				goto param_prob;
13098 			}
13099 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13100 				ip1dbg((
13101 				    "ip_output_options: bad option offset\n"));
13102 				code = (char *)&opt[IPOPT_OFFSET] -
13103 				    (char *)ipha;
13104 				goto param_prob;
13105 			}
13106 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13107 			case IPOPT_TS_TSONLY:
13108 				off = IPOPT_TS_TIMELEN;
13109 				break;
13110 			case IPOPT_TS_TSANDADDR:
13111 			case IPOPT_TS_PRESPEC:
13112 			case IPOPT_TS_PRESPEC_RFC791:
13113 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13114 				break;
13115 			default:
13116 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13117 				    (char *)ipha;
13118 				goto param_prob;
13119 			}
13120 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13121 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13122 				/*
13123 				 * No room and the overflow counter is 15
13124 				 * already.
13125 				 */
13126 				goto param_prob;
13127 			}
13128 			break;
13129 		}
13130 	}
13131 
13132 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13133 		return (0);
13134 
13135 	ip1dbg(("ip_output_options: error processing IP options."));
13136 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13137 
13138 param_prob:
13139 	bzero(&iras, sizeof (iras));
13140 	iras.ira_ill = iras.ira_rill = ill;
13141 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13142 	iras.ira_rifindex = iras.ira_ruifindex;
13143 	iras.ira_flags = IRAF_IS_IPV4;
13144 
13145 	ip_drop_output("ip_output_options", mp, ill);
13146 	icmp_param_problem(mp, (uint8_t)code, &iras);
13147 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13148 	return (-1);
13149 
13150 bad_src_route:
13151 	bzero(&iras, sizeof (iras));
13152 	iras.ira_ill = iras.ira_rill = ill;
13153 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13154 	iras.ira_rifindex = iras.ira_ruifindex;
13155 	iras.ira_flags = IRAF_IS_IPV4;
13156 
13157 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13158 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13159 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13160 	return (-1);
13161 }
13162 
13163 /*
13164  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13165  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13166  * thru /etc/system.
13167  */
13168 #define	CONN_MAXDRAINCNT	64
13169 
13170 static void
13171 conn_drain_init(ip_stack_t *ipst)
13172 {
13173 	int i, j;
13174 	idl_tx_list_t *itl_tx;
13175 
13176 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13177 
13178 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13179 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13180 		/*
13181 		 * Default value of the number of drainers is the
13182 		 * number of cpus, subject to maximum of 8 drainers.
13183 		 */
13184 		if (boot_max_ncpus != -1)
13185 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13186 		else
13187 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13188 	}
13189 
13190 	ipst->ips_idl_tx_list =
13191 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13192 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13193 		itl_tx =  &ipst->ips_idl_tx_list[i];
13194 		itl_tx->txl_drain_list =
13195 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13196 		    sizeof (idl_t), KM_SLEEP);
13197 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13198 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13199 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13200 			    MUTEX_DEFAULT, NULL);
13201 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13202 		}
13203 	}
13204 }
13205 
13206 static void
13207 conn_drain_fini(ip_stack_t *ipst)
13208 {
13209 	int i;
13210 	idl_tx_list_t *itl_tx;
13211 
13212 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13213 		itl_tx =  &ipst->ips_idl_tx_list[i];
13214 		kmem_free(itl_tx->txl_drain_list,
13215 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13216 	}
13217 	kmem_free(ipst->ips_idl_tx_list,
13218 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13219 	ipst->ips_idl_tx_list = NULL;
13220 }
13221 
13222 /*
13223  * Note: For an overview of how flowcontrol is handled in IP please see the
13224  * IP Flowcontrol notes at the top of this file.
13225  *
13226  * Flow control has blocked us from proceeding. Insert the given conn in one
13227  * of the conn drain lists. These conn wq's will be qenabled later on when
13228  * STREAMS flow control does a backenable. conn_walk_drain will enable
13229  * the first conn in each of these drain lists. Each of these qenabled conns
13230  * in turn enables the next in the list, after it runs, or when it closes,
13231  * thus sustaining the drain process.
13232  */
13233 void
13234 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13235 {
13236 	idl_t	*idl = tx_list->txl_drain_list;
13237 	uint_t	index;
13238 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13239 
13240 	mutex_enter(&connp->conn_lock);
13241 	if (connp->conn_state_flags & CONN_CLOSING) {
13242 		/*
13243 		 * The conn is closing as a result of which CONN_CLOSING
13244 		 * is set. Return.
13245 		 */
13246 		mutex_exit(&connp->conn_lock);
13247 		return;
13248 	} else if (connp->conn_idl == NULL) {
13249 		/*
13250 		 * Assign the next drain list round robin. We dont' use
13251 		 * a lock, and thus it may not be strictly round robin.
13252 		 * Atomicity of load/stores is enough to make sure that
13253 		 * conn_drain_list_index is always within bounds.
13254 		 */
13255 		index = tx_list->txl_drain_index;
13256 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13257 		connp->conn_idl = &tx_list->txl_drain_list[index];
13258 		index++;
13259 		if (index == ipst->ips_conn_drain_list_cnt)
13260 			index = 0;
13261 		tx_list->txl_drain_index = index;
13262 	}
13263 	mutex_exit(&connp->conn_lock);
13264 
13265 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
13266 	if ((connp->conn_drain_prev != NULL) ||
13267 	    (connp->conn_state_flags & CONN_CLOSING)) {
13268 		/*
13269 		 * The conn is already in the drain list, OR
13270 		 * the conn is closing. We need to check again for
13271 		 * the closing case again since close can happen
13272 		 * after we drop the conn_lock, and before we
13273 		 * acquire the CONN_DRAIN_LIST_LOCK.
13274 		 */
13275 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13276 		return;
13277 	} else {
13278 		idl = connp->conn_idl;
13279 	}
13280 
13281 	/*
13282 	 * The conn is not in the drain list. Insert it at the
13283 	 * tail of the drain list. The drain list is circular
13284 	 * and doubly linked. idl_conn points to the 1st element
13285 	 * in the list.
13286 	 */
13287 	if (idl->idl_conn == NULL) {
13288 		idl->idl_conn = connp;
13289 		connp->conn_drain_next = connp;
13290 		connp->conn_drain_prev = connp;
13291 	} else {
13292 		conn_t *head = idl->idl_conn;
13293 
13294 		connp->conn_drain_next = head;
13295 		connp->conn_drain_prev = head->conn_drain_prev;
13296 		head->conn_drain_prev->conn_drain_next = connp;
13297 		head->conn_drain_prev = connp;
13298 	}
13299 	/*
13300 	 * For non streams based sockets assert flow control.
13301 	 */
13302 	conn_setqfull(connp, NULL);
13303 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
13304 }
13305 
13306 static void
13307 conn_idl_remove(conn_t *connp)
13308 {
13309 	idl_t *idl = connp->conn_idl;
13310 
13311 	if (idl != NULL) {
13312 		/*
13313 		 * Remove ourself from the drain list, if we did not do
13314 		 * a putq, or if the conn is closing.
13315 		 * Note: It is possible that q->q_first is non-null. It means
13316 		 * that these messages landed after we did a enableok() in
13317 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
13318 		 * service them.
13319 		 */
13320 		if (connp->conn_drain_next == connp) {
13321 			/* Singleton in the list */
13322 			ASSERT(connp->conn_drain_prev == connp);
13323 			idl->idl_conn = NULL;
13324 		} else {
13325 			connp->conn_drain_prev->conn_drain_next =
13326 			    connp->conn_drain_next;
13327 			connp->conn_drain_next->conn_drain_prev =
13328 			    connp->conn_drain_prev;
13329 			if (idl->idl_conn == connp)
13330 				idl->idl_conn = connp->conn_drain_next;
13331 		}
13332 	}
13333 	connp->conn_drain_next = NULL;
13334 	connp->conn_drain_prev = NULL;
13335 
13336 	conn_clrqfull(connp, NULL);
13337 	/*
13338 	 * For streams based sockets open up flow control.
13339 	 */
13340 	if (!IPCL_IS_NONSTR(connp))
13341 		enableok(connp->conn_wq);
13342 }
13343 
13344 /*
13345  * This conn is closing, and we are called from ip_close. OR
13346  * this conn is draining because flow-control on the ill has been relieved.
13347  *
13348  * We must also need to remove conn's on this idl from the list, and also
13349  * inform the sockfs upcalls about the change in flow-control.
13350  */
13351 static void
13352 conn_drain_tail(conn_t *connp, boolean_t closing)
13353 {
13354 	idl_t *idl;
13355 	conn_t *next_connp;
13356 
13357 	/*
13358 	 * connp->conn_idl is stable at this point, and no lock is needed
13359 	 * to check it. If we are called from ip_close, close has already
13360 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13361 	 * called us only because conn_idl is non-null. If we are called thru
13362 	 * service, conn_idl could be null, but it cannot change because
13363 	 * service is single-threaded per queue, and there cannot be another
13364 	 * instance of service trying to call conn_drain_insert on this conn
13365 	 * now.
13366 	 */
13367 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13368 
13369 	/*
13370 	 * If connp->conn_idl is null, the conn has not been inserted into any
13371 	 * drain list even once since creation of the conn. Just return.
13372 	 */
13373 	if (connp == NULL || connp->conn_idl == NULL)
13374 		return;
13375 
13376 	if (connp->conn_drain_prev == NULL) {
13377 		/* This conn is currently not in the drain list.  */
13378 		return;
13379 	}
13380 	idl = connp->conn_idl;
13381 	if (!closing) {
13382 		/*
13383 		 * This conn is the current drainer. If this is the last conn
13384 		 * in the drain list, we need to do more checks, in the 'if'
13385 		 * below. Otherwwise we need to just qenable the next conn,
13386 		 * to sustain the draining, and is handled in the 'else'
13387 		 * below.
13388 		 */
13389 		next_connp = connp->conn_drain_next;
13390 		while (next_connp != connp) {
13391 			conn_t *delconnp = next_connp;
13392 
13393 			next_connp = next_connp->conn_drain_next;
13394 			conn_idl_remove(delconnp);
13395 		}
13396 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13397 	}
13398 	conn_idl_remove(connp);
13399 
13400 }
13401 
13402 /*
13403  * Write service routine. Shared perimeter entry point.
13404  * The device queue's messages has fallen below the low water mark and STREAMS
13405  * has backenabled the ill_wq. Send sockfs notification about flow-control onx
13406  * each waiting conn.
13407  */
13408 void
13409 ip_wsrv(queue_t *q)
13410 {
13411 	ill_t	*ill;
13412 
13413 	ill = (ill_t *)q->q_ptr;
13414 	if (ill->ill_state_flags == 0) {
13415 		ip_stack_t *ipst = ill->ill_ipst;
13416 
13417 		/*
13418 		 * The device flow control has opened up.
13419 		 * Walk through conn drain lists and qenable the
13420 		 * first conn in each list. This makes sense only
13421 		 * if the stream is fully plumbed and setup.
13422 		 * Hence the ill_state_flags check above.
13423 		 */
13424 		ip1dbg(("ip_wsrv: walking\n"));
13425 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13426 		enableok(ill->ill_wq);
13427 	}
13428 }
13429 
13430 /*
13431  * Callback to disable flow control in IP.
13432  *
13433  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13434  * is enabled.
13435  *
13436  * When MAC_TX() is not able to send any more packets, dld sets its queue
13437  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13438  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13439  * function and wakes up corresponding mac worker threads, which in turn
13440  * calls this callback function, and disables flow control.
13441  */
13442 void
13443 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13444 {
13445 	ill_t *ill = (ill_t *)arg;
13446 	ip_stack_t *ipst = ill->ill_ipst;
13447 	idl_tx_list_t *idl_txl;
13448 
13449 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13450 	mutex_enter(&idl_txl->txl_lock);
13451 	/* add code to to set a flag to indicate idl_txl is enabled */
13452 	conn_walk_drain(ipst, idl_txl);
13453 	mutex_exit(&idl_txl->txl_lock);
13454 }
13455 
13456 /*
13457  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
13458  * of conns that need to be drained, check if drain is already in progress.
13459  * If so set the idl_repeat bit, indicating that the last conn in the list
13460  * needs to reinitiate the drain once again, for the list. If drain is not
13461  * in progress for the list, initiate the draining, by qenabling the 1st
13462  * conn in the list. The drain is self-sustaining, each qenabled conn will
13463  * in turn qenable the next conn, when it is done/blocked/closing.
13464  */
13465 static void
13466 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13467 {
13468 	int i;
13469 	idl_t *idl;
13470 
13471 	IP_STAT(ipst, ip_conn_walk_drain);
13472 
13473 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13474 		idl = &tx_list->txl_drain_list[i];
13475 		mutex_enter(&idl->idl_lock);
13476 		conn_drain_tail(idl->idl_conn, B_FALSE);
13477 		mutex_exit(&idl->idl_lock);
13478 	}
13479 }
13480 
13481 /*
13482  * Determine if the ill and multicast aspects of that packets
13483  * "matches" the conn.
13484  */
13485 boolean_t
13486 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13487 {
13488 	ill_t		*ill = ira->ira_rill;
13489 	zoneid_t	zoneid = ira->ira_zoneid;
13490 	uint_t		in_ifindex;
13491 	ipaddr_t	dst, src;
13492 
13493 	dst = ipha->ipha_dst;
13494 	src = ipha->ipha_src;
13495 
13496 	/*
13497 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13498 	 * unicast, broadcast and multicast reception to
13499 	 * conn_incoming_ifindex.
13500 	 * conn_wantpacket is called for unicast, broadcast and
13501 	 * multicast packets.
13502 	 */
13503 	in_ifindex = connp->conn_incoming_ifindex;
13504 
13505 	/* mpathd can bind to the under IPMP interface, which we allow */
13506 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13507 		if (!IS_UNDER_IPMP(ill))
13508 			return (B_FALSE);
13509 
13510 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13511 			return (B_FALSE);
13512 	}
13513 
13514 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13515 		return (B_FALSE);
13516 
13517 	if (!(ira->ira_flags & IRAF_MULTICAST))
13518 		return (B_TRUE);
13519 
13520 	if (connp->conn_multi_router) {
13521 		/* multicast packet and multicast router socket: send up */
13522 		return (B_TRUE);
13523 	}
13524 
13525 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13526 	    ipha->ipha_protocol == IPPROTO_RSVP)
13527 		return (B_TRUE);
13528 
13529 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13530 }
13531 
13532 void
13533 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13534 {
13535 	if (IPCL_IS_NONSTR(connp)) {
13536 		(*connp->conn_upcalls->su_txq_full)
13537 		    (connp->conn_upper_handle, B_TRUE);
13538 		if (flow_stopped != NULL)
13539 			*flow_stopped = B_TRUE;
13540 	} else {
13541 		queue_t *q = connp->conn_wq;
13542 
13543 		ASSERT(q != NULL);
13544 		if (!(q->q_flag & QFULL)) {
13545 			mutex_enter(QLOCK(q));
13546 			if (!(q->q_flag & QFULL)) {
13547 				/* still need to set QFULL */
13548 				q->q_flag |= QFULL;
13549 				/* set flow_stopped to true under QLOCK */
13550 				if (flow_stopped != NULL)
13551 					*flow_stopped = B_TRUE;
13552 				mutex_exit(QLOCK(q));
13553 			} else {
13554 				/* flow_stopped is left unchanged */
13555 				mutex_exit(QLOCK(q));
13556 			}
13557 		}
13558 	}
13559 }
13560 
13561 void
13562 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13563 {
13564 	if (IPCL_IS_NONSTR(connp)) {
13565 		(*connp->conn_upcalls->su_txq_full)
13566 		    (connp->conn_upper_handle, B_FALSE);
13567 		if (flow_stopped != NULL)
13568 			*flow_stopped = B_FALSE;
13569 	} else {
13570 		queue_t *q = connp->conn_wq;
13571 
13572 		ASSERT(q != NULL);
13573 		if (q->q_flag & QFULL) {
13574 			mutex_enter(QLOCK(q));
13575 			if (q->q_flag & QFULL) {
13576 				q->q_flag &= ~QFULL;
13577 				/* set flow_stopped to false under QLOCK */
13578 				if (flow_stopped != NULL)
13579 					*flow_stopped = B_FALSE;
13580 				mutex_exit(QLOCK(q));
13581 				if (q->q_flag & QWANTW)
13582 					qbackenable(q, 0);
13583 			} else {
13584 				/* flow_stopped is left unchanged */
13585 				mutex_exit(QLOCK(q));
13586 			}
13587 		}
13588 	}
13589 	connp->conn_direct_blocked = B_FALSE;
13590 }
13591 
13592 /*
13593  * Return the length in bytes of the IPv4 headers (base header, label, and
13594  * other IP options) that will be needed based on the
13595  * ip_pkt_t structure passed by the caller.
13596  *
13597  * The returned length does not include the length of the upper level
13598  * protocol (ULP) header.
13599  * The caller needs to check that the length doesn't exceed the max for IPv4.
13600  */
13601 int
13602 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13603 {
13604 	int len;
13605 
13606 	len = IP_SIMPLE_HDR_LENGTH;
13607 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13608 		ASSERT(ipp->ipp_label_len_v4 != 0);
13609 		/* We need to round up here */
13610 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13611 	}
13612 
13613 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13614 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13615 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13616 		len += ipp->ipp_ipv4_options_len;
13617 	}
13618 	return (len);
13619 }
13620 
13621 /*
13622  * All-purpose routine to build an IPv4 header with options based
13623  * on the abstract ip_pkt_t.
13624  *
13625  * The caller has to set the source and destination address as well as
13626  * ipha_length. The caller has to massage any source route and compensate
13627  * for the ULP pseudo-header checksum due to the source route.
13628  */
13629 void
13630 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13631     uint8_t protocol)
13632 {
13633 	ipha_t	*ipha = (ipha_t *)buf;
13634 	uint8_t *cp;
13635 
13636 	/* Initialize IPv4 header */
13637 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13638 	ipha->ipha_length = 0;	/* Caller will set later */
13639 	ipha->ipha_ident = 0;
13640 	ipha->ipha_fragment_offset_and_flags = 0;
13641 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13642 	ipha->ipha_protocol = protocol;
13643 	ipha->ipha_hdr_checksum = 0;
13644 
13645 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13646 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13647 		ipha->ipha_src = ipp->ipp_addr_v4;
13648 
13649 	cp = (uint8_t *)&ipha[1];
13650 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13651 		ASSERT(ipp->ipp_label_len_v4 != 0);
13652 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13653 		cp += ipp->ipp_label_len_v4;
13654 		/* We need to round up here */
13655 		while ((uintptr_t)cp & 0x3) {
13656 			*cp++ = IPOPT_NOP;
13657 		}
13658 	}
13659 
13660 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13661 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13662 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13663 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13664 		cp += ipp->ipp_ipv4_options_len;
13665 	}
13666 	ipha->ipha_version_and_hdr_length =
13667 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13668 
13669 	ASSERT((int)(cp - buf) == buf_len);
13670 }
13671 
13672 /* Allocate the private structure */
13673 static int
13674 ip_priv_alloc(void **bufp)
13675 {
13676 	void	*buf;
13677 
13678 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13679 		return (ENOMEM);
13680 
13681 	*bufp = buf;
13682 	return (0);
13683 }
13684 
13685 /* Function to delete the private structure */
13686 void
13687 ip_priv_free(void *buf)
13688 {
13689 	ASSERT(buf != NULL);
13690 	kmem_free(buf, sizeof (ip_priv_t));
13691 }
13692 
13693 /*
13694  * The entry point for IPPF processing.
13695  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13696  * routine just returns.
13697  *
13698  * When called, ip_process generates an ipp_packet_t structure
13699  * which holds the state information for this packet and invokes the
13700  * the classifier (via ipp_packet_process). The classification, depending on
13701  * configured filters, results in a list of actions for this packet. Invoking
13702  * an action may cause the packet to be dropped, in which case we return NULL.
13703  * proc indicates the callout position for
13704  * this packet and ill is the interface this packet arrived on or will leave
13705  * on (inbound and outbound resp.).
13706  *
13707  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13708  * on the ill corrsponding to the destination IP address.
13709  */
13710 mblk_t *
13711 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13712 {
13713 	ip_priv_t	*priv;
13714 	ipp_action_id_t	aid;
13715 	int		rc = 0;
13716 	ipp_packet_t	*pp;
13717 
13718 	/* If the classifier is not loaded, return  */
13719 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13720 		return (mp);
13721 	}
13722 
13723 	ASSERT(mp != NULL);
13724 
13725 	/* Allocate the packet structure */
13726 	rc = ipp_packet_alloc(&pp, "ip", aid);
13727 	if (rc != 0)
13728 		goto drop;
13729 
13730 	/* Allocate the private structure */
13731 	rc = ip_priv_alloc((void **)&priv);
13732 	if (rc != 0) {
13733 		ipp_packet_free(pp);
13734 		goto drop;
13735 	}
13736 	priv->proc = proc;
13737 	priv->ill_index = ill_get_upper_ifindex(rill);
13738 
13739 	ipp_packet_set_private(pp, priv, ip_priv_free);
13740 	ipp_packet_set_data(pp, mp);
13741 
13742 	/* Invoke the classifier */
13743 	rc = ipp_packet_process(&pp);
13744 	if (pp != NULL) {
13745 		mp = ipp_packet_get_data(pp);
13746 		ipp_packet_free(pp);
13747 		if (rc != 0)
13748 			goto drop;
13749 		return (mp);
13750 	} else {
13751 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13752 		mp = NULL;
13753 	}
13754 drop:
13755 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13756 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13757 		ip_drop_input("ip_process", mp, ill);
13758 	} else {
13759 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13760 		ip_drop_output("ip_process", mp, ill);
13761 	}
13762 	freemsg(mp);
13763 	return (NULL);
13764 }
13765 
13766 /*
13767  * Propagate a multicast group membership operation (add/drop) on
13768  * all the interfaces crossed by the related multirt routes.
13769  * The call is considered successful if the operation succeeds
13770  * on at least one interface.
13771  *
13772  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13773  * multicast addresses with the ire argument being the first one.
13774  * We walk the bucket to find all the of those.
13775  *
13776  * Common to IPv4 and IPv6.
13777  */
13778 static int
13779 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13780     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13781     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13782     mcast_record_t fmode, const in6_addr_t *v6src)
13783 {
13784 	ire_t		*ire_gw;
13785 	irb_t		*irb;
13786 	int		ifindex;
13787 	int		error = 0;
13788 	int		result;
13789 	ip_stack_t	*ipst = ire->ire_ipst;
13790 	ipaddr_t	group;
13791 	boolean_t	isv6;
13792 	int		match_flags;
13793 
13794 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13795 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13796 		isv6 = B_FALSE;
13797 	} else {
13798 		isv6 = B_TRUE;
13799 	}
13800 
13801 	irb = ire->ire_bucket;
13802 	ASSERT(irb != NULL);
13803 
13804 	result = 0;
13805 	irb_refhold(irb);
13806 	for (; ire != NULL; ire = ire->ire_next) {
13807 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13808 			continue;
13809 
13810 		/* We handle -ifp routes by matching on the ill if set */
13811 		match_flags = MATCH_IRE_TYPE;
13812 		if (ire->ire_ill != NULL)
13813 			match_flags |= MATCH_IRE_ILL;
13814 
13815 		if (isv6) {
13816 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13817 				continue;
13818 
13819 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13820 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13821 			    match_flags, 0, ipst, NULL);
13822 		} else {
13823 			if (ire->ire_addr != group)
13824 				continue;
13825 
13826 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13827 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13828 			    match_flags, 0, ipst, NULL);
13829 		}
13830 		/* No interface route exists for the gateway; skip this ire. */
13831 		if (ire_gw == NULL)
13832 			continue;
13833 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13834 			ire_refrele(ire_gw);
13835 			continue;
13836 		}
13837 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13838 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13839 
13840 		/*
13841 		 * The operation is considered a success if
13842 		 * it succeeds at least once on any one interface.
13843 		 */
13844 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13845 		    fmode, v6src);
13846 		if (error == 0)
13847 			result = CGTP_MCAST_SUCCESS;
13848 
13849 		ire_refrele(ire_gw);
13850 	}
13851 	irb_refrele(irb);
13852 	/*
13853 	 * Consider the call as successful if we succeeded on at least
13854 	 * one interface. Otherwise, return the last encountered error.
13855 	 */
13856 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13857 }
13858 
13859 /*
13860  * Get the CGTP (multirouting) filtering status.
13861  * If 0, the CGTP hooks are transparent.
13862  */
13863 /* ARGSUSED */
13864 static int
13865 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
13866 {
13867 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
13868 
13869 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
13870 	return (0);
13871 }
13872 
13873 /*
13874  * Set the CGTP (multirouting) filtering status.
13875  * If the status is changed from active to transparent
13876  * or from transparent to active, forward the new status
13877  * to the filtering module (if loaded).
13878  */
13879 /* ARGSUSED */
13880 static int
13881 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
13882     cred_t *ioc_cr)
13883 {
13884 	long		new_value;
13885 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
13886 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
13887 
13888 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
13889 		return (EPERM);
13890 
13891 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
13892 	    new_value < 0 || new_value > 1) {
13893 		return (EINVAL);
13894 	}
13895 
13896 	if ((!*ip_cgtp_filter_value) && new_value) {
13897 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
13898 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
13899 		    " (module not loaded)" : "");
13900 	}
13901 	if (*ip_cgtp_filter_value && (!new_value)) {
13902 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
13903 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
13904 		    " (module not loaded)" : "");
13905 	}
13906 
13907 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13908 		int	res;
13909 		netstackid_t stackid;
13910 
13911 		stackid = ipst->ips_netstack->netstack_stackid;
13912 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
13913 		    new_value);
13914 		if (res)
13915 			return (res);
13916 	}
13917 
13918 	*ip_cgtp_filter_value = (boolean_t)new_value;
13919 
13920 	ill_set_inputfn_all(ipst);
13921 	return (0);
13922 }
13923 
13924 /*
13925  * Return the expected CGTP hooks version number.
13926  */
13927 int
13928 ip_cgtp_filter_supported(void)
13929 {
13930 	return (ip_cgtp_filter_rev);
13931 }
13932 
13933 /*
13934  * CGTP hooks can be registered by invoking this function.
13935  * Checks that the version number matches.
13936  */
13937 int
13938 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13939 {
13940 	netstack_t *ns;
13941 	ip_stack_t *ipst;
13942 
13943 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13944 		return (ENOTSUP);
13945 
13946 	ns = netstack_find_by_stackid(stackid);
13947 	if (ns == NULL)
13948 		return (EINVAL);
13949 	ipst = ns->netstack_ip;
13950 	ASSERT(ipst != NULL);
13951 
13952 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13953 		netstack_rele(ns);
13954 		return (EALREADY);
13955 	}
13956 
13957 	ipst->ips_ip_cgtp_filter_ops = ops;
13958 
13959 	ill_set_inputfn_all(ipst);
13960 
13961 	netstack_rele(ns);
13962 	return (0);
13963 }
13964 
13965 /*
13966  * CGTP hooks can be unregistered by invoking this function.
13967  * Returns ENXIO if there was no registration.
13968  * Returns EBUSY if the ndd variable has not been turned off.
13969  */
13970 int
13971 ip_cgtp_filter_unregister(netstackid_t stackid)
13972 {
13973 	netstack_t *ns;
13974 	ip_stack_t *ipst;
13975 
13976 	ns = netstack_find_by_stackid(stackid);
13977 	if (ns == NULL)
13978 		return (EINVAL);
13979 	ipst = ns->netstack_ip;
13980 	ASSERT(ipst != NULL);
13981 
13982 	if (ipst->ips_ip_cgtp_filter) {
13983 		netstack_rele(ns);
13984 		return (EBUSY);
13985 	}
13986 
13987 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13988 		netstack_rele(ns);
13989 		return (ENXIO);
13990 	}
13991 	ipst->ips_ip_cgtp_filter_ops = NULL;
13992 
13993 	ill_set_inputfn_all(ipst);
13994 
13995 	netstack_rele(ns);
13996 	return (0);
13997 }
13998 
13999 /*
14000  * Check whether there is a CGTP filter registration.
14001  * Returns non-zero if there is a registration, otherwise returns zero.
14002  * Note: returns zero if bad stackid.
14003  */
14004 int
14005 ip_cgtp_filter_is_registered(netstackid_t stackid)
14006 {
14007 	netstack_t *ns;
14008 	ip_stack_t *ipst;
14009 	int ret;
14010 
14011 	ns = netstack_find_by_stackid(stackid);
14012 	if (ns == NULL)
14013 		return (0);
14014 	ipst = ns->netstack_ip;
14015 	ASSERT(ipst != NULL);
14016 
14017 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
14018 		ret = 1;
14019 	else
14020 		ret = 0;
14021 
14022 	netstack_rele(ns);
14023 	return (ret);
14024 }
14025 
14026 static int
14027 ip_squeue_switch(int val)
14028 {
14029 	int rval;
14030 
14031 	switch (val) {
14032 	case IP_SQUEUE_ENTER_NODRAIN:
14033 		rval = SQ_NODRAIN;
14034 		break;
14035 	case IP_SQUEUE_ENTER:
14036 		rval = SQ_PROCESS;
14037 		break;
14038 	case IP_SQUEUE_FILL:
14039 	default:
14040 		rval = SQ_FILL;
14041 		break;
14042 	}
14043 	return (rval);
14044 }
14045 
14046 /* ARGSUSED */
14047 static int
14048 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
14049     caddr_t addr, cred_t *cr)
14050 {
14051 	int *v = (int *)addr;
14052 	long new_value;
14053 
14054 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14055 		return (EPERM);
14056 
14057 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14058 		return (EINVAL);
14059 
14060 	ip_squeue_flag = ip_squeue_switch(new_value);
14061 	*v = new_value;
14062 	return (0);
14063 }
14064 
14065 /*
14066  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
14067  * ip_debug.
14068  */
14069 /* ARGSUSED */
14070 static int
14071 ip_int_set(queue_t *q, mblk_t *mp, char *value,
14072     caddr_t addr, cred_t *cr)
14073 {
14074 	int *v = (int *)addr;
14075 	long new_value;
14076 
14077 	if (secpolicy_net_config(cr, B_FALSE) != 0)
14078 		return (EPERM);
14079 
14080 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
14081 		return (EINVAL);
14082 
14083 	*v = new_value;
14084 	return (0);
14085 }
14086 
14087 static void *
14088 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
14089 {
14090 	kstat_t *ksp;
14091 
14092 	ip_stat_t template = {
14093 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
14094 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
14095 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
14096 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
14097 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
14098 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
14099 		{ "ip_opt",			KSTAT_DATA_UINT64 },
14100 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
14101 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
14102 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
14103 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
14104 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
14105 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
14106 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
14107 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
14108 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
14109 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14110 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
14111 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
14112 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14113 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14114 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
14115 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
14116 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
14117 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
14118 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
14119 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
14120 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
14121 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
14122 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
14123 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
14124 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
14125 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
14126 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
14127 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
14128 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
14129 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
14130 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
14131 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
14132 	};
14133 
14134 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
14135 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
14136 	    KSTAT_FLAG_VIRTUAL, stackid);
14137 
14138 	if (ksp == NULL)
14139 		return (NULL);
14140 
14141 	bcopy(&template, ip_statisticsp, sizeof (template));
14142 	ksp->ks_data = (void *)ip_statisticsp;
14143 	ksp->ks_private = (void *)(uintptr_t)stackid;
14144 
14145 	kstat_install(ksp);
14146 	return (ksp);
14147 }
14148 
14149 static void
14150 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
14151 {
14152 	if (ksp != NULL) {
14153 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14154 		kstat_delete_netstack(ksp, stackid);
14155 	}
14156 }
14157 
14158 static void *
14159 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
14160 {
14161 	kstat_t	*ksp;
14162 
14163 	ip_named_kstat_t template = {
14164 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
14165 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
14166 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
14167 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
14168 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
14169 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
14170 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
14171 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
14172 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
14173 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
14174 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
14175 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
14176 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
14177 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
14178 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
14179 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
14180 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
14181 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
14182 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
14183 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
14184 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
14185 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
14186 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
14187 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
14188 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
14189 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14190 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14191 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14192 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14193 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14194 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14195 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14196 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14197 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14198 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14199 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14200 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14201 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14202 	};
14203 
14204 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14205 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14206 	if (ksp == NULL || ksp->ks_data == NULL)
14207 		return (NULL);
14208 
14209 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14210 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14211 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
14212 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14213 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14214 
14215 	template.netToMediaEntrySize.value.i32 =
14216 	    sizeof (mib2_ipNetToMediaEntry_t);
14217 
14218 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14219 
14220 	bcopy(&template, ksp->ks_data, sizeof (template));
14221 	ksp->ks_update = ip_kstat_update;
14222 	ksp->ks_private = (void *)(uintptr_t)stackid;
14223 
14224 	kstat_install(ksp);
14225 	return (ksp);
14226 }
14227 
14228 static void
14229 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14230 {
14231 	if (ksp != NULL) {
14232 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14233 		kstat_delete_netstack(ksp, stackid);
14234 	}
14235 }
14236 
14237 static int
14238 ip_kstat_update(kstat_t *kp, int rw)
14239 {
14240 	ip_named_kstat_t *ipkp;
14241 	mib2_ipIfStatsEntry_t ipmib;
14242 	ill_walk_context_t ctx;
14243 	ill_t *ill;
14244 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14245 	netstack_t	*ns;
14246 	ip_stack_t	*ipst;
14247 
14248 	if (kp == NULL || kp->ks_data == NULL)
14249 		return (EIO);
14250 
14251 	if (rw == KSTAT_WRITE)
14252 		return (EACCES);
14253 
14254 	ns = netstack_find_by_stackid(stackid);
14255 	if (ns == NULL)
14256 		return (-1);
14257 	ipst = ns->netstack_ip;
14258 	if (ipst == NULL) {
14259 		netstack_rele(ns);
14260 		return (-1);
14261 	}
14262 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14263 
14264 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14265 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14266 	ill = ILL_START_WALK_V4(&ctx, ipst);
14267 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14268 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14269 	rw_exit(&ipst->ips_ill_g_lock);
14270 
14271 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14272 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14273 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14274 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14275 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14276 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14277 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14278 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14279 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14280 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14281 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14282 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14283 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
14284 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14285 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14286 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14287 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14288 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14289 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14290 
14291 	ipkp->routingDiscards.value.ui32 =	0;
14292 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14293 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14294 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14295 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14296 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14297 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14298 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14299 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14300 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14301 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14302 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14303 
14304 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14305 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14306 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14307 
14308 	netstack_rele(ns);
14309 
14310 	return (0);
14311 }
14312 
14313 static void *
14314 icmp_kstat_init(netstackid_t stackid)
14315 {
14316 	kstat_t	*ksp;
14317 
14318 	icmp_named_kstat_t template = {
14319 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14320 		{ "inErrors",		KSTAT_DATA_UINT32 },
14321 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14322 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14323 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14324 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14325 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14326 		{ "inEchos",		KSTAT_DATA_UINT32 },
14327 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14328 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14329 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14330 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14331 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14332 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14333 		{ "outErrors",		KSTAT_DATA_UINT32 },
14334 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14335 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14336 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14337 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14338 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14339 		{ "outEchos",		KSTAT_DATA_UINT32 },
14340 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14341 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14342 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14343 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14344 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14345 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14346 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14347 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14348 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14349 		{ "outDrops",		KSTAT_DATA_UINT32 },
14350 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14351 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14352 	};
14353 
14354 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14355 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14356 	if (ksp == NULL || ksp->ks_data == NULL)
14357 		return (NULL);
14358 
14359 	bcopy(&template, ksp->ks_data, sizeof (template));
14360 
14361 	ksp->ks_update = icmp_kstat_update;
14362 	ksp->ks_private = (void *)(uintptr_t)stackid;
14363 
14364 	kstat_install(ksp);
14365 	return (ksp);
14366 }
14367 
14368 static void
14369 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14370 {
14371 	if (ksp != NULL) {
14372 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14373 		kstat_delete_netstack(ksp, stackid);
14374 	}
14375 }
14376 
14377 static int
14378 icmp_kstat_update(kstat_t *kp, int rw)
14379 {
14380 	icmp_named_kstat_t *icmpkp;
14381 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14382 	netstack_t	*ns;
14383 	ip_stack_t	*ipst;
14384 
14385 	if ((kp == NULL) || (kp->ks_data == NULL))
14386 		return (EIO);
14387 
14388 	if (rw == KSTAT_WRITE)
14389 		return (EACCES);
14390 
14391 	ns = netstack_find_by_stackid(stackid);
14392 	if (ns == NULL)
14393 		return (-1);
14394 	ipst = ns->netstack_ip;
14395 	if (ipst == NULL) {
14396 		netstack_rele(ns);
14397 		return (-1);
14398 	}
14399 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14400 
14401 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14402 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14403 	icmpkp->inDestUnreachs.value.ui32 =
14404 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14405 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14406 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14407 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14408 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14409 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14410 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14411 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14412 	icmpkp->inTimestampReps.value.ui32 =
14413 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14414 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14415 	icmpkp->inAddrMaskReps.value.ui32 =
14416 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14417 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14418 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14419 	icmpkp->outDestUnreachs.value.ui32 =
14420 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14421 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14422 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14423 	icmpkp->outSrcQuenchs.value.ui32 =
14424 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14425 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14426 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14427 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14428 	icmpkp->outTimestamps.value.ui32 =
14429 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14430 	icmpkp->outTimestampReps.value.ui32 =
14431 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14432 	icmpkp->outAddrMasks.value.ui32 =
14433 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14434 	icmpkp->outAddrMaskReps.value.ui32 =
14435 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14436 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14437 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14438 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14439 	icmpkp->outFragNeeded.value.ui32 =
14440 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14441 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14442 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14443 	icmpkp->inBadRedirects.value.ui32 =
14444 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14445 
14446 	netstack_rele(ns);
14447 	return (0);
14448 }
14449 
14450 /*
14451  * This is the fanout function for raw socket opened for SCTP.  Note
14452  * that it is called after SCTP checks that there is no socket which
14453  * wants a packet.  Then before SCTP handles this out of the blue packet,
14454  * this function is called to see if there is any raw socket for SCTP.
14455  * If there is and it is bound to the correct address, the packet will
14456  * be sent to that socket.  Note that only one raw socket can be bound to
14457  * a port.  This is assured in ipcl_sctp_hash_insert();
14458  */
14459 void
14460 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14461     ip_recv_attr_t *ira)
14462 {
14463 	conn_t		*connp;
14464 	queue_t		*rq;
14465 	boolean_t	secure;
14466 	ill_t		*ill = ira->ira_ill;
14467 	ip_stack_t	*ipst = ill->ill_ipst;
14468 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14469 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14470 	iaflags_t	iraflags = ira->ira_flags;
14471 	ill_t		*rill = ira->ira_rill;
14472 
14473 	secure = iraflags & IRAF_IPSEC_SECURE;
14474 
14475 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14476 	    ira, ipst);
14477 	if (connp == NULL) {
14478 		/*
14479 		 * Although raw sctp is not summed, OOB chunks must be.
14480 		 * Drop the packet here if the sctp checksum failed.
14481 		 */
14482 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14483 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
14484 			freemsg(mp);
14485 			return;
14486 		}
14487 		ira->ira_ill = ira->ira_rill = NULL;
14488 		sctp_ootb_input(mp, ira, ipst);
14489 		ira->ira_ill = ill;
14490 		ira->ira_rill = rill;
14491 		return;
14492 	}
14493 	rq = connp->conn_rq;
14494 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14495 		CONN_DEC_REF(connp);
14496 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14497 		freemsg(mp);
14498 		return;
14499 	}
14500 	if (((iraflags & IRAF_IS_IPV4) ?
14501 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14502 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14503 	    secure) {
14504 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14505 		    ip6h, ira);
14506 		if (mp == NULL) {
14507 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14508 			/* Note that mp is NULL */
14509 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14510 			CONN_DEC_REF(connp);
14511 			return;
14512 		}
14513 	}
14514 
14515 	if (iraflags & IRAF_ICMP_ERROR) {
14516 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14517 	} else {
14518 		ill_t *rill = ira->ira_rill;
14519 
14520 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14521 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14522 		ira->ira_ill = ira->ira_rill = NULL;
14523 		(connp->conn_recv)(connp, mp, NULL, ira);
14524 		ira->ira_ill = ill;
14525 		ira->ira_rill = rill;
14526 	}
14527 	CONN_DEC_REF(connp);
14528 }
14529 
14530 /*
14531  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14532  * header before the ip payload.
14533  */
14534 static void
14535 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14536 {
14537 	int len = (mp->b_wptr - mp->b_rptr);
14538 	mblk_t *ip_mp;
14539 
14540 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14541 	if (is_fp_mp || len != fp_mp_len) {
14542 		if (len > fp_mp_len) {
14543 			/*
14544 			 * fastpath header and ip header in the first mblk
14545 			 */
14546 			mp->b_rptr += fp_mp_len;
14547 		} else {
14548 			/*
14549 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14550 			 * attach the fastpath header before ip header.
14551 			 */
14552 			ip_mp = mp->b_cont;
14553 			freeb(mp);
14554 			mp = ip_mp;
14555 			mp->b_rptr += (fp_mp_len - len);
14556 		}
14557 	} else {
14558 		ip_mp = mp->b_cont;
14559 		freeb(mp);
14560 		mp = ip_mp;
14561 	}
14562 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14563 	freemsg(mp);
14564 }
14565 
14566 /*
14567  * Normal post fragmentation function.
14568  *
14569  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14570  * using the same state machine.
14571  *
14572  * We return an error on failure. In particular we return EWOULDBLOCK
14573  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14574  * (currently by canputnext failure resulting in backenabling from GLD.)
14575  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14576  * indication that they can flow control until ip_wsrv() tells then to restart.
14577  *
14578  * If the nce passed by caller is incomplete, this function
14579  * queues the packet and if necessary, sends ARP request and bails.
14580  * If the Neighbor Cache passed is fully resolved, we simply prepend
14581  * the link-layer header to the packet, do ipsec hw acceleration
14582  * work if necessary, and send the packet out on the wire.
14583  */
14584 /* ARGSUSED6 */
14585 int
14586 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14587     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14588 {
14589 	queue_t		*wq;
14590 	ill_t		*ill = nce->nce_ill;
14591 	ip_stack_t	*ipst = ill->ill_ipst;
14592 	uint64_t	delta;
14593 	boolean_t	isv6 = ill->ill_isv6;
14594 	boolean_t	fp_mp;
14595 	ncec_t		*ncec = nce->nce_common;
14596 
14597 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14598 
14599 	ASSERT(mp != NULL);
14600 	ASSERT(mp->b_datap->db_type == M_DATA);
14601 	ASSERT(pkt_len == msgdsize(mp));
14602 
14603 	/*
14604 	 * If we have already been here and are coming back after ARP/ND.
14605 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14606 	 * in that case since they have seen the packet when it came here
14607 	 * the first time.
14608 	 */
14609 	if (ixaflags & IXAF_NO_TRACE)
14610 		goto sendit;
14611 
14612 	if (ixaflags & IXAF_IS_IPV4) {
14613 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14614 
14615 		ASSERT(!isv6);
14616 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14617 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14618 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14619 			int	error;
14620 
14621 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14622 			    ipst->ips_ipv4firewall_physical_out,
14623 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14624 			DTRACE_PROBE1(ip4__physical__out__end,
14625 			    mblk_t *, mp);
14626 			if (mp == NULL)
14627 				return (error);
14628 
14629 			/* The length could have changed */
14630 			pkt_len = msgdsize(mp);
14631 		}
14632 		if (ipst->ips_ip4_observe.he_interested) {
14633 			/*
14634 			 * Note that for TX the zoneid is the sending
14635 			 * zone, whether or not MLP is in play.
14636 			 * Since the szone argument is the IP zoneid (i.e.,
14637 			 * zero for exclusive-IP zones) and ipobs wants
14638 			 * the system zoneid, we map it here.
14639 			 */
14640 			szone = IP_REAL_ZONEID(szone, ipst);
14641 
14642 			/*
14643 			 * On the outbound path the destination zone will be
14644 			 * unknown as we're sending this packet out on the
14645 			 * wire.
14646 			 */
14647 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14648 			    ill, ipst);
14649 		}
14650 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14651 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14652 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14653 	} else {
14654 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14655 
14656 		ASSERT(isv6);
14657 		ASSERT(pkt_len ==
14658 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14659 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14660 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14661 			int	error;
14662 
14663 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14664 			    ipst->ips_ipv6firewall_physical_out,
14665 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14666 			DTRACE_PROBE1(ip6__physical__out__end,
14667 			    mblk_t *, mp);
14668 			if (mp == NULL)
14669 				return (error);
14670 
14671 			/* The length could have changed */
14672 			pkt_len = msgdsize(mp);
14673 		}
14674 		if (ipst->ips_ip6_observe.he_interested) {
14675 			/* See above */
14676 			szone = IP_REAL_ZONEID(szone, ipst);
14677 
14678 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14679 			    ill, ipst);
14680 		}
14681 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14682 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14683 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14684 	}
14685 
14686 sendit:
14687 	/*
14688 	 * We check the state without a lock because the state can never
14689 	 * move "backwards" to initial or incomplete.
14690 	 */
14691 	switch (ncec->ncec_state) {
14692 	case ND_REACHABLE:
14693 	case ND_STALE:
14694 	case ND_DELAY:
14695 	case ND_PROBE:
14696 		mp = ip_xmit_attach_llhdr(mp, nce);
14697 		if (mp == NULL) {
14698 			/*
14699 			 * ip_xmit_attach_llhdr has increased
14700 			 * ipIfStatsOutDiscards and called ip_drop_output()
14701 			 */
14702 			return (ENOBUFS);
14703 		}
14704 		/*
14705 		 * check if nce_fastpath completed and we tagged on a
14706 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14707 		 */
14708 		fp_mp = (mp->b_datap->db_type == M_DATA);
14709 
14710 		if (fp_mp &&
14711 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14712 			ill_dld_direct_t *idd;
14713 
14714 			idd = &ill->ill_dld_capab->idc_direct;
14715 			/*
14716 			 * Send the packet directly to DLD, where it
14717 			 * may be queued depending on the availability
14718 			 * of transmit resources at the media layer.
14719 			 * Return value should be taken into
14720 			 * account and flow control the TCP.
14721 			 */
14722 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14723 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14724 			    pkt_len);
14725 
14726 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14727 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14728 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14729 			} else {
14730 				uintptr_t cookie;
14731 
14732 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14733 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14734 					if (ixacookie != NULL)
14735 						*ixacookie = cookie;
14736 					return (EWOULDBLOCK);
14737 				}
14738 			}
14739 		} else {
14740 			wq = ill->ill_wq;
14741 
14742 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14743 			    !canputnext(wq)) {
14744 				if (ixacookie != NULL)
14745 					*ixacookie = 0;
14746 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14747 				    nce->nce_fp_mp != NULL ?
14748 				    MBLKL(nce->nce_fp_mp) : 0);
14749 				return (EWOULDBLOCK);
14750 			}
14751 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14752 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14753 			    pkt_len);
14754 			putnext(wq, mp);
14755 		}
14756 
14757 		/*
14758 		 * The rest of this function implements Neighbor Unreachability
14759 		 * detection. Determine if the ncec is eligible for NUD.
14760 		 */
14761 		if (ncec->ncec_flags & NCE_F_NONUD)
14762 			return (0);
14763 
14764 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14765 
14766 		/*
14767 		 * Check for upper layer advice
14768 		 */
14769 		if (ixaflags & IXAF_REACH_CONF) {
14770 			timeout_id_t tid;
14771 
14772 			/*
14773 			 * It should be o.k. to check the state without
14774 			 * a lock here, at most we lose an advice.
14775 			 */
14776 			ncec->ncec_last = TICK_TO_MSEC(ddi_get_lbolt64());
14777 			if (ncec->ncec_state != ND_REACHABLE) {
14778 				mutex_enter(&ncec->ncec_lock);
14779 				ncec->ncec_state = ND_REACHABLE;
14780 				tid = ncec->ncec_timeout_id;
14781 				ncec->ncec_timeout_id = 0;
14782 				mutex_exit(&ncec->ncec_lock);
14783 				(void) untimeout(tid);
14784 				if (ip_debug > 2) {
14785 					/* ip1dbg */
14786 					pr_addr_dbg("ip_xmit: state"
14787 					    " for %s changed to"
14788 					    " REACHABLE\n", AF_INET6,
14789 					    &ncec->ncec_addr);
14790 				}
14791 			}
14792 			return (0);
14793 		}
14794 
14795 		delta =  TICK_TO_MSEC(ddi_get_lbolt64()) - ncec->ncec_last;
14796 		ip1dbg(("ip_xmit: delta = %" PRId64
14797 		    " ill_reachable_time = %d \n", delta,
14798 		    ill->ill_reachable_time));
14799 		if (delta > (uint64_t)ill->ill_reachable_time) {
14800 			mutex_enter(&ncec->ncec_lock);
14801 			switch (ncec->ncec_state) {
14802 			case ND_REACHABLE:
14803 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14804 				/* FALLTHROUGH */
14805 			case ND_STALE:
14806 				/*
14807 				 * ND_REACHABLE is identical to
14808 				 * ND_STALE in this specific case. If
14809 				 * reachable time has expired for this
14810 				 * neighbor (delta is greater than
14811 				 * reachable time), conceptually, the
14812 				 * neighbor cache is no longer in
14813 				 * REACHABLE state, but already in
14814 				 * STALE state.  So the correct
14815 				 * transition here is to ND_DELAY.
14816 				 */
14817 				ncec->ncec_state = ND_DELAY;
14818 				mutex_exit(&ncec->ncec_lock);
14819 				nce_restart_timer(ncec,
14820 				    ipst->ips_delay_first_probe_time);
14821 				if (ip_debug > 3) {
14822 					/* ip2dbg */
14823 					pr_addr_dbg("ip_xmit: state"
14824 					    " for %s changed to"
14825 					    " DELAY\n", AF_INET6,
14826 					    &ncec->ncec_addr);
14827 				}
14828 				break;
14829 			case ND_DELAY:
14830 			case ND_PROBE:
14831 				mutex_exit(&ncec->ncec_lock);
14832 				/* Timers have already started */
14833 				break;
14834 			case ND_UNREACHABLE:
14835 				/*
14836 				 * nce_timer has detected that this ncec
14837 				 * is unreachable and initiated deleting
14838 				 * this ncec.
14839 				 * This is a harmless race where we found the
14840 				 * ncec before it was deleted and have
14841 				 * just sent out a packet using this
14842 				 * unreachable ncec.
14843 				 */
14844 				mutex_exit(&ncec->ncec_lock);
14845 				break;
14846 			default:
14847 				ASSERT(0);
14848 				mutex_exit(&ncec->ncec_lock);
14849 			}
14850 		}
14851 		return (0);
14852 
14853 	case ND_INCOMPLETE:
14854 		/*
14855 		 * the state could have changed since we didn't hold the lock.
14856 		 * Re-verify state under lock.
14857 		 */
14858 		mutex_enter(&ncec->ncec_lock);
14859 		if (NCE_ISREACHABLE(ncec)) {
14860 			mutex_exit(&ncec->ncec_lock);
14861 			goto sendit;
14862 		}
14863 		/* queue the packet */
14864 		nce_queue_mp(ncec, mp, ipmp_packet_is_probe(mp, nce->nce_ill));
14865 		mutex_exit(&ncec->ncec_lock);
14866 		DTRACE_PROBE2(ip__xmit__incomplete,
14867 		    (ncec_t *), ncec, (mblk_t *), mp);
14868 		return (0);
14869 
14870 	case ND_INITIAL:
14871 		/*
14872 		 * State could have changed since we didn't hold the lock, so
14873 		 * re-verify state.
14874 		 */
14875 		mutex_enter(&ncec->ncec_lock);
14876 		if (NCE_ISREACHABLE(ncec))  {
14877 			mutex_exit(&ncec->ncec_lock);
14878 			goto sendit;
14879 		}
14880 		nce_queue_mp(ncec, mp, ipmp_packet_is_probe(mp, nce->nce_ill));
14881 		if (ncec->ncec_state == ND_INITIAL) {
14882 			ncec->ncec_state = ND_INCOMPLETE;
14883 			mutex_exit(&ncec->ncec_lock);
14884 			/*
14885 			 * figure out the source we want to use
14886 			 * and resolve it.
14887 			 */
14888 			ip_ndp_resolve(ncec);
14889 		} else  {
14890 			mutex_exit(&ncec->ncec_lock);
14891 		}
14892 		return (0);
14893 
14894 	case ND_UNREACHABLE:
14895 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14896 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14897 		    mp, ill);
14898 		freemsg(mp);
14899 		return (0);
14900 
14901 	default:
14902 		ASSERT(0);
14903 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14904 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14905 		    mp, ill);
14906 		freemsg(mp);
14907 		return (ENETUNREACH);
14908 	}
14909 }
14910 
14911 /*
14912  * Return B_TRUE if the buffers differ in length or content.
14913  * This is used for comparing extension header buffers.
14914  * Note that an extension header would be declared different
14915  * even if all that changed was the next header value in that header i.e.
14916  * what really changed is the next extension header.
14917  */
14918 boolean_t
14919 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14920     uint_t blen)
14921 {
14922 	if (!b_valid)
14923 		blen = 0;
14924 
14925 	if (alen != blen)
14926 		return (B_TRUE);
14927 	if (alen == 0)
14928 		return (B_FALSE);	/* Both zero length */
14929 	return (bcmp(abuf, bbuf, alen));
14930 }
14931 
14932 /*
14933  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14934  * Return B_FALSE if memory allocation fails - don't change any state!
14935  */
14936 boolean_t
14937 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14938     const void *src, uint_t srclen)
14939 {
14940 	void *dst;
14941 
14942 	if (!src_valid)
14943 		srclen = 0;
14944 
14945 	ASSERT(*dstlenp == 0);
14946 	if (src != NULL && srclen != 0) {
14947 		dst = mi_alloc(srclen, BPRI_MED);
14948 		if (dst == NULL)
14949 			return (B_FALSE);
14950 	} else {
14951 		dst = NULL;
14952 	}
14953 	if (*dstp != NULL)
14954 		mi_free(*dstp);
14955 	*dstp = dst;
14956 	*dstlenp = dst == NULL ? 0 : srclen;
14957 	return (B_TRUE);
14958 }
14959 
14960 /*
14961  * Replace what is in *dst, *dstlen with the source.
14962  * Assumes ip_allocbuf has already been called.
14963  */
14964 void
14965 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14966     const void *src, uint_t srclen)
14967 {
14968 	if (!src_valid)
14969 		srclen = 0;
14970 
14971 	ASSERT(*dstlenp == srclen);
14972 	if (src != NULL && srclen != 0)
14973 		bcopy(src, *dstp, srclen);
14974 }
14975 
14976 /*
14977  * Free the storage pointed to by the members of an ip_pkt_t.
14978  */
14979 void
14980 ip_pkt_free(ip_pkt_t *ipp)
14981 {
14982 	uint_t	fields = ipp->ipp_fields;
14983 
14984 	if (fields & IPPF_HOPOPTS) {
14985 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14986 		ipp->ipp_hopopts = NULL;
14987 		ipp->ipp_hopoptslen = 0;
14988 	}
14989 	if (fields & IPPF_RTHDRDSTOPTS) {
14990 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14991 		ipp->ipp_rthdrdstopts = NULL;
14992 		ipp->ipp_rthdrdstoptslen = 0;
14993 	}
14994 	if (fields & IPPF_DSTOPTS) {
14995 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14996 		ipp->ipp_dstopts = NULL;
14997 		ipp->ipp_dstoptslen = 0;
14998 	}
14999 	if (fields & IPPF_RTHDR) {
15000 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15001 		ipp->ipp_rthdr = NULL;
15002 		ipp->ipp_rthdrlen = 0;
15003 	}
15004 	if (fields & IPPF_IPV4_OPTIONS) {
15005 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
15006 		ipp->ipp_ipv4_options = NULL;
15007 		ipp->ipp_ipv4_options_len = 0;
15008 	}
15009 	if (fields & IPPF_LABEL_V4) {
15010 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
15011 		ipp->ipp_label_v4 = NULL;
15012 		ipp->ipp_label_len_v4 = 0;
15013 	}
15014 	if (fields & IPPF_LABEL_V6) {
15015 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
15016 		ipp->ipp_label_v6 = NULL;
15017 		ipp->ipp_label_len_v6 = 0;
15018 	}
15019 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15020 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15021 }
15022 
15023 /*
15024  * Copy from src to dst and allocate as needed.
15025  * Returns zero or ENOMEM.
15026  *
15027  * The caller must initialize dst to zero.
15028  */
15029 int
15030 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
15031 {
15032 	uint_t	fields = src->ipp_fields;
15033 
15034 	/* Start with fields that don't require memory allocation */
15035 	dst->ipp_fields = fields &
15036 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
15037 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
15038 
15039 	dst->ipp_addr = src->ipp_addr;
15040 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
15041 	dst->ipp_hoplimit = src->ipp_hoplimit;
15042 	dst->ipp_tclass = src->ipp_tclass;
15043 	dst->ipp_type_of_service = src->ipp_type_of_service;
15044 
15045 	if (fields & IPPF_HOPOPTS) {
15046 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
15047 		if (dst->ipp_hopopts == NULL) {
15048 			ip_pkt_free(dst);
15049 			return (ENOMEM);
15050 		}
15051 		dst->ipp_fields |= IPPF_HOPOPTS;
15052 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
15053 		    src->ipp_hopoptslen);
15054 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
15055 	}
15056 	if (fields & IPPF_RTHDRDSTOPTS) {
15057 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
15058 		    kmflag);
15059 		if (dst->ipp_rthdrdstopts == NULL) {
15060 			ip_pkt_free(dst);
15061 			return (ENOMEM);
15062 		}
15063 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
15064 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
15065 		    src->ipp_rthdrdstoptslen);
15066 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
15067 	}
15068 	if (fields & IPPF_DSTOPTS) {
15069 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
15070 		if (dst->ipp_dstopts == NULL) {
15071 			ip_pkt_free(dst);
15072 			return (ENOMEM);
15073 		}
15074 		dst->ipp_fields |= IPPF_DSTOPTS;
15075 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
15076 		    src->ipp_dstoptslen);
15077 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
15078 	}
15079 	if (fields & IPPF_RTHDR) {
15080 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
15081 		if (dst->ipp_rthdr == NULL) {
15082 			ip_pkt_free(dst);
15083 			return (ENOMEM);
15084 		}
15085 		dst->ipp_fields |= IPPF_RTHDR;
15086 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
15087 		    src->ipp_rthdrlen);
15088 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
15089 	}
15090 	if (fields & IPPF_IPV4_OPTIONS) {
15091 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
15092 		    kmflag);
15093 		if (dst->ipp_ipv4_options == NULL) {
15094 			ip_pkt_free(dst);
15095 			return (ENOMEM);
15096 		}
15097 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
15098 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
15099 		    src->ipp_ipv4_options_len);
15100 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
15101 	}
15102 	if (fields & IPPF_LABEL_V4) {
15103 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
15104 		if (dst->ipp_label_v4 == NULL) {
15105 			ip_pkt_free(dst);
15106 			return (ENOMEM);
15107 		}
15108 		dst->ipp_fields |= IPPF_LABEL_V4;
15109 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
15110 		    src->ipp_label_len_v4);
15111 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
15112 	}
15113 	if (fields & IPPF_LABEL_V6) {
15114 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
15115 		if (dst->ipp_label_v6 == NULL) {
15116 			ip_pkt_free(dst);
15117 			return (ENOMEM);
15118 		}
15119 		dst->ipp_fields |= IPPF_LABEL_V6;
15120 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
15121 		    src->ipp_label_len_v6);
15122 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
15123 	}
15124 	if (fields & IPPF_FRAGHDR) {
15125 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
15126 		if (dst->ipp_fraghdr == NULL) {
15127 			ip_pkt_free(dst);
15128 			return (ENOMEM);
15129 		}
15130 		dst->ipp_fields |= IPPF_FRAGHDR;
15131 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
15132 		    src->ipp_fraghdrlen);
15133 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
15134 	}
15135 	return (0);
15136 }
15137 
15138 /*
15139  * Returns INADDR_ANY if no source route
15140  */
15141 ipaddr_t
15142 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
15143 {
15144 	ipaddr_t	nexthop = INADDR_ANY;
15145 	ipoptp_t	opts;
15146 	uchar_t		*opt;
15147 	uint8_t		optval;
15148 	uint8_t		optlen;
15149 	uint32_t	totallen;
15150 
15151 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15152 		return (INADDR_ANY);
15153 
15154 	totallen = ipp->ipp_ipv4_options_len;
15155 	if (totallen & 0x3)
15156 		return (INADDR_ANY);
15157 
15158 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15159 	    optval != IPOPT_EOL;
15160 	    optval = ipoptp_next(&opts)) {
15161 		opt = opts.ipoptp_cur;
15162 		switch (optval) {
15163 			uint8_t off;
15164 		case IPOPT_SSRR:
15165 		case IPOPT_LSRR:
15166 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15167 				break;
15168 			}
15169 			optlen = opts.ipoptp_len;
15170 			off = opt[IPOPT_OFFSET];
15171 			off--;
15172 			if (optlen < IP_ADDR_LEN ||
15173 			    off > optlen - IP_ADDR_LEN) {
15174 				/* End of source route */
15175 				break;
15176 			}
15177 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15178 			if (nexthop == htonl(INADDR_LOOPBACK)) {
15179 				/* Ignore */
15180 				nexthop = INADDR_ANY;
15181 				break;
15182 			}
15183 			break;
15184 		}
15185 	}
15186 	return (nexthop);
15187 }
15188 
15189 /*
15190  * Reverse a source route.
15191  */
15192 void
15193 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15194 {
15195 	ipaddr_t	tmp;
15196 	ipoptp_t	opts;
15197 	uchar_t		*opt;
15198 	uint8_t		optval;
15199 	uint32_t	totallen;
15200 
15201 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15202 		return;
15203 
15204 	totallen = ipp->ipp_ipv4_options_len;
15205 	if (totallen & 0x3)
15206 		return;
15207 
15208 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15209 	    optval != IPOPT_EOL;
15210 	    optval = ipoptp_next(&opts)) {
15211 		uint8_t off1, off2;
15212 
15213 		opt = opts.ipoptp_cur;
15214 		switch (optval) {
15215 		case IPOPT_SSRR:
15216 		case IPOPT_LSRR:
15217 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15218 				break;
15219 			}
15220 			off1 = IPOPT_MINOFF_SR - 1;
15221 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15222 			while (off2 > off1) {
15223 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15224 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15225 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15226 				off2 -= IP_ADDR_LEN;
15227 				off1 += IP_ADDR_LEN;
15228 			}
15229 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15230 			break;
15231 		}
15232 	}
15233 }
15234 
15235 /*
15236  * Returns NULL if no routing header
15237  */
15238 in6_addr_t *
15239 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15240 {
15241 	in6_addr_t	*nexthop = NULL;
15242 	ip6_rthdr0_t	*rthdr;
15243 
15244 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15245 		return (NULL);
15246 
15247 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15248 	if (rthdr->ip6r0_segleft == 0)
15249 		return (NULL);
15250 
15251 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15252 	return (nexthop);
15253 }
15254 
15255 zoneid_t
15256 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15257     zoneid_t lookup_zoneid)
15258 {
15259 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15260 	ire_t		*ire;
15261 	int		ire_flags = MATCH_IRE_TYPE;
15262 	zoneid_t	zoneid = ALL_ZONES;
15263 
15264 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15265 		return (ALL_ZONES);
15266 
15267 	if (lookup_zoneid != ALL_ZONES)
15268 		ire_flags |= MATCH_IRE_ZONEONLY;
15269 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15270 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15271 	if (ire != NULL) {
15272 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15273 		ire_refrele(ire);
15274 	}
15275 	return (zoneid);
15276 }
15277 
15278 zoneid_t
15279 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15280     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15281 {
15282 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15283 	ire_t		*ire;
15284 	int		ire_flags = MATCH_IRE_TYPE;
15285 	zoneid_t	zoneid = ALL_ZONES;
15286 
15287 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15288 		return (ALL_ZONES);
15289 
15290 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15291 		ire_flags |= MATCH_IRE_ILL;
15292 
15293 	if (lookup_zoneid != ALL_ZONES)
15294 		ire_flags |= MATCH_IRE_ZONEONLY;
15295 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15296 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15297 	if (ire != NULL) {
15298 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15299 		ire_refrele(ire);
15300 	}
15301 	return (zoneid);
15302 }
15303 
15304 /*
15305  * IP obserability hook support functions.
15306  */
15307 static void
15308 ipobs_init(ip_stack_t *ipst)
15309 {
15310 	netid_t id;
15311 
15312 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15313 
15314 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15315 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15316 
15317 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15318 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15319 }
15320 
15321 static void
15322 ipobs_fini(ip_stack_t *ipst)
15323 {
15324 
15325 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15326 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15327 }
15328 
15329 /*
15330  * hook_pkt_observe_t is composed in network byte order so that the
15331  * entire mblk_t chain handed into hook_run can be used as-is.
15332  * The caveat is that use of the fields, such as the zone fields,
15333  * requires conversion into host byte order first.
15334  */
15335 void
15336 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15337     const ill_t *ill, ip_stack_t *ipst)
15338 {
15339 	hook_pkt_observe_t *hdr;
15340 	uint64_t grifindex;
15341 	mblk_t *imp;
15342 
15343 	imp = allocb(sizeof (*hdr), BPRI_HI);
15344 	if (imp == NULL)
15345 		return;
15346 
15347 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15348 	/*
15349 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15350 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15351 	 */
15352 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15353 	imp->b_cont = mp;
15354 
15355 	ASSERT(DB_TYPE(mp) == M_DATA);
15356 
15357 	if (IS_UNDER_IPMP(ill))
15358 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15359 	else
15360 		grifindex = 0;
15361 
15362 	hdr->hpo_version = 1;
15363 	hdr->hpo_htype = htype;
15364 	hdr->hpo_pktlen = htons((ushort_t)msgdsize(mp));
15365 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15366 	hdr->hpo_grifindex = htonl(grifindex);
15367 	hdr->hpo_zsrc = htonl(zsrc);
15368 	hdr->hpo_zdst = htonl(zdst);
15369 	hdr->hpo_pkt = imp;
15370 	hdr->hpo_ctx = ipst->ips_netstack;
15371 
15372 	if (ill->ill_isv6) {
15373 		hdr->hpo_family = AF_INET6;
15374 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15375 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15376 	} else {
15377 		hdr->hpo_family = AF_INET;
15378 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15379 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15380 	}
15381 
15382 	imp->b_cont = NULL;
15383 	freemsg(imp);
15384 }
15385 
15386 /*
15387  * Utility routine that checks if `v4srcp' is a valid address on underlying
15388  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15389  * associated with `v4srcp' on success.  NOTE: if this is not called from
15390  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15391  * group during or after this lookup.
15392  */
15393 boolean_t
15394 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15395 {
15396 	ipif_t *ipif;
15397 
15398 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15399 	if (ipif != NULL) {
15400 		if (ipifp != NULL)
15401 			*ipifp = ipif;
15402 		else
15403 			ipif_refrele(ipif);
15404 		return (B_TRUE);
15405 	}
15406 
15407 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15408 	    *v4srcp));
15409 	return (B_FALSE);
15410 }
15411