1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright (c) 1990 Mentat Inc.
  25  * Copyright (c) 2017 OmniTI Computer Consulting, Inc. All rights reserved.
  26  * Copyright (c) 2016 by Delphix. All rights reserved.
  27  * Copyright (c) 2019 Joyent, Inc. All rights reserved.
  28  */
  29 
  30 #include <sys/types.h>
  31 #include <sys/stream.h>
  32 #include <sys/dlpi.h>
  33 #include <sys/stropts.h>
  34 #include <sys/sysmacros.h>
  35 #include <sys/strsubr.h>
  36 #include <sys/strlog.h>
  37 #include <sys/strsun.h>
  38 #include <sys/zone.h>
  39 #define _SUN_TPI_VERSION 2
  40 #include <sys/tihdr.h>
  41 #include <sys/xti_inet.h>
  42 #include <sys/ddi.h>
  43 #include <sys/suntpi.h>
  44 #include <sys/cmn_err.h>
  45 #include <sys/debug.h>
  46 #include <sys/kobj.h>
  47 #include <sys/modctl.h>
  48 #include <sys/atomic.h>
  49 #include <sys/policy.h>
  50 #include <sys/priv.h>
  51 #include <sys/taskq.h>
  52 
  53 #include <sys/systm.h>
  54 #include <sys/param.h>
  55 #include <sys/kmem.h>
  56 #include <sys/sdt.h>
  57 #include <sys/socket.h>
  58 #include <sys/vtrace.h>
  59 #include <sys/isa_defs.h>
  60 #include <sys/mac.h>
  61 #include <net/if.h>
  62 #include <net/if_arp.h>
  63 #include <net/route.h>
  64 #include <sys/sockio.h>
  65 #include <netinet/in.h>
  66 #include <net/if_dl.h>
  67 
  68 #include <inet/common.h>
  69 #include <inet/mi.h>
  70 #include <inet/mib2.h>
  71 #include <inet/nd.h>
  72 #include <inet/arp.h>
  73 #include <inet/snmpcom.h>
  74 #include <inet/optcom.h>
  75 #include <inet/kstatcom.h>
  76 
  77 #include <netinet/igmp_var.h>
  78 #include <netinet/ip6.h>
  79 #include <netinet/icmp6.h>
  80 #include <netinet/sctp.h>
  81 
  82 #include <inet/ip.h>
  83 #include <inet/ip_impl.h>
  84 #include <inet/ip6.h>
  85 #include <inet/ip6_asp.h>
  86 #include <inet/tcp.h>
  87 #include <inet/tcp_impl.h>
  88 #include <inet/ip_multi.h>
  89 #include <inet/ip_if.h>
  90 #include <inet/ip_ire.h>
  91 #include <inet/ip_ftable.h>
  92 #include <inet/ip_rts.h>
  93 #include <inet/ip_ndp.h>
  94 #include <inet/ip_listutils.h>
  95 #include <netinet/igmp.h>
  96 #include <netinet/ip_mroute.h>
  97 #include <inet/ipp_common.h>
  98 #include <inet/cc.h>
  99 
 100 #include <net/pfkeyv2.h>
 101 #include <inet/sadb.h>
 102 #include <inet/ipsec_impl.h>
 103 #include <inet/iptun/iptun_impl.h>
 104 #include <inet/ipdrop.h>
 105 #include <inet/ip_netinfo.h>
 106 #include <inet/ilb_ip.h>
 107 
 108 #include <sys/ethernet.h>
 109 #include <net/if_types.h>
 110 #include <sys/cpuvar.h>
 111 
 112 #include <ipp/ipp.h>
 113 #include <ipp/ipp_impl.h>
 114 #include <ipp/ipgpc/ipgpc.h>
 115 
 116 #include <sys/pattr.h>
 117 #include <inet/ipclassifier.h>
 118 #include <inet/sctp_ip.h>
 119 #include <inet/sctp/sctp_impl.h>
 120 #include <inet/udp_impl.h>
 121 #include <inet/rawip_impl.h>
 122 #include <inet/rts_impl.h>
 123 
 124 #include <sys/tsol/label.h>
 125 #include <sys/tsol/tnet.h>
 126 
 127 #include <sys/squeue_impl.h>
 128 #include <inet/ip_arp.h>
 129 
 130 #include <sys/clock_impl.h>       /* For LBOLT_FASTPATH{,64} */
 131 
 132 /*
 133  * Values for squeue switch:
 134  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
 135  * IP_SQUEUE_ENTER: SQ_PROCESS
 136  * IP_SQUEUE_FILL: SQ_FILL
 137  */
 138 int ip_squeue_enter = IP_SQUEUE_ENTER;  /* Setable in /etc/system */
 139 
 140 int ip_squeue_flag;
 141 
 142 /*
 143  * Setable in /etc/system
 144  */
 145 int ip_poll_normal_ms = 100;
 146 int ip_poll_normal_ticks = 0;
 147 int ip_modclose_ackwait_ms = 3000;
 148 
 149 /*
 150  * It would be nice to have these present only in DEBUG systems, but the
 151  * current design of the global symbol checking logic requires them to be
 152  * unconditionally present.
 153  */
 154 uint_t ip_thread_data;                  /* TSD key for debug support */
 155 krwlock_t ip_thread_rwlock;
 156 list_t  ip_thread_list;
 157 
 158 /*
 159  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
 160  */
 161 
 162 struct listptr_s {
 163         mblk_t  *lp_head;       /* pointer to the head of the list */
 164         mblk_t  *lp_tail;       /* pointer to the tail of the list */
 165 };
 166 
 167 typedef struct listptr_s listptr_t;
 168 
 169 /*
 170  * This is used by ip_snmp_get_mib2_ip_route_media and
 171  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
 172  */
 173 typedef struct iproutedata_s {
 174         uint_t          ird_idx;
 175         uint_t          ird_flags;      /* see below */
 176         listptr_t       ird_route;      /* ipRouteEntryTable */
 177         listptr_t       ird_netmedia;   /* ipNetToMediaEntryTable */
 178         listptr_t       ird_attrs;      /* ipRouteAttributeTable */
 179 } iproutedata_t;
 180 
 181 /* Include ire_testhidden and IRE_IF_CLONE routes */
 182 #define IRD_REPORT_ALL  0x01
 183 
 184 /*
 185  * Cluster specific hooks. These should be NULL when booted as a non-cluster
 186  */
 187 
 188 /*
 189  * Hook functions to enable cluster networking
 190  * On non-clustered systems these vectors must always be NULL.
 191  *
 192  * Hook function to Check ip specified ip address is a shared ip address
 193  * in the cluster
 194  *
 195  */
 196 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
 197     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
 198 
 199 /*
 200  * Hook function to generate cluster wide ip fragment identifier
 201  */
 202 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
 203     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
 204     void *args) = NULL;
 205 
 206 /*
 207  * Hook function to generate cluster wide SPI.
 208  */
 209 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
 210     void *) = NULL;
 211 
 212 /*
 213  * Hook function to verify if the SPI is already utlized.
 214  */
 215 
 216 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
 217 
 218 /*
 219  * Hook function to delete the SPI from the cluster wide repository.
 220  */
 221 
 222 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
 223 
 224 /*
 225  * Hook function to inform the cluster when packet received on an IDLE SA
 226  */
 227 
 228 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
 229     in6_addr_t, in6_addr_t, void *) = NULL;
 230 
 231 /*
 232  * Synchronization notes:
 233  *
 234  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
 235  * MT level protection given by STREAMS. IP uses a combination of its own
 236  * internal serialization mechanism and standard Solaris locking techniques.
 237  * The internal serialization is per phyint.  This is used to serialize
 238  * plumbing operations, IPMP operations, most set ioctls, etc.
 239  *
 240  * Plumbing is a long sequence of operations involving message
 241  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
 242  * involved in plumbing operations. A natural model is to serialize these
 243  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
 244  * parallel without any interference. But various set ioctls on hme0 are best
 245  * serialized, along with IPMP operations and processing of DLPI control
 246  * messages received from drivers on a per phyint basis. This serialization is
 247  * provided by the ipsq_t and primitives operating on this. Details can
 248  * be found in ip_if.c above the core primitives operating on ipsq_t.
 249  *
 250  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
 251  * Simiarly lookup of an ire by a thread also returns a refheld ire.
 252  * In addition ipif's and ill's referenced by the ire are also indirectly
 253  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
 254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
 255  * address of an ipif has to go through the ipsq_t. This ensures that only
 256  * one such exclusive operation proceeds at any time on the ipif. It then
 257  * waits for all refcnts
 258  * associated with this ipif to come down to zero. The address is changed
 259  * only after the ipif has been quiesced. Then the ipif is brought up again.
 260  * More details are described above the comment in ip_sioctl_flags.
 261  *
 262  * Packet processing is based mostly on IREs and are fully multi-threaded
 263  * using standard Solaris MT techniques.
 264  *
 265  * There are explicit locks in IP to handle:
 266  * - The ip_g_head list maintained by mi_open_link() and friends.
 267  *
 268  * - The reassembly data structures (one lock per hash bucket)
 269  *
 270  * - conn_lock is meant to protect conn_t fields. The fields actually
 271  *   protected by conn_lock are documented in the conn_t definition.
 272  *
 273  * - ire_lock to protect some of the fields of the ire, IRE tables
 274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
 275  *
 276  * - ndp_g_lock and ncec_lock for protecting NCEs.
 277  *
 278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
 279  *
 280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
 281  *      * The AVL tree based global multi list of all ills.
 282  *      * The linked list of all ipifs of an ill
 283  *      * The <ipsq-xop> mapping
 284  *      * <ill-phyint> association
 285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
 286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
 287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
 288  *   writer for the actual duration of the insertion/deletion/change.
 289  *
 290  * - ill_lock:  This is a per ill mutex.
 291  *   It protects some members of the ill_t struct; see ip.h for details.
 292  *   It also protects the <ill-phyint> assoc.
 293  *   It also protects the list of ipifs hanging off the ill.
 294  *
 295  * - ipsq_lock: This is a per ipsq_t mutex lock.
 296  *   This protects some members of the ipsq_t struct; see ip.h for details.
 297  *   It also protects the <ipsq-ipxop> mapping
 298  *
 299  * - ipx_lock: This is a per ipxop_t mutex lock.
 300  *   This protects some members of the ipxop_t struct; see ip.h for details.
 301  *
 302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
 303  *   phyint_flags
 304  *
 305  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
 306  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
 307  *   uniqueness check also done atomically.
 308  *
 309  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
 310  *   group list linked by ill_usesrc_grp_next. It also protects the
 311  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
 312  *   group is being added or deleted.  This lock is taken as a reader when
 313  *   walking the list/group(eg: to get the number of members in a usesrc group).
 314  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
 315  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
 316  *   example, it is not necessary to take this lock in the initial portion
 317  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
 318  *   operations are executed exclusively and that ensures that the "usesrc
 319  *   group state" cannot change. The "usesrc group state" change can happen
 320  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
 321  *
 322  * Changing <ill-phyint>, <ipsq-xop> assocications:
 323  *
 324  * To change the <ill-phyint> association, the ill_g_lock must be held
 325  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
 326  * must be held.
 327  *
 328  * To change the <ipsq-xop> association, the ill_g_lock must be held as
 329  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
 330  * This is only done when ills are added or removed from IPMP groups.
 331  *
 332  * To add or delete an ipif from the list of ipifs hanging off the ill,
 333  * ill_g_lock (writer) and ill_lock must be held and the thread must be
 334  * a writer on the associated ipsq.
 335  *
 336  * To add or delete an ill to the system, the ill_g_lock must be held as
 337  * writer and the thread must be a writer on the associated ipsq.
 338  *
 339  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
 340  * must be a writer on the associated ipsq.
 341  *
 342  * Lock hierarchy
 343  *
 344  * Some lock hierarchy scenarios are listed below.
 345  *
 346  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
 347  * ill_g_lock -> ill_lock(s) -> phyint_lock
 348  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
 349  * ill_g_lock -> ip_addr_avail_lock
 350  * conn_lock -> irb_lock -> ill_lock -> ire_lock
 351  * ill_g_lock -> ip_g_nd_lock
 352  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
 353  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
 354  * arl_lock -> ill_lock
 355  * ips_ire_dep_lock -> irb_lock
 356  *
 357  * When more than 1 ill lock is needed to be held, all ill lock addresses
 358  * are sorted on address and locked starting from highest addressed lock
 359  * downward.
 360  *
 361  * Multicast scenarios
 362  * ips_ill_g_lock -> ill_mcast_lock
 363  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
 364  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
 365  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
 366  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
 367  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
 368  *
 369  * IPsec scenarios
 370  *
 371  * ipsa_lock -> ill_g_lock -> ill_lock
 372  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
 373  *
 374  * Trusted Solaris scenarios
 375  *
 376  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
 377  * igsa_lock -> gcdb_lock
 378  * gcgrp_rwlock -> ire_lock
 379  * gcgrp_rwlock -> gcdb_lock
 380  *
 381  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
 382  *
 383  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
 384  * sq_lock -> conn_lock -> QLOCK(q)
 385  * ill_lock -> ft_lock -> fe_lock
 386  *
 387  * Routing/forwarding table locking notes:
 388  *
 389  * Lock acquisition order: Radix tree lock, irb_lock.
 390  * Requirements:
 391  * i.  Walker must not hold any locks during the walker callback.
 392  * ii  Walker must not see a truncated tree during the walk because of any node
 393  *     deletion.
 394  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
 395  *     in many places in the code to walk the irb list. Thus even if all the
 396  *     ires in a bucket have been deleted, we still can't free the radix node
 397  *     until the ires have actually been inactive'd (freed).
 398  *
 399  * Tree traversal - Need to hold the global tree lock in read mode.
 400  * Before dropping the global tree lock, need to either increment the ire_refcnt
 401  * to ensure that the radix node can't be deleted.
 402  *
 403  * Tree add - Need to hold the global tree lock in write mode to add a
 404  * radix node. To prevent the node from being deleted, increment the
 405  * irb_refcnt, after the node is added to the tree. The ire itself is
 406  * added later while holding the irb_lock, but not the tree lock.
 407  *
 408  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
 409  * All associated ires must be inactive (i.e. freed), and irb_refcnt
 410  * must be zero.
 411  *
 412  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
 413  * global tree lock (read mode) for traversal.
 414  *
 415  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
 416  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
 417  *
 418  * IPsec notes :
 419  *
 420  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
 421  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
 422  * ip_xmit_attr_t has the
 423  * information used by the IPsec code for applying the right level of
 424  * protection. The information initialized by IP in the ip_xmit_attr_t
 425  * is determined by the per-socket policy or global policy in the system.
 426  * For inbound datagrams, the ip_recv_attr_t
 427  * starts out with nothing in it. It gets filled
 428  * with the right information if it goes through the AH/ESP code, which
 429  * happens if the incoming packet is secure. The information initialized
 430  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
 431  * the policy requirements needed by per-socket policy or global policy
 432  * is met or not.
 433  *
 434  * For fully connected sockets i.e dst, src [addr, port] is known,
 435  * conn_policy_cached is set indicating that policy has been cached.
 436  * conn_in_enforce_policy may or may not be set depending on whether
 437  * there is a global policy match or per-socket policy match.
 438  * Policy inheriting happpens in ip_policy_set once the destination is known.
 439  * Once the right policy is set on the conn_t, policy cannot change for
 440  * this socket. This makes life simpler for TCP (UDP ?) where
 441  * re-transmissions go out with the same policy. For symmetry, policy
 442  * is cached for fully connected UDP sockets also. Thus if policy is cached,
 443  * it also implies that policy is latched i.e policy cannot change
 444  * on these sockets. As we have the right policy on the conn, we don't
 445  * have to lookup global policy for every outbound and inbound datagram
 446  * and thus serving as an optimization. Note that a global policy change
 447  * does not affect fully connected sockets if they have policy. If fully
 448  * connected sockets did not have any policy associated with it, global
 449  * policy change may affect them.
 450  *
 451  * IP Flow control notes:
 452  * ---------------------
 453  * Non-TCP streams are flow controlled by IP. The way this is accomplished
 454  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
 455  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
 456  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
 457  * functions.
 458  *
 459  * Per Tx ring udp flow control:
 460  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
 461  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
 462  *
 463  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
 464  * To achieve best performance, outgoing traffic need to be fanned out among
 465  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
 466  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
 467  * the address of connp as fanout hint to mac_tx(). Under flow controlled
 468  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
 469  * cookie points to a specific Tx ring that is blocked. The cookie is used to
 470  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
 471  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
 472  * connp's. The drain list is not a single list but a configurable number of
 473  * lists.
 474  *
 475  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
 476  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
 477  * which is equal to 128. This array in turn contains a pointer to idl_t[],
 478  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
 479  * list will point to the list of connp's that are flow controlled.
 480  *
 481  *                      ---------------   -------   -------   -------
 482  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 483  *                   |  ---------------   -------   -------   -------
 484  *                   |  ---------------   -------   -------   -------
 485  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 486  * ----------------  |  ---------------   -------   -------   -------
 487  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
 488  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
 489  *                   |  ---------------   -------   -------   -------
 490  *                   .        .              .         .         .
 491  *                   |  ---------------   -------   -------   -------
 492  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 493  *                      ---------------   -------   -------   -------
 494  *                      ---------------   -------   -------   -------
 495  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 496  *                   |  ---------------   -------   -------   -------
 497  *                   |  ---------------   -------   -------   -------
 498  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 499  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
 500  * ----------------  |        .              .         .         .
 501  *                   |  ---------------   -------   -------   -------
 502  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 503  *                      ---------------   -------   -------   -------
 504  *     .....
 505  * ----------------
 506  * |idl_tx_list[n]|-> ...
 507  * ----------------
 508  *
 509  * When mac_tx() returns a cookie, the cookie is hashed into an index into
 510  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
 511  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
 512  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
 513  * Further, conn_blocked is set to indicate that the conn is blocked.
 514  *
 515  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
 516  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
 517  * is again hashed to locate the appropriate idl_tx_list, which is then
 518  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
 519  * the drain list and calls conn_drain_remove() to clear flow control (via
 520  * calling su_txq_full() or clearing QFULL), and remove the conn from the
 521  * drain list.
 522  *
 523  * Note that the drain list is not a single list but a (configurable) array of
 524  * lists (8 elements by default).  Synchronization between drain insertion and
 525  * flow control wakeup is handled by using idl_txl->txl_lock, and only
 526  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
 527  *
 528  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
 529  * On the send side, if the packet cannot be sent down to the driver by IP
 530  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
 531  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
 532  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
 533  * control has been relieved, the blocked conns in the 0'th drain list are
 534  * drained as in the non-STREAMS case.
 535  *
 536  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
 537  * is done when the conn is inserted into the drain list (conn_drain_insert())
 538  * and cleared when the conn is removed from the it (conn_drain_remove()).
 539  *
 540  * IPQOS notes:
 541  *
 542  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
 543  * and IPQoS modules. IPPF includes hooks in IP at different control points
 544  * (callout positions) which direct packets to IPQoS modules for policy
 545  * processing. Policies, if present, are global.
 546  *
 547  * The callout positions are located in the following paths:
 548  *              o local_in (packets destined for this host)
 549  *              o local_out (packets orginating from this host )
 550  *              o fwd_in  (packets forwarded by this m/c - inbound)
 551  *              o fwd_out (packets forwarded by this m/c - outbound)
 552  * Hooks at these callout points can be enabled/disabled using the ndd variable
 553  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
 554  * By default all the callout positions are enabled.
 555  *
 556  * Outbound (local_out)
 557  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
 558  *
 559  * Inbound (local_in)
 560  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
 561  *
 562  * Forwarding (in and out)
 563  * Hooks are placed in ire_recv_forward_v4/v6.
 564  *
 565  * IP Policy Framework processing (IPPF processing)
 566  * Policy processing for a packet is initiated by ip_process, which ascertains
 567  * that the classifier (ipgpc) is loaded and configured, failing which the
 568  * packet resumes normal processing in IP. If the clasifier is present, the
 569  * packet is acted upon by one or more IPQoS modules (action instances), per
 570  * filters configured in ipgpc and resumes normal IP processing thereafter.
 571  * An action instance can drop a packet in course of its processing.
 572  *
 573  * Zones notes:
 574  *
 575  * The partitioning rules for networking are as follows:
 576  * 1) Packets coming from a zone must have a source address belonging to that
 577  * zone.
 578  * 2) Packets coming from a zone can only be sent on a physical interface on
 579  * which the zone has an IP address.
 580  * 3) Between two zones on the same machine, packet delivery is only allowed if
 581  * there's a matching route for the destination and zone in the forwarding
 582  * table.
 583  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
 584  * different zones can bind to the same port with the wildcard address
 585  * (INADDR_ANY).
 586  *
 587  * The granularity of interface partitioning is at the logical interface level.
 588  * Therefore, every zone has its own IP addresses, and incoming packets can be
 589  * attributed to a zone unambiguously. A logical interface is placed into a zone
 590  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
 591  * structure. Rule (1) is implemented by modifying the source address selection
 592  * algorithm so that the list of eligible addresses is filtered based on the
 593  * sending process zone.
 594  *
 595  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
 596  * across all zones, depending on their type. Here is the break-up:
 597  *
 598  * IRE type                             Shared/exclusive
 599  * --------                             ----------------
 600  * IRE_BROADCAST                        Exclusive
 601  * IRE_DEFAULT (default routes)         Shared (*)
 602  * IRE_LOCAL                            Exclusive (x)
 603  * IRE_LOOPBACK                         Exclusive
 604  * IRE_PREFIX (net routes)              Shared (*)
 605  * IRE_IF_NORESOLVER (interface routes) Exclusive
 606  * IRE_IF_RESOLVER (interface routes)   Exclusive
 607  * IRE_IF_CLONE (interface routes)      Exclusive
 608  * IRE_HOST (host routes)               Shared (*)
 609  *
 610  * (*) A zone can only use a default or off-subnet route if the gateway is
 611  * directly reachable from the zone, that is, if the gateway's address matches
 612  * one of the zone's logical interfaces.
 613  *
 614  * (x) IRE_LOCAL are handled a bit differently.
 615  * When ip_restrict_interzone_loopback is set (the default),
 616  * ire_route_recursive restricts loopback using an IRE_LOCAL
 617  * between zone to the case when L2 would have conceptually looped the packet
 618  * back, i.e. the loopback which is required since neither Ethernet drivers
 619  * nor Ethernet hardware loops them back. This is the case when the normal
 620  * routes (ignoring IREs with different zoneids) would send out the packet on
 621  * the same ill as the ill with which is IRE_LOCAL is associated.
 622  *
 623  * Multiple zones can share a common broadcast address; typically all zones
 624  * share the 255.255.255.255 address. Incoming as well as locally originated
 625  * broadcast packets must be dispatched to all the zones on the broadcast
 626  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
 627  * since some zones may not be on the 10.16.72/24 network. To handle this, each
 628  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
 629  * sent to every zone that has an IRE_BROADCAST entry for the destination
 630  * address on the input ill, see ip_input_broadcast().
 631  *
 632  * Applications in different zones can join the same multicast group address.
 633  * The same logic applies for multicast as for broadcast. ip_input_multicast
 634  * dispatches packets to all zones that have members on the physical interface.
 635  */
 636 
 637 /*
 638  * Squeue Fanout flags:
 639  *      0: No fanout.
 640  *      1: Fanout across all squeues
 641  */
 642 boolean_t       ip_squeue_fanout = 0;
 643 
 644 /*
 645  * Maximum dups allowed per packet.
 646  */
 647 uint_t ip_max_frag_dups = 10;
 648 
 649 static int      ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
 650                     cred_t *credp, boolean_t isv6);
 651 static mblk_t   *ip_xmit_attach_llhdr(mblk_t *, nce_t *);
 652 
 653 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
 654 static void     icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
 655 static void     icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
 656     ip_recv_attr_t *);
 657 static void     icmp_options_update(ipha_t *);
 658 static void     icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
 659 static void     icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
 660 static mblk_t   *icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
 661 static void     icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
 662     ip_recv_attr_t *);
 663 static void     icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
 664 static void     icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
 665     ip_recv_attr_t *);
 666 
 667 mblk_t          *ip_dlpi_alloc(size_t, t_uscalar_t);
 668 char            *ip_dot_addr(ipaddr_t, char *);
 669 mblk_t          *ip_carve_mp(mblk_t **, ssize_t);
 670 static char     *ip_dot_saddr(uchar_t *, char *);
 671 static int      ip_lrput(queue_t *, mblk_t *);
 672 ipaddr_t        ip_net_mask(ipaddr_t);
 673 char            *ip_nv_lookup(nv_t *, int);
 674 int             ip_rput(queue_t *, mblk_t *);
 675 static void     ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
 676                     void *dummy_arg);
 677 int             ip_snmp_get(queue_t *, mblk_t *, int, boolean_t);
 678 static mblk_t   *ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
 679                     mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
 680 static mblk_t   *ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
 681                     ip_stack_t *, boolean_t);
 682 static mblk_t   *ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
 683                     boolean_t);
 684 static mblk_t   *ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
 685 static mblk_t   *ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
 686 static mblk_t   *ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
 687 static mblk_t   *ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
 688 static mblk_t   *ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
 689                     ip_stack_t *ipst, boolean_t);
 690 static mblk_t   *ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
 691                     ip_stack_t *ipst, boolean_t);
 692 static mblk_t   *ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
 693                     ip_stack_t *ipst);
 694 static mblk_t   *ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
 695                     ip_stack_t *ipst);
 696 static mblk_t   *ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
 697                     ip_stack_t *ipst);
 698 static mblk_t   *ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
 699                     ip_stack_t *ipst);
 700 static mblk_t   *ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
 701                     ip_stack_t *ipst);
 702 static mblk_t   *ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
 703                     ip_stack_t *ipst);
 704 static mblk_t   *ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
 705                     ip_stack_t *ipst);
 706 static mblk_t   *ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
 707                     ip_stack_t *ipst);
 708 static void     ip_snmp_get2_v4(ire_t *, iproutedata_t *);
 709 static void     ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
 710 static void     ip_snmp_get2_v4_media(ncec_t *, void *);
 711 static void     ip_snmp_get2_v6_media(ncec_t *, void *);
 712 int             ip_snmp_set(queue_t *, int, int, uchar_t *, int);
 713 
 714 static mblk_t   *ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
 715                     mblk_t *);
 716 
 717 static void     conn_drain_init(ip_stack_t *);
 718 static void     conn_drain_fini(ip_stack_t *);
 719 static void     conn_drain(conn_t *connp, boolean_t closing);
 720 
 721 static void     conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
 722 static void     conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
 723 
 724 static void     *ip_stack_init(netstackid_t stackid, netstack_t *ns);
 725 static void     ip_stack_shutdown(netstackid_t stackid, void *arg);
 726 static void     ip_stack_fini(netstackid_t stackid, void *arg);
 727 
 728 static int      ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
 729     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
 730     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
 731     const in6_addr_t *);
 732 
 733 static int      ip_squeue_switch(int);
 734 
 735 static void     *ip_kstat_init(netstackid_t, ip_stack_t *);
 736 static void     ip_kstat_fini(netstackid_t, kstat_t *);
 737 static int      ip_kstat_update(kstat_t *kp, int rw);
 738 static void     *icmp_kstat_init(netstackid_t);
 739 static void     icmp_kstat_fini(netstackid_t, kstat_t *);
 740 static int      icmp_kstat_update(kstat_t *kp, int rw);
 741 static void     *ip_kstat2_init(netstackid_t, ip_stat_t *);
 742 static void     ip_kstat2_fini(netstackid_t, kstat_t *);
 743 
 744 static void     ipobs_init(ip_stack_t *);
 745 static void     ipobs_fini(ip_stack_t *);
 746 
 747 static int      ip_tp_cpu_update(cpu_setup_t, int, void *);
 748 
 749 ipaddr_t        ip_g_all_ones = IP_HOST_MASK;
 750 
 751 static long ip_rput_pullups;
 752 int     dohwcksum = 1;  /* use h/w cksum if supported by the hardware */
 753 
 754 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
 755 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
 756 
 757 int     ip_debug;
 758 
 759 /*
 760  * Multirouting/CGTP stuff
 761  */
 762 int     ip_cgtp_filter_rev = CGTP_FILTER_REV;   /* CGTP hooks version */
 763 
 764 /*
 765  * IP tunables related declarations. Definitions are in ip_tunables.c
 766  */
 767 extern mod_prop_info_t ip_propinfo_tbl[];
 768 extern int ip_propinfo_count;
 769 
 770 /*
 771  * Table of IP ioctls encoding the various properties of the ioctl and
 772  * indexed based on the last byte of the ioctl command. Occasionally there
 773  * is a clash, and there is more than 1 ioctl with the same last byte.
 774  * In such a case 1 ioctl is encoded in the ndx table and the remaining
 775  * ioctls are encoded in the misc table. An entry in the ndx table is
 776  * retrieved by indexing on the last byte of the ioctl command and comparing
 777  * the ioctl command with the value in the ndx table. In the event of a
 778  * mismatch the misc table is then searched sequentially for the desired
 779  * ioctl command.
 780  *
 781  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
 782  */
 783 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
 784         /* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 785         /* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 786         /* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 787         /* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 788         /* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 789         /* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 790         /* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 791         /* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 792         /* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 793         /* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 794 
 795         /* 010 */ { SIOCADDRT,  sizeof (struct rtentry), IPI_PRIV,
 796                         MISC_CMD, ip_siocaddrt, NULL },
 797         /* 011 */ { SIOCDELRT,  sizeof (struct rtentry), IPI_PRIV,
 798                         MISC_CMD, ip_siocdelrt, NULL },
 799 
 800         /* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 801                         IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
 802         /* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
 803                         IF_CMD, ip_sioctl_get_addr, NULL },
 804 
 805         /* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 806                         IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
 807         /* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
 808                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
 809 
 810         /* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
 811                         IPI_PRIV | IPI_WR,
 812                         IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
 813         /* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
 814                         IPI_MODOK | IPI_GET_CMD,
 815                         IF_CMD, ip_sioctl_get_flags, NULL },
 816 
 817         /* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 818         /* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 819 
 820         /* copyin size cannot be coded for SIOCGIFCONF */
 821         /* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
 822                         MISC_CMD, ip_sioctl_get_ifconf, NULL },
 823 
 824         /* 021 */ { SIOCSIFMTU, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 825                         IF_CMD, ip_sioctl_mtu, NULL },
 826         /* 022 */ { SIOCGIFMTU, sizeof (struct ifreq), IPI_GET_CMD,
 827                         IF_CMD, ip_sioctl_get_mtu, NULL },
 828         /* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
 829                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
 830         /* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 831                         IF_CMD, ip_sioctl_brdaddr, NULL },
 832         /* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
 833                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
 834         /* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 835                         IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
 836         /* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
 837                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
 838         /* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
 839                         IF_CMD, ip_sioctl_metric, NULL },
 840         /* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 841 
 842         /* See 166-168 below for extended SIOC*XARP ioctls */
 843         /* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
 844                         ARP_CMD, ip_sioctl_arp, NULL },
 845         /* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
 846                         ARP_CMD, ip_sioctl_arp, NULL },
 847         /* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
 848                         ARP_CMD, ip_sioctl_arp, NULL },
 849 
 850         /* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 851         /* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 852         /* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 853         /* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 854         /* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 855         /* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 856         /* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 857         /* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 858         /* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 859         /* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 860         /* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 861         /* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 862         /* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 863         /* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 864         /* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 865         /* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 866         /* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 867         /* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 868         /* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 869         /* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 870         /* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 871 
 872         /* 054 */ { IF_UNITSEL, sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
 873                         MISC_CMD, if_unitsel, if_unitsel_restart },
 874 
 875         /* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 876         /* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 877         /* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 878         /* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 879         /* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 880         /* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 881         /* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 882         /* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 883         /* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 884         /* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 885         /* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 886         /* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 887         /* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 888         /* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 889         /* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 890         /* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 891         /* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 892         /* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 893 
 894         /* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
 895                         IPI_PRIV | IPI_WR | IPI_MODOK,
 896                         IF_CMD, ip_sioctl_sifname, NULL },
 897 
 898         /* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 899         /* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 900         /* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 901         /* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 902         /* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 903         /* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 904         /* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 905         /* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 906         /* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 907         /* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 908         /* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 909         /* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 910         /* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 911 
 912         /* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
 913                         MISC_CMD, ip_sioctl_get_ifnum, NULL },
 914         /* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
 915                         IF_CMD, ip_sioctl_get_muxid, NULL },
 916         /* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
 917                         IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
 918 
 919         /* Both if and lif variants share same func */
 920         /* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
 921                         IF_CMD, ip_sioctl_get_lifindex, NULL },
 922         /* Both if and lif variants share same func */
 923         /* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
 924                         IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
 925 
 926         /* copyin size cannot be coded for SIOCGIFCONF */
 927         /* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
 928                         MISC_CMD, ip_sioctl_get_ifconf, NULL },
 929         /* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 930         /* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 931         /* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 932         /* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 933         /* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 934         /* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 935         /* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 936         /* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 937         /* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 938         /* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 939         /* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 940         /* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 941         /* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 942         /* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 943         /* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 944         /* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 945         /* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 946 
 947         /* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
 948                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
 949                         ip_sioctl_removeif_restart },
 950         /* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
 951                         IPI_GET_CMD | IPI_PRIV | IPI_WR,
 952                         LIF_CMD, ip_sioctl_addif, NULL },
 953 #define SIOCLIFADDR_NDX 112
 954         /* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 955                         LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
 956         /* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
 957                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
 958         /* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 959                         LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
 960         /* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
 961                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
 962         /* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
 963                         IPI_PRIV | IPI_WR,
 964                         LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
 965         /* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
 966                         IPI_GET_CMD | IPI_MODOK,
 967                         LIF_CMD, ip_sioctl_get_flags, NULL },
 968 
 969         /* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 970         /* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 971 
 972         /* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
 973                         ip_sioctl_get_lifconf, NULL },
 974         /* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 975                         LIF_CMD, ip_sioctl_mtu, NULL },
 976         /* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
 977                         LIF_CMD, ip_sioctl_get_mtu, NULL },
 978         /* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
 979                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
 980         /* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 981                         LIF_CMD, ip_sioctl_brdaddr, NULL },
 982         /* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
 983                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
 984         /* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 985                         LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
 986         /* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
 987                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
 988         /* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 989                         LIF_CMD, ip_sioctl_metric, NULL },
 990         /* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
 991                         IPI_PRIV | IPI_WR | IPI_MODOK,
 992                         LIF_CMD, ip_sioctl_slifname,
 993                         ip_sioctl_slifname_restart },
 994 
 995         /* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
 996                         MISC_CMD, ip_sioctl_get_lifnum, NULL },
 997         /* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
 998                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
 999         /* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1000                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1001         /* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1002                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1003         /* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1004                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1005         /* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1006                         LIF_CMD, ip_sioctl_token, NULL },
1007         /* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1008                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1009         /* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1010                         LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1011         /* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1012                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1013         /* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1014                         LIF_CMD, ip_sioctl_lnkinfo, NULL },
1015 
1016         /* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1017                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1018         /* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1019                         LIF_CMD, ip_siocdelndp_v6, NULL },
1020         /* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1021                         LIF_CMD, ip_siocqueryndp_v6, NULL },
1022         /* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1023                         LIF_CMD, ip_siocsetndp_v6, NULL },
1024         /* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1025                         MISC_CMD, ip_sioctl_tmyaddr, NULL },
1026         /* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1027                         MISC_CMD, ip_sioctl_tonlink, NULL },
1028         /* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1029                         MISC_CMD, ip_sioctl_tmysite, NULL },
1030         /* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031         /* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 
1033         /* Old *IPSECONFIG ioctls are now deprecated, now see spdsock.c */
1034         /* 149 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035         /* 150 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036         /* 151 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037         /* 152 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 
1039         /* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 
1041         /* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1042                         LIF_CMD, ip_sioctl_get_binding, NULL },
1043         /* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1044                         IPI_PRIV | IPI_WR,
1045                         LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1046         /* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1047                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1048         /* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1049                         IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1050 
1051         /* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1052         /* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053         /* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054         /* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 
1056         /* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 
1058         /* These are handled in ip_sioctl_copyin_setup itself */
1059         /* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1060                         MISC_CMD, NULL, NULL },
1061         /* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1062                         MISC_CMD, NULL, NULL },
1063         /* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1064 
1065         /* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1066                         ip_sioctl_get_lifconf, NULL },
1067 
1068         /* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1069                         XARP_CMD, ip_sioctl_arp, NULL },
1070         /* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1071                         XARP_CMD, ip_sioctl_arp, NULL },
1072         /* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1073                         XARP_CMD, ip_sioctl_arp, NULL },
1074 
1075         /* SIOCPOPSOCKFS is not handled by IP */
1076         /* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1077 
1078         /* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1079                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1080         /* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1081                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1082                         ip_sioctl_slifzone_restart },
1083         /* 172-174 are SCTP ioctls and not handled by IP */
1084         /* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085         /* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086         /* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1087         /* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1088                         IPI_GET_CMD, LIF_CMD,
1089                         ip_sioctl_get_lifusesrc, 0 },
1090         /* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1091                         IPI_PRIV | IPI_WR,
1092                         LIF_CMD, ip_sioctl_slifusesrc,
1093                         NULL },
1094         /* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1095                         ip_sioctl_get_lifsrcof, NULL },
1096         /* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1097                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1098         /* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1099                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1100         /* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1101                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1102         /* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1103                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1104         /* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105         /* SIOCSENABLESDP is handled by SDP */
1106         /* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1107         /* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1108         /* 185 */ { SIOCGIFHWADDR, sizeof (struct ifreq), IPI_GET_CMD,
1109                         IF_CMD, ip_sioctl_get_ifhwaddr, NULL },
1110         /* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1111         /* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1112                         ip_sioctl_ilb_cmd, NULL },
1113         /* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1114         /* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1115         /* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1116                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1117         /* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1118                         LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart },
1119         /* 192 */ { SIOCGLIFHWADDR, sizeof (struct lifreq), IPI_GET_CMD,
1120                         LIF_CMD, ip_sioctl_get_lifhwaddr, NULL }
1121 };
1122 
1123 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1124 
1125 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1126         { I_LINK,       0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1127         { I_UNLINK,     0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1128         { I_PLINK,      0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1129         { I_PUNLINK,    0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1130         { ND_GET,       0, 0, 0, NULL, NULL },
1131         { ND_SET,       0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1132         { IP_IOCTL,     0, 0, 0, NULL, NULL },
1133         { SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1134                 MISC_CMD, mrt_ioctl},
1135         { SIOCGETSGCNT, sizeof (struct sioc_sg_req), IPI_GET_CMD,
1136                 MISC_CMD, mrt_ioctl},
1137         { SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1138                 MISC_CMD, mrt_ioctl}
1139 };
1140 
1141 int ip_misc_ioctl_count =
1142     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1143 
1144 int     conn_drain_nthreads;            /* Number of drainers reqd. */
1145                                         /* Settable in /etc/system */
1146 /* Defined in ip_ire.c */
1147 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1148 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1149 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1150 
1151 static nv_t     ire_nv_arr[] = {
1152         { IRE_BROADCAST, "BROADCAST" },
1153         { IRE_LOCAL, "LOCAL" },
1154         { IRE_LOOPBACK, "LOOPBACK" },
1155         { IRE_DEFAULT, "DEFAULT" },
1156         { IRE_PREFIX, "PREFIX" },
1157         { IRE_IF_NORESOLVER, "IF_NORESOL" },
1158         { IRE_IF_RESOLVER, "IF_RESOLV" },
1159         { IRE_IF_CLONE, "IF_CLONE" },
1160         { IRE_HOST, "HOST" },
1161         { IRE_MULTICAST, "MULTICAST" },
1162         { IRE_NOROUTE, "NOROUTE" },
1163         { 0 }
1164 };
1165 
1166 nv_t    *ire_nv_tbl = ire_nv_arr;
1167 
1168 /* Simple ICMP IP Header Template */
1169 static ipha_t icmp_ipha = {
1170         IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1171 };
1172 
1173 struct module_info ip_mod_info = {
1174         IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1175         IP_MOD_LOWAT
1176 };
1177 
1178 /*
1179  * Duplicate static symbols within a module confuses mdb; so we avoid the
1180  * problem by making the symbols here distinct from those in udp.c.
1181  */
1182 
1183 /*
1184  * Entry points for IP as a device and as a module.
1185  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1186  */
1187 static struct qinit iprinitv4 = {
1188         ip_rput, NULL, ip_openv4, ip_close, NULL, &ip_mod_info
1189 };
1190 
1191 struct qinit iprinitv6 = {
1192         ip_rput_v6, NULL, ip_openv6, ip_close, NULL, &ip_mod_info
1193 };
1194 
1195 static struct qinit ipwinit = {
1196         ip_wput_nondata, ip_wsrv, NULL, NULL, NULL, &ip_mod_info
1197 };
1198 
1199 static struct qinit iplrinit = {
1200         ip_lrput, NULL, ip_openv4, ip_close, NULL, &ip_mod_info
1201 };
1202 
1203 static struct qinit iplwinit = {
1204         ip_lwput, NULL, NULL, NULL, NULL, &ip_mod_info
1205 };
1206 
1207 /* For AF_INET aka /dev/ip */
1208 struct streamtab ipinfov4 = {
1209         &iprinitv4, &ipwinit, &iplrinit, &iplwinit
1210 };
1211 
1212 /* For AF_INET6 aka /dev/ip6 */
1213 struct streamtab ipinfov6 = {
1214         &iprinitv6, &ipwinit, &iplrinit, &iplwinit
1215 };
1216 
1217 #ifdef  DEBUG
1218 boolean_t skip_sctp_cksum = B_FALSE;
1219 #endif
1220 
1221 /*
1222  * Generate an ICMP fragmentation needed message.
1223  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1224  * constructed by the caller.
1225  */
1226 void
1227 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1228 {
1229         icmph_t icmph;
1230         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
1231 
1232         mp = icmp_pkt_err_ok(mp, ira);
1233         if (mp == NULL)
1234                 return;
1235 
1236         bzero(&icmph, sizeof (icmph_t));
1237         icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1238         icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1239         icmph.icmph_du_mtu = htons((uint16_t)mtu);
1240         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1241         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1242 
1243         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1244 }
1245 
1246 /*
1247  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1248  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1249  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1250  * Likewise, if the ICMP error is misformed (too short, etc), then it
1251  * returns NULL. The caller uses this to determine whether or not to send
1252  * to raw sockets.
1253  *
1254  * All error messages are passed to the matching transport stream.
1255  *
1256  * The following cases are handled by icmp_inbound:
1257  * 1) It needs to send a reply back and possibly delivering it
1258  *    to the "interested" upper clients.
1259  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1260  * 3) It needs to change some values in IP only.
1261  * 4) It needs to change some values in IP and upper layers e.g TCP
1262  *    by delivering an error to the upper layers.
1263  *
1264  * We handle the above three cases in the context of IPsec in the
1265  * following way :
1266  *
1267  * 1) Send the reply back in the same way as the request came in.
1268  *    If it came in encrypted, it goes out encrypted. If it came in
1269  *    clear, it goes out in clear. Thus, this will prevent chosen
1270  *    plain text attack.
1271  * 2) The client may or may not expect things to come in secure.
1272  *    If it comes in secure, the policy constraints are checked
1273  *    before delivering it to the upper layers. If it comes in
1274  *    clear, ipsec_inbound_accept_clear will decide whether to
1275  *    accept this in clear or not. In both the cases, if the returned
1276  *    message (IP header + 8 bytes) that caused the icmp message has
1277  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1278  *    sending up. If there are only 8 bytes of returned message, then
1279  *    upper client will not be notified.
1280  * 3) Check with global policy to see whether it matches the constaints.
1281  *    But this will be done only if icmp_accept_messages_in_clear is
1282  *    zero.
1283  * 4) If we need to change both in IP and ULP, then the decision taken
1284  *    while affecting the values in IP and while delivering up to TCP
1285  *    should be the same.
1286  *
1287  *      There are two cases.
1288  *
1289  *      a) If we reject data at the IP layer (ipsec_check_global_policy()
1290  *         failed), we will not deliver it to the ULP, even though they
1291  *         are *willing* to accept in *clear*. This is fine as our global
1292  *         disposition to icmp messages asks us reject the datagram.
1293  *
1294  *      b) If we accept data at the IP layer (ipsec_check_global_policy()
1295  *         succeeded or icmp_accept_messages_in_clear is 1), and not able
1296  *         to deliver it to ULP (policy failed), it can lead to
1297  *         consistency problems. The cases known at this time are
1298  *         ICMP_DESTINATION_UNREACHABLE  messages with following code
1299  *         values :
1300  *
1301  *         - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1302  *           and Upper layer rejects. Then the communication will
1303  *           come to a stop. This is solved by making similar decisions
1304  *           at both levels. Currently, when we are unable to deliver
1305  *           to the Upper Layer (due to policy failures) while IP has
1306  *           adjusted dce_pmtu, the next outbound datagram would
1307  *           generate a local ICMP_FRAGMENTATION_NEEDED message - which
1308  *           will be with the right level of protection. Thus the right
1309  *           value will be communicated even if we are not able to
1310  *           communicate when we get from the wire initially. But this
1311  *           assumes there would be at least one outbound datagram after
1312  *           IP has adjusted its dce_pmtu value. To make things
1313  *           simpler, we accept in clear after the validation of
1314  *           AH/ESP headers.
1315  *
1316  *         - Other ICMP ERRORS : We may not be able to deliver it to the
1317  *           upper layer depending on the level of protection the upper
1318  *           layer expects and the disposition in ipsec_inbound_accept_clear().
1319  *           ipsec_inbound_accept_clear() decides whether a given ICMP error
1320  *           should be accepted in clear when the Upper layer expects secure.
1321  *           Thus the communication may get aborted by some bad ICMP
1322  *           packets.
1323  */
1324 mblk_t *
1325 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1326 {
1327         icmph_t         *icmph;
1328         ipha_t          *ipha;          /* Outer header */
1329         int             ip_hdr_length;  /* Outer header length */
1330         boolean_t       interested;
1331         ipif_t          *ipif;
1332         uint32_t        ts;
1333         uint32_t        *tsp;
1334         timestruc_t     now;
1335         ill_t           *ill = ira->ira_ill;
1336         ip_stack_t      *ipst = ill->ill_ipst;
1337         zoneid_t        zoneid = ira->ira_zoneid;
1338         int             len_needed;
1339         mblk_t          *mp_ret = NULL;
1340 
1341         ipha = (ipha_t *)mp->b_rptr;
1342 
1343         BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1344 
1345         ip_hdr_length = ira->ira_ip_hdr_length;
1346         if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1347                 if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1348                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1349                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1350                         freemsg(mp);
1351                         return (NULL);
1352                 }
1353                 /* Last chance to get real. */
1354                 ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1355                 if (ipha == NULL) {
1356                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1357                         freemsg(mp);
1358                         return (NULL);
1359                 }
1360         }
1361 
1362         /* The IP header will always be a multiple of four bytes */
1363         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1364         ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1365             icmph->icmph_code));
1366 
1367         /*
1368          * We will set "interested" to "true" if we should pass a copy to
1369          * the transport or if we handle the packet locally.
1370          */
1371         interested = B_FALSE;
1372         switch (icmph->icmph_type) {
1373         case ICMP_ECHO_REPLY:
1374                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1375                 break;
1376         case ICMP_DEST_UNREACHABLE:
1377                 if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1378                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1379                 interested = B_TRUE;    /* Pass up to transport */
1380                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1381                 break;
1382         case ICMP_SOURCE_QUENCH:
1383                 interested = B_TRUE;    /* Pass up to transport */
1384                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1385                 break;
1386         case ICMP_REDIRECT:
1387                 if (!ipst->ips_ip_ignore_redirect)
1388                         interested = B_TRUE;
1389                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1390                 break;
1391         case ICMP_ECHO_REQUEST:
1392                 /*
1393                  * Whether to respond to echo requests that come in as IP
1394                  * broadcasts or as IP multicast is subject to debate
1395                  * (what isn't?).  We aim to please, you pick it.
1396                  * Default is do it.
1397                  */
1398                 if (ira->ira_flags & IRAF_MULTICAST) {
1399                         /* multicast: respond based on tunable */
1400                         interested = ipst->ips_ip_g_resp_to_echo_mcast;
1401                 } else if (ira->ira_flags & IRAF_BROADCAST) {
1402                         /* broadcast: respond based on tunable */
1403                         interested = ipst->ips_ip_g_resp_to_echo_bcast;
1404                 } else {
1405                         /* unicast: always respond */
1406                         interested = B_TRUE;
1407                 }
1408                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1409                 if (!interested) {
1410                         /* We never pass these to RAW sockets */
1411                         freemsg(mp);
1412                         return (NULL);
1413                 }
1414 
1415                 /* Check db_ref to make sure we can modify the packet. */
1416                 if (mp->b_datap->db_ref > 1) {
1417                         mblk_t  *mp1;
1418 
1419                         mp1 = copymsg(mp);
1420                         freemsg(mp);
1421                         if (!mp1) {
1422                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1423                                 return (NULL);
1424                         }
1425                         mp = mp1;
1426                         ipha = (ipha_t *)mp->b_rptr;
1427                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1428                 }
1429                 icmph->icmph_type = ICMP_ECHO_REPLY;
1430                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1431                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1432                 return (NULL);
1433 
1434         case ICMP_ROUTER_ADVERTISEMENT:
1435         case ICMP_ROUTER_SOLICITATION:
1436                 break;
1437         case ICMP_TIME_EXCEEDED:
1438                 interested = B_TRUE;    /* Pass up to transport */
1439                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1440                 break;
1441         case ICMP_PARAM_PROBLEM:
1442                 interested = B_TRUE;    /* Pass up to transport */
1443                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1444                 break;
1445         case ICMP_TIME_STAMP_REQUEST:
1446                 /* Response to Time Stamp Requests is local policy. */
1447                 if (ipst->ips_ip_g_resp_to_timestamp) {
1448                         if (ira->ira_flags & IRAF_MULTIBROADCAST)
1449                                 interested =
1450                                     ipst->ips_ip_g_resp_to_timestamp_bcast;
1451                         else
1452                                 interested = B_TRUE;
1453                 }
1454                 if (!interested) {
1455                         /* We never pass these to RAW sockets */
1456                         freemsg(mp);
1457                         return (NULL);
1458                 }
1459 
1460                 /* Make sure we have enough of the packet */
1461                 len_needed = ip_hdr_length + ICMPH_SIZE +
1462                     3 * sizeof (uint32_t);
1463 
1464                 if (mp->b_wptr - mp->b_rptr < len_needed) {
1465                         ipha = ip_pullup(mp, len_needed, ira);
1466                         if (ipha == NULL) {
1467                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1468                                 ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1469                                     mp, ill);
1470                                 freemsg(mp);
1471                                 return (NULL);
1472                         }
1473                         /* Refresh following the pullup. */
1474                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1475                 }
1476                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1477                 /* Check db_ref to make sure we can modify the packet. */
1478                 if (mp->b_datap->db_ref > 1) {
1479                         mblk_t  *mp1;
1480 
1481                         mp1 = copymsg(mp);
1482                         freemsg(mp);
1483                         if (!mp1) {
1484                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1485                                 return (NULL);
1486                         }
1487                         mp = mp1;
1488                         ipha = (ipha_t *)mp->b_rptr;
1489                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1490                 }
1491                 icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1492                 tsp = (uint32_t *)&icmph[1];
1493                 tsp++;          /* Skip past 'originate time' */
1494                 /* Compute # of milliseconds since midnight */
1495                 gethrestime(&now);
1496                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1497                     NSEC2MSEC(now.tv_nsec);
1498                 *tsp++ = htonl(ts);     /* Lay in 'receive time' */
1499                 *tsp++ = htonl(ts);     /* Lay in 'send time' */
1500                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1501                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1502                 return (NULL);
1503 
1504         case ICMP_TIME_STAMP_REPLY:
1505                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1506                 break;
1507         case ICMP_INFO_REQUEST:
1508                 /* Per RFC 1122 3.2.2.7, ignore this. */
1509         case ICMP_INFO_REPLY:
1510                 break;
1511         case ICMP_ADDRESS_MASK_REQUEST:
1512                 if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1513                         interested =
1514                             ipst->ips_ip_respond_to_address_mask_broadcast;
1515                 } else {
1516                         interested = B_TRUE;
1517                 }
1518                 if (!interested) {
1519                         /* We never pass these to RAW sockets */
1520                         freemsg(mp);
1521                         return (NULL);
1522                 }
1523                 len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1524                 if (mp->b_wptr - mp->b_rptr < len_needed) {
1525                         ipha = ip_pullup(mp, len_needed, ira);
1526                         if (ipha == NULL) {
1527                                 BUMP_MIB(ill->ill_ip_mib,
1528                                     ipIfStatsInTruncatedPkts);
1529                                 ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1530                                     ill);
1531                                 freemsg(mp);
1532                                 return (NULL);
1533                         }
1534                         /* Refresh following the pullup. */
1535                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1536                 }
1537                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1538                 /* Check db_ref to make sure we can modify the packet. */
1539                 if (mp->b_datap->db_ref > 1) {
1540                         mblk_t  *mp1;
1541 
1542                         mp1 = copymsg(mp);
1543                         freemsg(mp);
1544                         if (!mp1) {
1545                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1546                                 return (NULL);
1547                         }
1548                         mp = mp1;
1549                         ipha = (ipha_t *)mp->b_rptr;
1550                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1551                 }
1552                 /*
1553                  * Need the ipif with the mask be the same as the source
1554                  * address of the mask reply. For unicast we have a specific
1555                  * ipif. For multicast/broadcast we only handle onlink
1556                  * senders, and use the source address to pick an ipif.
1557                  */
1558                 ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1559                 if (ipif == NULL) {
1560                         /* Broadcast or multicast */
1561                         ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1562                         if (ipif == NULL) {
1563                                 freemsg(mp);
1564                                 return (NULL);
1565                         }
1566                 }
1567                 icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1568                 bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1569                 ipif_refrele(ipif);
1570                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1571                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1572                 return (NULL);
1573 
1574         case ICMP_ADDRESS_MASK_REPLY:
1575                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1576                 break;
1577         default:
1578                 interested = B_TRUE;    /* Pass up to transport */
1579                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1580                 break;
1581         }
1582         /*
1583          * See if there is an ICMP client to avoid an extra copymsg/freemsg
1584          * if there isn't one.
1585          */
1586         if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1587                 /* If there is an ICMP client and we want one too, copy it. */
1588 
1589                 if (!interested) {
1590                         /* Caller will deliver to RAW sockets */
1591                         return (mp);
1592                 }
1593                 mp_ret = copymsg(mp);
1594                 if (mp_ret == NULL) {
1595                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1596                         ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1597                 }
1598         } else if (!interested) {
1599                 /* Neither we nor raw sockets are interested. Drop packet now */
1600                 freemsg(mp);
1601                 return (NULL);
1602         }
1603 
1604         /*
1605          * ICMP error or redirect packet. Make sure we have enough of
1606          * the header and that db_ref == 1 since we might end up modifying
1607          * the packet.
1608          */
1609         if (mp->b_cont != NULL) {
1610                 if (ip_pullup(mp, -1, ira) == NULL) {
1611                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1612                         ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1613                             mp, ill);
1614                         freemsg(mp);
1615                         return (mp_ret);
1616                 }
1617         }
1618 
1619         if (mp->b_datap->db_ref > 1) {
1620                 mblk_t  *mp1;
1621 
1622                 mp1 = copymsg(mp);
1623                 if (mp1 == NULL) {
1624                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1625                         ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1626                         freemsg(mp);
1627                         return (mp_ret);
1628                 }
1629                 freemsg(mp);
1630                 mp = mp1;
1631         }
1632 
1633         /*
1634          * In case mp has changed, verify the message before any further
1635          * processes.
1636          */
1637         ipha = (ipha_t *)mp->b_rptr;
1638         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1639         if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1640                 freemsg(mp);
1641                 return (mp_ret);
1642         }
1643 
1644         switch (icmph->icmph_type) {
1645         case ICMP_REDIRECT:
1646                 icmp_redirect_v4(mp, ipha, icmph, ira);
1647                 break;
1648         case ICMP_DEST_UNREACHABLE:
1649                 if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1650                         /* Update DCE and adjust MTU is icmp header if needed */
1651                         icmp_inbound_too_big_v4(icmph, ira);
1652                 }
1653                 /* FALLTHROUGH */
1654         default:
1655                 icmp_inbound_error_fanout_v4(mp, icmph, ira);
1656                 break;
1657         }
1658         return (mp_ret);
1659 }
1660 
1661 /*
1662  * Send an ICMP echo, timestamp or address mask reply.
1663  * The caller has already updated the payload part of the packet.
1664  * We handle the ICMP checksum, IP source address selection and feed
1665  * the packet into ip_output_simple.
1666  */
1667 static void
1668 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1669     ip_recv_attr_t *ira)
1670 {
1671         uint_t          ip_hdr_length = ira->ira_ip_hdr_length;
1672         ill_t           *ill = ira->ira_ill;
1673         ip_stack_t      *ipst = ill->ill_ipst;
1674         ip_xmit_attr_t  ixas;
1675 
1676         /* Send out an ICMP packet */
1677         icmph->icmph_checksum = 0;
1678         icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1679         /* Reset time to live. */
1680         ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1681         {
1682                 /* Swap source and destination addresses */
1683                 ipaddr_t tmp;
1684 
1685                 tmp = ipha->ipha_src;
1686                 ipha->ipha_src = ipha->ipha_dst;
1687                 ipha->ipha_dst = tmp;
1688         }
1689         ipha->ipha_ident = 0;
1690         if (!IS_SIMPLE_IPH(ipha))
1691                 icmp_options_update(ipha);
1692 
1693         bzero(&ixas, sizeof (ixas));
1694         ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1695         ixas.ixa_zoneid = ira->ira_zoneid;
1696         ixas.ixa_cred = kcred;
1697         ixas.ixa_cpid = NOPID;
1698         ixas.ixa_tsl = ira->ira_tsl; /* Behave as a multi-level responder */
1699         ixas.ixa_ifindex = 0;
1700         ixas.ixa_ipst = ipst;
1701         ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1702 
1703         if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1704                 /*
1705                  * This packet should go out the same way as it
1706                  * came in i.e in clear, independent of the IPsec policy
1707                  * for transmitting packets.
1708                  */
1709                 ixas.ixa_flags |= IXAF_NO_IPSEC;
1710         } else {
1711                 if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1712                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1713                         /* Note: mp already consumed and ip_drop_packet done */
1714                         return;
1715                 }
1716         }
1717         if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1718                 /*
1719                  * Not one or our addresses (IRE_LOCALs), thus we let
1720                  * ip_output_simple pick the source.
1721                  */
1722                 ipha->ipha_src = INADDR_ANY;
1723                 ixas.ixa_flags |= IXAF_SET_SOURCE;
1724         }
1725         /* Should we send with DF and use dce_pmtu? */
1726         if (ipst->ips_ipv4_icmp_return_pmtu) {
1727                 ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1728                 ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1729         }
1730 
1731         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1732 
1733         (void) ip_output_simple(mp, &ixas);
1734         ixa_cleanup(&ixas);
1735 }
1736 
1737 /*
1738  * Verify the ICMP messages for either for ICMP error or redirect packet.
1739  * The caller should have fully pulled up the message. If it's a redirect
1740  * packet, only basic checks on IP header will be done; otherwise, verify
1741  * the packet by looking at the included ULP header.
1742  *
1743  * Called before icmp_inbound_error_fanout_v4 is called.
1744  */
1745 static boolean_t
1746 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1747 {
1748         ill_t           *ill = ira->ira_ill;
1749         int             hdr_length;
1750         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
1751         conn_t          *connp;
1752         ipha_t          *ipha;  /* Inner IP header */
1753 
1754         ipha = (ipha_t *)&icmph[1];
1755         if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1756                 goto truncated;
1757 
1758         hdr_length = IPH_HDR_LENGTH(ipha);
1759 
1760         if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1761                 goto discard_pkt;
1762 
1763         if (hdr_length < sizeof (ipha_t))
1764                 goto truncated;
1765 
1766         if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1767                 goto truncated;
1768 
1769         /*
1770          * Stop here for ICMP_REDIRECT.
1771          */
1772         if (icmph->icmph_type == ICMP_REDIRECT)
1773                 return (B_TRUE);
1774 
1775         /*
1776          * ICMP errors only.
1777          */
1778         switch (ipha->ipha_protocol) {
1779         case IPPROTO_UDP:
1780                 /*
1781                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1782                  * transport header.
1783                  */
1784                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1785                     mp->b_wptr)
1786                         goto truncated;
1787                 break;
1788         case IPPROTO_TCP: {
1789                 tcpha_t         *tcpha;
1790 
1791                 /*
1792                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1793                  * transport header.
1794                  */
1795                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1796                     mp->b_wptr)
1797                         goto truncated;
1798 
1799                 tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1800                 connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1801                     ipst);
1802                 if (connp == NULL)
1803                         goto discard_pkt;
1804 
1805                 if ((connp->conn_verifyicmp != NULL) &&
1806                     !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1807                         CONN_DEC_REF(connp);
1808                         goto discard_pkt;
1809                 }
1810                 CONN_DEC_REF(connp);
1811                 break;
1812         }
1813         case IPPROTO_SCTP:
1814                 /*
1815                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1816                  * transport header.
1817                  */
1818                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1819                     mp->b_wptr)
1820                         goto truncated;
1821                 break;
1822         case IPPROTO_ESP:
1823         case IPPROTO_AH:
1824                 break;
1825         case IPPROTO_ENCAP:
1826                 if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1827                     mp->b_wptr)
1828                         goto truncated;
1829                 break;
1830         default:
1831                 break;
1832         }
1833 
1834         return (B_TRUE);
1835 
1836 discard_pkt:
1837         /* Bogus ICMP error. */
1838         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1839         return (B_FALSE);
1840 
1841 truncated:
1842         /* We pulled up everthing already. Must be truncated */
1843         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1844         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1845         return (B_FALSE);
1846 }
1847 
1848 /* Table from RFC 1191 */
1849 static int icmp_frag_size_table[] =
1850 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1851 
1852 /*
1853  * Process received ICMP Packet too big.
1854  * Just handles the DCE create/update, including using the above table of
1855  * PMTU guesses. The caller is responsible for validating the packet before
1856  * passing it in and also to fanout the ICMP error to any matching transport
1857  * conns. Assumes the message has been fully pulled up and verified.
1858  *
1859  * Before getting here, the caller has called icmp_inbound_verify_v4()
1860  * that should have verified with ULP to prevent undoing the changes we're
1861  * going to make to DCE. For example, TCP might have verified that the packet
1862  * which generated error is in the send window.
1863  *
1864  * In some cases modified this MTU in the ICMP header packet; the caller
1865  * should pass to the matching ULP after this returns.
1866  */
1867 static void
1868 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1869 {
1870         dce_t           *dce;
1871         int             old_mtu;
1872         int             mtu, orig_mtu;
1873         ipaddr_t        dst;
1874         boolean_t       disable_pmtud;
1875         ill_t           *ill = ira->ira_ill;
1876         ip_stack_t      *ipst = ill->ill_ipst;
1877         uint_t          hdr_length;
1878         ipha_t          *ipha;
1879 
1880         /* Caller already pulled up everything. */
1881         ipha = (ipha_t *)&icmph[1];
1882         ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1883             icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1884         ASSERT(ill != NULL);
1885 
1886         hdr_length = IPH_HDR_LENGTH(ipha);
1887 
1888         /*
1889          * We handle path MTU for source routed packets since the DCE
1890          * is looked up using the final destination.
1891          */
1892         dst = ip_get_dst(ipha);
1893 
1894         dce = dce_lookup_and_add_v4(dst, ipst);
1895         if (dce == NULL) {
1896                 /* Couldn't add a unique one - ENOMEM */
1897                 ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1898                     ntohl(dst)));
1899                 return;
1900         }
1901 
1902         /* Check for MTU discovery advice as described in RFC 1191 */
1903         mtu = ntohs(icmph->icmph_du_mtu);
1904         orig_mtu = mtu;
1905         disable_pmtud = B_FALSE;
1906 
1907         mutex_enter(&dce->dce_lock);
1908         if (dce->dce_flags & DCEF_PMTU)
1909                 old_mtu = dce->dce_pmtu;
1910         else
1911                 old_mtu = ill->ill_mtu;
1912 
1913         if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1914                 uint32_t length;
1915                 int     i;
1916 
1917                 /*
1918                  * Use the table from RFC 1191 to figure out
1919                  * the next "plateau" based on the length in
1920                  * the original IP packet.
1921                  */
1922                 length = ntohs(ipha->ipha_length);
1923                 DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1924                     uint32_t, length);
1925                 if (old_mtu <= length &&
1926                     old_mtu >= length - hdr_length) {
1927                         /*
1928                          * Handle broken BSD 4.2 systems that
1929                          * return the wrong ipha_length in ICMP
1930                          * errors.
1931                          */
1932                         ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1933                             length, old_mtu));
1934                         length -= hdr_length;
1935                 }
1936                 for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1937                         if (length > icmp_frag_size_table[i])
1938                                 break;
1939                 }
1940                 if (i == A_CNT(icmp_frag_size_table)) {
1941                         /* Smaller than IP_MIN_MTU! */
1942                         ip1dbg(("Too big for packet size %d\n",
1943                             length));
1944                         disable_pmtud = B_TRUE;
1945                         mtu = ipst->ips_ip_pmtu_min;
1946                 } else {
1947                         mtu = icmp_frag_size_table[i];
1948                         ip1dbg(("Calculated mtu %d, packet size %d, "
1949                             "before %d\n", mtu, length, old_mtu));
1950                         if (mtu < ipst->ips_ip_pmtu_min) {
1951                                 mtu = ipst->ips_ip_pmtu_min;
1952                                 disable_pmtud = B_TRUE;
1953                         }
1954                 }
1955         }
1956         if (disable_pmtud)
1957                 dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1958         else
1959                 dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1960 
1961         dce->dce_pmtu = MIN(old_mtu, mtu);
1962         /* Prepare to send the new max frag size for the ULP. */
1963         icmph->icmph_du_zero = 0;
1964         icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1965         DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1966             dce, int, orig_mtu, int, mtu);
1967 
1968         /* We now have a PMTU for sure */
1969         dce->dce_flags |= DCEF_PMTU;
1970         dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1971         mutex_exit(&dce->dce_lock);
1972         /*
1973          * After dropping the lock the new value is visible to everyone.
1974          * Then we bump the generation number so any cached values reinspect
1975          * the dce_t.
1976          */
1977         dce_increment_generation(dce);
1978         dce_refrele(dce);
1979 }
1980 
1981 /*
1982  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1983  * calls this function.
1984  */
1985 static mblk_t *
1986 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1987 {
1988         int length;
1989 
1990         ASSERT(mp->b_datap->db_type == M_DATA);
1991 
1992         /* icmp_inbound_v4 has already pulled up the whole error packet */
1993         ASSERT(mp->b_cont == NULL);
1994 
1995         /*
1996          * The length that we want to overlay is the inner header
1997          * and what follows it.
1998          */
1999         length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2000 
2001         /*
2002          * Overlay the inner header and whatever follows it over the
2003          * outer header.
2004          */
2005         bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2006 
2007         /* Adjust for what we removed */
2008         mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2009         return (mp);
2010 }
2011 
2012 /*
2013  * Try to pass the ICMP message upstream in case the ULP cares.
2014  *
2015  * If the packet that caused the ICMP error is secure, we send
2016  * it to AH/ESP to make sure that the attached packet has a
2017  * valid association. ipha in the code below points to the
2018  * IP header of the packet that caused the error.
2019  *
2020  * For IPsec cases, we let the next-layer-up (which has access to
2021  * cached policy on the conn_t, or can query the SPD directly)
2022  * subtract out any IPsec overhead if they must.  We therefore make no
2023  * adjustments here for IPsec overhead.
2024  *
2025  * IFN could have been generated locally or by some router.
2026  *
2027  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2028  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2029  *          This happens because IP adjusted its value of MTU on an
2030  *          earlier IFN message and could not tell the upper layer,
2031  *          the new adjusted value of MTU e.g. Packet was encrypted
2032  *          or there was not enough information to fanout to upper
2033  *          layers. Thus on the next outbound datagram, ire_send_wire
2034  *          generates the IFN, where IPsec processing has *not* been
2035  *          done.
2036  *
2037  *          Note that we retain ixa_fragsize across IPsec thus once
2038  *          we have picking ixa_fragsize and entered ipsec_out_process we do
2039  *          no change the fragsize even if the path MTU changes before
2040  *          we reach ip_output_post_ipsec.
2041  *
2042  *          In the local case, IRAF_LOOPBACK will be set indicating
2043  *          that IFN was generated locally.
2044  *
2045  * ROUTER : IFN could be secure or non-secure.
2046  *
2047  *          * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2048  *            packet in error has AH/ESP headers to validate the AH/ESP
2049  *            headers. AH/ESP will verify whether there is a valid SA or
2050  *            not and send it back. We will fanout again if we have more
2051  *            data in the packet.
2052  *
2053  *            If the packet in error does not have AH/ESP, we handle it
2054  *            like any other case.
2055  *
2056  *          * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2057  *            up to AH/ESP for validation. AH/ESP will verify whether there is a
2058  *            valid SA or not and send it back. We will fanout again if
2059  *            we have more data in the packet.
2060  *
2061  *            If the packet in error does not have AH/ESP, we handle it
2062  *            like any other case.
2063  *
2064  * The caller must have called icmp_inbound_verify_v4.
2065  */
2066 static void
2067 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2068 {
2069         uint16_t        *up;    /* Pointer to ports in ULP header */
2070         uint32_t        ports;  /* reversed ports for fanout */
2071         ipha_t          ripha;  /* With reversed addresses */
2072         ipha_t          *ipha;  /* Inner IP header */
2073         uint_t          hdr_length; /* Inner IP header length */
2074         tcpha_t         *tcpha;
2075         conn_t          *connp;
2076         ill_t           *ill = ira->ira_ill;
2077         ip_stack_t      *ipst = ill->ill_ipst;
2078         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
2079         ill_t           *rill = ira->ira_rill;
2080 
2081         /* Caller already pulled up everything. */
2082         ipha = (ipha_t *)&icmph[1];
2083         ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2084         ASSERT(mp->b_cont == NULL);
2085 
2086         hdr_length = IPH_HDR_LENGTH(ipha);
2087         ira->ira_protocol = ipha->ipha_protocol;
2088 
2089         /*
2090          * We need a separate IP header with the source and destination
2091          * addresses reversed to do fanout/classification because the ipha in
2092          * the ICMP error is in the form we sent it out.
2093          */
2094         ripha.ipha_src = ipha->ipha_dst;
2095         ripha.ipha_dst = ipha->ipha_src;
2096         ripha.ipha_protocol = ipha->ipha_protocol;
2097         ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2098 
2099         ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2100             ripha.ipha_protocol, ntohl(ipha->ipha_src),
2101             ntohl(ipha->ipha_dst),
2102             icmph->icmph_type, icmph->icmph_code));
2103 
2104         switch (ipha->ipha_protocol) {
2105         case IPPROTO_UDP:
2106                 up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2107 
2108                 /* Attempt to find a client stream based on port. */
2109                 ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2110                     ntohs(up[0]), ntohs(up[1])));
2111 
2112                 /* Note that we send error to all matches. */
2113                 ira->ira_flags |= IRAF_ICMP_ERROR;
2114                 ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2115                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2116                 return;
2117 
2118         case IPPROTO_TCP:
2119                 /*
2120                  * Find a TCP client stream for this packet.
2121                  * Note that we do a reverse lookup since the header is
2122                  * in the form we sent it out.
2123                  */
2124                 tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2125                 connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2126                     ipst);
2127                 if (connp == NULL)
2128                         goto discard_pkt;
2129 
2130                 if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2131                     (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2132                         mp = ipsec_check_inbound_policy(mp, connp,
2133                             ipha, NULL, ira);
2134                         if (mp == NULL) {
2135                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2136                                 /* Note that mp is NULL */
2137                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
2138                                 CONN_DEC_REF(connp);
2139                                 return;
2140                         }
2141                 }
2142 
2143                 ira->ira_flags |= IRAF_ICMP_ERROR;
2144                 ira->ira_ill = ira->ira_rill = NULL;
2145                 if (IPCL_IS_TCP(connp)) {
2146                         SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2147                             connp->conn_recvicmp, connp, ira, SQ_FILL,
2148                             SQTAG_TCP_INPUT_ICMP_ERR);
2149                 } else {
2150                         /* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2151                         (connp->conn_recv)(connp, mp, NULL, ira);
2152                         CONN_DEC_REF(connp);
2153                 }
2154                 ira->ira_ill = ill;
2155                 ira->ira_rill = rill;
2156                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2157                 return;
2158 
2159         case IPPROTO_SCTP:
2160                 up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2161                 /* Find a SCTP client stream for this packet. */
2162                 ((uint16_t *)&ports)[0] = up[1];
2163                 ((uint16_t *)&ports)[1] = up[0];
2164 
2165                 ira->ira_flags |= IRAF_ICMP_ERROR;
2166                 ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2167                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2168                 return;
2169 
2170         case IPPROTO_ESP:
2171         case IPPROTO_AH:
2172                 if (!ipsec_loaded(ipss)) {
2173                         ip_proto_not_sup(mp, ira);
2174                         return;
2175                 }
2176 
2177                 if (ipha->ipha_protocol == IPPROTO_ESP)
2178                         mp = ipsecesp_icmp_error(mp, ira);
2179                 else
2180                         mp = ipsecah_icmp_error(mp, ira);
2181                 if (mp == NULL)
2182                         return;
2183 
2184                 /* Just in case ipsec didn't preserve the NULL b_cont */
2185                 if (mp->b_cont != NULL) {
2186                         if (!pullupmsg(mp, -1))
2187                                 goto discard_pkt;
2188                 }
2189 
2190                 /*
2191                  * Note that ira_pktlen and ira_ip_hdr_length are no longer
2192                  * correct, but we don't use them any more here.
2193                  *
2194                  * If succesful, the mp has been modified to not include
2195                  * the ESP/AH header so we can fanout to the ULP's icmp
2196                  * error handler.
2197                  */
2198                 if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2199                         goto truncated;
2200 
2201                 /* Verify the modified message before any further processes. */
2202                 ipha = (ipha_t *)mp->b_rptr;
2203                 hdr_length = IPH_HDR_LENGTH(ipha);
2204                 icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2205                 if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2206                         freemsg(mp);
2207                         return;
2208                 }
2209 
2210                 icmp_inbound_error_fanout_v4(mp, icmph, ira);
2211                 return;
2212 
2213         case IPPROTO_ENCAP: {
2214                 /* Look for self-encapsulated packets that caused an error */
2215                 ipha_t *in_ipha;
2216 
2217                 /*
2218                  * Caller has verified that length has to be
2219                  * at least the size of IP header.
2220                  */
2221                 ASSERT(hdr_length >= sizeof (ipha_t));
2222                 /*
2223                  * Check the sanity of the inner IP header like
2224                  * we did for the outer header.
2225                  */
2226                 in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2227                 if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2228                         goto discard_pkt;
2229                 }
2230                 if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2231                         goto discard_pkt;
2232                 }
2233                 /* Check for Self-encapsulated tunnels */
2234                 if (in_ipha->ipha_src == ipha->ipha_src &&
2235                     in_ipha->ipha_dst == ipha->ipha_dst) {
2236 
2237                         mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2238                             in_ipha);
2239                         if (mp == NULL)
2240                                 goto discard_pkt;
2241 
2242                         /*
2243                          * Just in case self_encap didn't preserve the NULL
2244                          * b_cont
2245                          */
2246                         if (mp->b_cont != NULL) {
2247                                 if (!pullupmsg(mp, -1))
2248                                         goto discard_pkt;
2249                         }
2250                         /*
2251                          * Note that ira_pktlen and ira_ip_hdr_length are no
2252                          * longer correct, but we don't use them any more here.
2253                          */
2254                         if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2255                                 goto truncated;
2256 
2257                         /*
2258                          * Verify the modified message before any further
2259                          * processes.
2260                          */
2261                         ipha = (ipha_t *)mp->b_rptr;
2262                         hdr_length = IPH_HDR_LENGTH(ipha);
2263                         icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2264                         if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2265                                 freemsg(mp);
2266                                 return;
2267                         }
2268 
2269                         /*
2270                          * The packet in error is self-encapsualted.
2271                          * And we are finding it further encapsulated
2272                          * which we could not have possibly generated.
2273                          */
2274                         if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2275                                 goto discard_pkt;
2276                         }
2277                         icmp_inbound_error_fanout_v4(mp, icmph, ira);
2278                         return;
2279                 }
2280                 /* No self-encapsulated */
2281         }
2282         /* FALLTHROUGH */
2283         case IPPROTO_IPV6:
2284                 if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2285                     &ripha.ipha_dst, ipst)) != NULL) {
2286                         ira->ira_flags |= IRAF_ICMP_ERROR;
2287                         connp->conn_recvicmp(connp, mp, NULL, ira);
2288                         CONN_DEC_REF(connp);
2289                         ira->ira_flags &= ~IRAF_ICMP_ERROR;
2290                         return;
2291                 }
2292                 /*
2293                  * No IP tunnel is interested, fallthrough and see
2294                  * if a raw socket will want it.
2295                  */
2296                 /* FALLTHROUGH */
2297         default:
2298                 ira->ira_flags |= IRAF_ICMP_ERROR;
2299                 ip_fanout_proto_v4(mp, &ripha, ira);
2300                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2301                 return;
2302         }
2303         /* NOTREACHED */
2304 discard_pkt:
2305         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2306         ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2307         ip_drop_input("ipIfStatsInDiscards", mp, ill);
2308         freemsg(mp);
2309         return;
2310 
2311 truncated:
2312         /* We pulled up everthing already. Must be truncated */
2313         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2314         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2315         freemsg(mp);
2316 }
2317 
2318 /*
2319  * Common IP options parser.
2320  *
2321  * Setup routine: fill in *optp with options-parsing state, then
2322  * tail-call ipoptp_next to return the first option.
2323  */
2324 uint8_t
2325 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2326 {
2327         uint32_t totallen; /* total length of all options */
2328 
2329         totallen = ipha->ipha_version_and_hdr_length -
2330             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2331         totallen <<= 2;
2332         optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2333         optp->ipoptp_end = optp->ipoptp_next + totallen;
2334         optp->ipoptp_flags = 0;
2335         return (ipoptp_next(optp));
2336 }
2337 
2338 /* Like above but without an ipha_t */
2339 uint8_t
2340 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2341 {
2342         optp->ipoptp_next = opt;
2343         optp->ipoptp_end = optp->ipoptp_next + totallen;
2344         optp->ipoptp_flags = 0;
2345         return (ipoptp_next(optp));
2346 }
2347 
2348 /*
2349  * Common IP options parser: extract next option.
2350  */
2351 uint8_t
2352 ipoptp_next(ipoptp_t *optp)
2353 {
2354         uint8_t *end = optp->ipoptp_end;
2355         uint8_t *cur = optp->ipoptp_next;
2356         uint8_t opt, len, pointer;
2357 
2358         /*
2359          * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2360          * has been corrupted.
2361          */
2362         ASSERT(cur <= end);
2363 
2364         if (cur == end)
2365                 return (IPOPT_EOL);
2366 
2367         opt = cur[IPOPT_OPTVAL];
2368 
2369         /*
2370          * Skip any NOP options.
2371          */
2372         while (opt == IPOPT_NOP) {
2373                 cur++;
2374                 if (cur == end)
2375                         return (IPOPT_EOL);
2376                 opt = cur[IPOPT_OPTVAL];
2377         }
2378 
2379         if (opt == IPOPT_EOL)
2380                 return (IPOPT_EOL);
2381 
2382         /*
2383          * Option requiring a length.
2384          */
2385         if ((cur + 1) >= end) {
2386                 optp->ipoptp_flags |= IPOPTP_ERROR;
2387                 return (IPOPT_EOL);
2388         }
2389         len = cur[IPOPT_OLEN];
2390         if (len < 2) {
2391                 optp->ipoptp_flags |= IPOPTP_ERROR;
2392                 return (IPOPT_EOL);
2393         }
2394         optp->ipoptp_cur = cur;
2395         optp->ipoptp_len = len;
2396         optp->ipoptp_next = cur + len;
2397         if (cur + len > end) {
2398                 optp->ipoptp_flags |= IPOPTP_ERROR;
2399                 return (IPOPT_EOL);
2400         }
2401 
2402         /*
2403          * For the options which require a pointer field, make sure
2404          * its there, and make sure it points to either something
2405          * inside this option, or the end of the option.
2406          */
2407         switch (opt) {
2408         case IPOPT_RR:
2409         case IPOPT_TS:
2410         case IPOPT_LSRR:
2411         case IPOPT_SSRR:
2412                 if (len <= IPOPT_OFFSET) {
2413                         optp->ipoptp_flags |= IPOPTP_ERROR;
2414                         return (opt);
2415                 }
2416                 pointer = cur[IPOPT_OFFSET];
2417                 if (pointer - 1 > len) {
2418                         optp->ipoptp_flags |= IPOPTP_ERROR;
2419                         return (opt);
2420                 }
2421                 break;
2422         }
2423 
2424         /*
2425          * Sanity check the pointer field based on the type of the
2426          * option.
2427          */
2428         switch (opt) {
2429         case IPOPT_RR:
2430         case IPOPT_SSRR:
2431         case IPOPT_LSRR:
2432                 if (pointer < IPOPT_MINOFF_SR)
2433                         optp->ipoptp_flags |= IPOPTP_ERROR;
2434                 break;
2435         case IPOPT_TS:
2436                 if (pointer < IPOPT_MINOFF_IT)
2437                         optp->ipoptp_flags |= IPOPTP_ERROR;
2438                 /*
2439                  * Note that the Internet Timestamp option also
2440                  * contains two four bit fields (the Overflow field,
2441                  * and the Flag field), which follow the pointer
2442                  * field.  We don't need to check that these fields
2443                  * fall within the length of the option because this
2444                  * was implicitely done above.  We've checked that the
2445                  * pointer value is at least IPOPT_MINOFF_IT, and that
2446                  * it falls within the option.  Since IPOPT_MINOFF_IT >
2447                  * IPOPT_POS_OV_FLG, we don't need the explicit check.
2448                  */
2449                 ASSERT(len > IPOPT_POS_OV_FLG);
2450                 break;
2451         }
2452 
2453         return (opt);
2454 }
2455 
2456 /*
2457  * Use the outgoing IP header to create an IP_OPTIONS option the way
2458  * it was passed down from the application.
2459  *
2460  * This is compatible with BSD in that it returns
2461  * the reverse source route with the final destination
2462  * as the last entry. The first 4 bytes of the option
2463  * will contain the final destination.
2464  */
2465 int
2466 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2467 {
2468         ipoptp_t        opts;
2469         uchar_t         *opt;
2470         uint8_t         optval;
2471         uint8_t         optlen;
2472         uint32_t        len = 0;
2473         uchar_t         *buf1 = buf;
2474         uint32_t        totallen;
2475         ipaddr_t        dst;
2476         ip_pkt_t        *ipp = &connp->conn_xmit_ipp;
2477 
2478         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2479                 return (0);
2480 
2481         totallen = ipp->ipp_ipv4_options_len;
2482         if (totallen & 0x3)
2483                 return (0);
2484 
2485         buf += IP_ADDR_LEN;     /* Leave room for final destination */
2486         len += IP_ADDR_LEN;
2487         bzero(buf1, IP_ADDR_LEN);
2488 
2489         dst = connp->conn_faddr_v4;
2490 
2491         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2492             optval != IPOPT_EOL;
2493             optval = ipoptp_next(&opts)) {
2494                 int     off;
2495 
2496                 opt = opts.ipoptp_cur;
2497                 if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2498                         break;
2499                 }
2500                 optlen = opts.ipoptp_len;
2501 
2502                 switch (optval) {
2503                 case IPOPT_SSRR:
2504                 case IPOPT_LSRR:
2505 
2506                         /*
2507                          * Insert destination as the first entry in the source
2508                          * route and move down the entries on step.
2509                          * The last entry gets placed at buf1.
2510                          */
2511                         buf[IPOPT_OPTVAL] = optval;
2512                         buf[IPOPT_OLEN] = optlen;
2513                         buf[IPOPT_OFFSET] = optlen;
2514 
2515                         off = optlen - IP_ADDR_LEN;
2516                         if (off < 0) {
2517                                 /* No entries in source route */
2518                                 break;
2519                         }
2520                         /* Last entry in source route if not already set */
2521                         if (dst == INADDR_ANY)
2522                                 bcopy(opt + off, buf1, IP_ADDR_LEN);
2523                         off -= IP_ADDR_LEN;
2524 
2525                         while (off > 0) {
2526                                 bcopy(opt + off,
2527                                     buf + off + IP_ADDR_LEN,
2528                                     IP_ADDR_LEN);
2529                                 off -= IP_ADDR_LEN;
2530                         }
2531                         /* ipha_dst into first slot */
2532                         bcopy(&dst, buf + off + IP_ADDR_LEN,
2533                             IP_ADDR_LEN);
2534                         buf += optlen;
2535                         len += optlen;
2536                         break;
2537 
2538                 default:
2539                         bcopy(opt, buf, optlen);
2540                         buf += optlen;
2541                         len += optlen;
2542                         break;
2543                 }
2544         }
2545 done:
2546         /* Pad the resulting options */
2547         while (len & 0x3) {
2548                 *buf++ = IPOPT_EOL;
2549                 len++;
2550         }
2551         return (len);
2552 }
2553 
2554 /*
2555  * Update any record route or timestamp options to include this host.
2556  * Reverse any source route option.
2557  * This routine assumes that the options are well formed i.e. that they
2558  * have already been checked.
2559  */
2560 static void
2561 icmp_options_update(ipha_t *ipha)
2562 {
2563         ipoptp_t        opts;
2564         uchar_t         *opt;
2565         uint8_t         optval;
2566         ipaddr_t        src;            /* Our local address */
2567         ipaddr_t        dst;
2568 
2569         ip2dbg(("icmp_options_update\n"));
2570         src = ipha->ipha_src;
2571         dst = ipha->ipha_dst;
2572 
2573         for (optval = ipoptp_first(&opts, ipha);
2574             optval != IPOPT_EOL;
2575             optval = ipoptp_next(&opts)) {
2576                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2577                 opt = opts.ipoptp_cur;
2578                 ip2dbg(("icmp_options_update: opt %d, len %d\n",
2579                     optval, opts.ipoptp_len));
2580                 switch (optval) {
2581                         int off1, off2;
2582                 case IPOPT_SSRR:
2583                 case IPOPT_LSRR:
2584                         /*
2585                          * Reverse the source route.  The first entry
2586                          * should be the next to last one in the current
2587                          * source route (the last entry is our address).
2588                          * The last entry should be the final destination.
2589                          */
2590                         off1 = IPOPT_MINOFF_SR - 1;
2591                         off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2592                         if (off2 < 0) {
2593                                 /* No entries in source route */
2594                                 ip1dbg((
2595                                     "icmp_options_update: bad src route\n"));
2596                                 break;
2597                         }
2598                         bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2599                         bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2600                         bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2601                         off2 -= IP_ADDR_LEN;
2602 
2603                         while (off1 < off2) {
2604                                 bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2605                                 bcopy((char *)opt + off2, (char *)opt + off1,
2606                                     IP_ADDR_LEN);
2607                                 bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2608                                 off1 += IP_ADDR_LEN;
2609                                 off2 -= IP_ADDR_LEN;
2610                         }
2611                         opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2612                         break;
2613                 }
2614         }
2615 }
2616 
2617 /*
2618  * Process received ICMP Redirect messages.
2619  * Assumes the caller has verified that the headers are in the pulled up mblk.
2620  * Consumes mp.
2621  */
2622 static void
2623 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2624 {
2625         ire_t           *ire, *nire;
2626         ire_t           *prev_ire;
2627         ipaddr_t        src, dst, gateway;
2628         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2629         ipha_t          *inner_ipha;    /* Inner IP header */
2630 
2631         /* Caller already pulled up everything. */
2632         inner_ipha = (ipha_t *)&icmph[1];
2633         src = ipha->ipha_src;
2634         dst = inner_ipha->ipha_dst;
2635         gateway = icmph->icmph_rd_gateway;
2636         /* Make sure the new gateway is reachable somehow. */
2637         ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2638             ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2639         /*
2640          * Make sure we had a route for the dest in question and that
2641          * that route was pointing to the old gateway (the source of the
2642          * redirect packet.)
2643          * We do longest match and then compare ire_gateway_addr below.
2644          */
2645         prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2646             NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2647         /*
2648          * Check that
2649          *      the redirect was not from ourselves
2650          *      the new gateway and the old gateway are directly reachable
2651          */
2652         if (prev_ire == NULL || ire == NULL ||
2653             (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2654             (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2655             !(ire->ire_type & IRE_IF_ALL) ||
2656             prev_ire->ire_gateway_addr != src) {
2657                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2658                 ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2659                 freemsg(mp);
2660                 if (ire != NULL)
2661                         ire_refrele(ire);
2662                 if (prev_ire != NULL)
2663                         ire_refrele(prev_ire);
2664                 return;
2665         }
2666 
2667         ire_refrele(prev_ire);
2668         ire_refrele(ire);
2669 
2670         /*
2671          * TODO: more precise handling for cases 0, 2, 3, the latter two
2672          * require TOS routing
2673          */
2674         switch (icmph->icmph_code) {
2675         case 0:
2676         case 1:
2677                 /* TODO: TOS specificity for cases 2 and 3 */
2678         case 2:
2679         case 3:
2680                 break;
2681         default:
2682                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2683                 ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2684                 freemsg(mp);
2685                 return;
2686         }
2687         /*
2688          * Create a Route Association.  This will allow us to remember that
2689          * someone we believe told us to use the particular gateway.
2690          */
2691         ire = ire_create(
2692             (uchar_t *)&dst,                        /* dest addr */
2693             (uchar_t *)&ip_g_all_ones,              /* mask */
2694             (uchar_t *)&gateway,            /* gateway addr */
2695             IRE_HOST,
2696             NULL,                               /* ill */
2697             ALL_ZONES,
2698             (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2699             NULL,                               /* tsol_gc_t */
2700             ipst);
2701 
2702         if (ire == NULL) {
2703                 freemsg(mp);
2704                 return;
2705         }
2706         nire = ire_add(ire);
2707         /* Check if it was a duplicate entry */
2708         if (nire != NULL && nire != ire) {
2709                 ASSERT(nire->ire_identical_ref > 1);
2710                 ire_delete(nire);
2711                 ire_refrele(nire);
2712                 nire = NULL;
2713         }
2714         ire = nire;
2715         if (ire != NULL) {
2716                 ire_refrele(ire);               /* Held in ire_add */
2717 
2718                 /* tell routing sockets that we received a redirect */
2719                 ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2720                     (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2721                     (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2722         }
2723 
2724         /*
2725          * Delete any existing IRE_HOST type redirect ires for this destination.
2726          * This together with the added IRE has the effect of
2727          * modifying an existing redirect.
2728          */
2729         prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2730             ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2731         if (prev_ire != NULL) {
2732                 if (prev_ire ->ire_flags & RTF_DYNAMIC)
2733                         ire_delete(prev_ire);
2734                 ire_refrele(prev_ire);
2735         }
2736 
2737         freemsg(mp);
2738 }
2739 
2740 /*
2741  * Generate an ICMP parameter problem message.
2742  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2743  * constructed by the caller.
2744  */
2745 static void
2746 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2747 {
2748         icmph_t icmph;
2749         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2750 
2751         mp = icmp_pkt_err_ok(mp, ira);
2752         if (mp == NULL)
2753                 return;
2754 
2755         bzero(&icmph, sizeof (icmph_t));
2756         icmph.icmph_type = ICMP_PARAM_PROBLEM;
2757         icmph.icmph_pp_ptr = ptr;
2758         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2759         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2760 }
2761 
2762 /*
2763  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2764  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2765  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2766  * an icmp error packet can be sent.
2767  * Assigns an appropriate source address to the packet. If ipha_dst is
2768  * one of our addresses use it for source. Otherwise let ip_output_simple
2769  * pick the source address.
2770  */
2771 static void
2772 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2773 {
2774         ipaddr_t dst;
2775         icmph_t *icmph;
2776         ipha_t  *ipha;
2777         uint_t  len_needed;
2778         size_t  msg_len;
2779         mblk_t  *mp1;
2780         ipaddr_t src;
2781         ire_t   *ire;
2782         ip_xmit_attr_t ixas;
2783         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2784 
2785         ipha = (ipha_t *)mp->b_rptr;
2786 
2787         bzero(&ixas, sizeof (ixas));
2788         ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2789         ixas.ixa_zoneid = ira->ira_zoneid;
2790         ixas.ixa_ifindex = 0;
2791         ixas.ixa_ipst = ipst;
2792         ixas.ixa_cred = kcred;
2793         ixas.ixa_cpid = NOPID;
2794         ixas.ixa_tsl = ira->ira_tsl; /* Behave as a multi-level responder */
2795         ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2796 
2797         if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2798                 /*
2799                  * Apply IPsec based on how IPsec was applied to
2800                  * the packet that had the error.
2801                  *
2802                  * If it was an outbound packet that caused the ICMP
2803                  * error, then the caller will have setup the IRA
2804                  * appropriately.
2805                  */
2806                 if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2807                         BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2808                         /* Note: mp already consumed and ip_drop_packet done */
2809                         return;
2810                 }
2811         } else {
2812                 /*
2813                  * This is in clear. The icmp message we are building
2814                  * here should go out in clear, independent of our policy.
2815                  */
2816                 ixas.ixa_flags |= IXAF_NO_IPSEC;
2817         }
2818 
2819         /* Remember our eventual destination */
2820         dst = ipha->ipha_src;
2821 
2822         /*
2823          * If the packet was for one of our unicast addresses, make
2824          * sure we respond with that as the source. Otherwise
2825          * have ip_output_simple pick the source address.
2826          */
2827         ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2828             (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2829             MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2830         if (ire != NULL) {
2831                 ire_refrele(ire);
2832                 src = ipha->ipha_dst;
2833         } else {
2834                 src = INADDR_ANY;
2835                 ixas.ixa_flags |= IXAF_SET_SOURCE;
2836         }
2837 
2838         /*
2839          * Check if we can send back more then 8 bytes in addition to
2840          * the IP header.  We try to send 64 bytes of data and the internal
2841          * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2842          */
2843         len_needed = IPH_HDR_LENGTH(ipha);
2844         if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2845             ipha->ipha_protocol == IPPROTO_IPV6) {
2846                 if (!pullupmsg(mp, -1)) {
2847                         BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2848                         ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2849                         freemsg(mp);
2850                         return;
2851                 }
2852                 ipha = (ipha_t *)mp->b_rptr;
2853 
2854                 if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2855                         len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2856                             len_needed));
2857                 } else {
2858                         ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2859 
2860                         ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2861                         len_needed += ip_hdr_length_v6(mp, ip6h);
2862                 }
2863         }
2864         len_needed += ipst->ips_ip_icmp_return;
2865         msg_len = msgdsize(mp);
2866         if (msg_len > len_needed) {
2867                 (void) adjmsg(mp, len_needed - msg_len);
2868                 msg_len = len_needed;
2869         }
2870         mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2871         if (mp1 == NULL) {
2872                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2873                 freemsg(mp);
2874                 return;
2875         }
2876         mp1->b_cont = mp;
2877         mp = mp1;
2878 
2879         /*
2880          * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2881          * node generates be accepted in peace by all on-host destinations.
2882          * If we do NOT assume that all on-host destinations trust
2883          * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2884          * (Look for IXAF_TRUSTED_ICMP).
2885          */
2886         ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2887 
2888         ipha = (ipha_t *)mp->b_rptr;
2889         mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2890         *ipha = icmp_ipha;
2891         ipha->ipha_src = src;
2892         ipha->ipha_dst = dst;
2893         ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2894         msg_len += sizeof (icmp_ipha) + len;
2895         if (msg_len > IP_MAXPACKET) {
2896                 (void) adjmsg(mp, IP_MAXPACKET - msg_len);
2897                 msg_len = IP_MAXPACKET;
2898         }
2899         ipha->ipha_length = htons((uint16_t)msg_len);
2900         icmph = (icmph_t *)&ipha[1];
2901         bcopy(stuff, icmph, len);
2902         icmph->icmph_checksum = 0;
2903         icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2904         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2905 
2906         (void) ip_output_simple(mp, &ixas);
2907         ixa_cleanup(&ixas);
2908 }
2909 
2910 /*
2911  * Determine if an ICMP error packet can be sent given the rate limit.
2912  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2913  * in milliseconds) and a burst size. Burst size number of packets can
2914  * be sent arbitrarely closely spaced.
2915  * The state is tracked using two variables to implement an approximate
2916  * token bucket filter:
2917  *      icmp_pkt_err_last - lbolt value when the last burst started
2918  *      icmp_pkt_err_sent - number of packets sent in current burst
2919  */
2920 boolean_t
2921 icmp_err_rate_limit(ip_stack_t *ipst)
2922 {
2923         clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2924         uint_t refilled; /* Number of packets refilled in tbf since last */
2925         /* Guard against changes by loading into local variable */
2926         uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2927 
2928         if (err_interval == 0)
2929                 return (B_FALSE);
2930 
2931         if (ipst->ips_icmp_pkt_err_last > now) {
2932                 /* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2933                 ipst->ips_icmp_pkt_err_last = 0;
2934                 ipst->ips_icmp_pkt_err_sent = 0;
2935         }
2936         /*
2937          * If we are in a burst update the token bucket filter.
2938          * Update the "last" time to be close to "now" but make sure
2939          * we don't loose precision.
2940          */
2941         if (ipst->ips_icmp_pkt_err_sent != 0) {
2942                 refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2943                 if (refilled > ipst->ips_icmp_pkt_err_sent) {
2944                         ipst->ips_icmp_pkt_err_sent = 0;
2945                 } else {
2946                         ipst->ips_icmp_pkt_err_sent -= refilled;
2947                         ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2948                 }
2949         }
2950         if (ipst->ips_icmp_pkt_err_sent == 0) {
2951                 /* Start of new burst */
2952                 ipst->ips_icmp_pkt_err_last = now;
2953         }
2954         if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2955                 ipst->ips_icmp_pkt_err_sent++;
2956                 ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2957                     ipst->ips_icmp_pkt_err_sent));
2958                 return (B_FALSE);
2959         }
2960         ip1dbg(("icmp_err_rate_limit: dropped\n"));
2961         return (B_TRUE);
2962 }
2963 
2964 /*
2965  * Check if it is ok to send an IPv4 ICMP error packet in
2966  * response to the IPv4 packet in mp.
2967  * Free the message and return null if no
2968  * ICMP error packet should be sent.
2969  */
2970 static mblk_t *
2971 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2972 {
2973         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2974         icmph_t *icmph;
2975         ipha_t  *ipha;
2976         uint_t  len_needed;
2977 
2978         if (!mp)
2979                 return (NULL);
2980         ipha = (ipha_t *)mp->b_rptr;
2981         if (ip_csum_hdr(ipha)) {
2982                 BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2983                 ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2984                 freemsg(mp);
2985                 return (NULL);
2986         }
2987         if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2988             ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2989             CLASSD(ipha->ipha_dst) ||
2990             CLASSD(ipha->ipha_src) ||
2991             (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2992                 /* Note: only errors to the fragment with offset 0 */
2993                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2994                 freemsg(mp);
2995                 return (NULL);
2996         }
2997         if (ipha->ipha_protocol == IPPROTO_ICMP) {
2998                 /*
2999                  * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3000                  * errors in response to any ICMP errors.
3001                  */
3002                 len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3003                 if (mp->b_wptr - mp->b_rptr < len_needed) {
3004                         if (!pullupmsg(mp, len_needed)) {
3005                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3006                                 freemsg(mp);
3007                                 return (NULL);
3008                         }
3009                         ipha = (ipha_t *)mp->b_rptr;
3010                 }
3011                 icmph = (icmph_t *)
3012                     (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3013                 switch (icmph->icmph_type) {
3014                 case ICMP_DEST_UNREACHABLE:
3015                 case ICMP_SOURCE_QUENCH:
3016                 case ICMP_TIME_EXCEEDED:
3017                 case ICMP_PARAM_PROBLEM:
3018                 case ICMP_REDIRECT:
3019                         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3020                         freemsg(mp);
3021                         return (NULL);
3022                 default:
3023                         break;
3024                 }
3025         }
3026         /*
3027          * If this is a labeled system, then check to see if we're allowed to
3028          * send a response to this particular sender.  If not, then just drop.
3029          */
3030         if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3031                 ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3032                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3033                 freemsg(mp);
3034                 return (NULL);
3035         }
3036         if (icmp_err_rate_limit(ipst)) {
3037                 /*
3038                  * Only send ICMP error packets every so often.
3039                  * This should be done on a per port/source basis,
3040                  * but for now this will suffice.
3041                  */
3042                 freemsg(mp);
3043                 return (NULL);
3044         }
3045         return (mp);
3046 }
3047 
3048 /*
3049  * Called when a packet was sent out the same link that it arrived on.
3050  * Check if it is ok to send a redirect and then send it.
3051  */
3052 void
3053 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3054     ip_recv_attr_t *ira)
3055 {
3056         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
3057         ipaddr_t        src, nhop;
3058         mblk_t          *mp1;
3059         ire_t           *nhop_ire;
3060 
3061         /*
3062          * Check the source address to see if it originated
3063          * on the same logical subnet it is going back out on.
3064          * If so, we should be able to send it a redirect.
3065          * Avoid sending a redirect if the destination
3066          * is directly connected (i.e., we matched an IRE_ONLINK),
3067          * or if the packet was source routed out this interface.
3068          *
3069          * We avoid sending a redirect if the
3070          * destination is directly connected
3071          * because it is possible that multiple
3072          * IP subnets may have been configured on
3073          * the link, and the source may not
3074          * be on the same subnet as ip destination,
3075          * even though they are on the same
3076          * physical link.
3077          */
3078         if ((ire->ire_type & IRE_ONLINK) ||
3079             ip_source_routed(ipha, ipst))
3080                 return;
3081 
3082         nhop_ire = ire_nexthop(ire);
3083         if (nhop_ire == NULL)
3084                 return;
3085 
3086         nhop = nhop_ire->ire_addr;
3087 
3088         if (nhop_ire->ire_type & IRE_IF_CLONE) {
3089                 ire_t   *ire2;
3090 
3091                 /* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3092                 mutex_enter(&nhop_ire->ire_lock);
3093                 ire2 = nhop_ire->ire_dep_parent;
3094                 if (ire2 != NULL)
3095                         ire_refhold(ire2);
3096                 mutex_exit(&nhop_ire->ire_lock);
3097                 ire_refrele(nhop_ire);
3098                 nhop_ire = ire2;
3099         }
3100         if (nhop_ire == NULL)
3101                 return;
3102 
3103         ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3104 
3105         src = ipha->ipha_src;
3106 
3107         /*
3108          * We look at the interface ire for the nexthop,
3109          * to see if ipha_src is in the same subnet
3110          * as the nexthop.
3111          */
3112         if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3113                 /*
3114                  * The source is directly connected.
3115                  */
3116                 mp1 = copymsg(mp);
3117                 if (mp1 != NULL) {
3118                         icmp_send_redirect(mp1, nhop, ira);
3119                 }
3120         }
3121         ire_refrele(nhop_ire);
3122 }
3123 
3124 /*
3125  * Generate an ICMP redirect message.
3126  */
3127 static void
3128 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3129 {
3130         icmph_t icmph;
3131         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3132 
3133         mp = icmp_pkt_err_ok(mp, ira);
3134         if (mp == NULL)
3135                 return;
3136 
3137         bzero(&icmph, sizeof (icmph_t));
3138         icmph.icmph_type = ICMP_REDIRECT;
3139         icmph.icmph_code = 1;
3140         icmph.icmph_rd_gateway = gateway;
3141         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3142         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3143 }
3144 
3145 /*
3146  * Generate an ICMP time exceeded message.
3147  */
3148 void
3149 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3150 {
3151         icmph_t icmph;
3152         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3153 
3154         mp = icmp_pkt_err_ok(mp, ira);
3155         if (mp == NULL)
3156                 return;
3157 
3158         bzero(&icmph, sizeof (icmph_t));
3159         icmph.icmph_type = ICMP_TIME_EXCEEDED;
3160         icmph.icmph_code = code;
3161         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3162         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3163 }
3164 
3165 /*
3166  * Generate an ICMP unreachable message.
3167  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3168  * constructed by the caller.
3169  */
3170 void
3171 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3172 {
3173         icmph_t icmph;
3174         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3175 
3176         mp = icmp_pkt_err_ok(mp, ira);
3177         if (mp == NULL)
3178                 return;
3179 
3180         bzero(&icmph, sizeof (icmph_t));
3181         icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3182         icmph.icmph_code = code;
3183         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3184         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3185 }
3186 
3187 /*
3188  * Latch in the IPsec state for a stream based the policy in the listener
3189  * and the actions in the ip_recv_attr_t.
3190  * Called directly from TCP and SCTP.
3191  */
3192 boolean_t
3193 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3194 {
3195         ASSERT(lconnp->conn_policy != NULL);
3196         ASSERT(connp->conn_policy == NULL);
3197 
3198         IPPH_REFHOLD(lconnp->conn_policy);
3199         connp->conn_policy = lconnp->conn_policy;
3200 
3201         if (ira->ira_ipsec_action != NULL) {
3202                 if (connp->conn_latch == NULL) {
3203                         connp->conn_latch = iplatch_create();
3204                         if (connp->conn_latch == NULL)
3205                                 return (B_FALSE);
3206                 }
3207                 ipsec_latch_inbound(connp, ira);
3208         }
3209         return (B_TRUE);
3210 }
3211 
3212 /*
3213  * Verify whether or not the IP address is a valid local address.
3214  * Could be a unicast, including one for a down interface.
3215  * If allow_mcbc then a multicast or broadcast address is also
3216  * acceptable.
3217  *
3218  * In the case of a broadcast/multicast address, however, the
3219  * upper protocol is expected to reset the src address
3220  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3221  * no packets are emitted with broadcast/multicast address as
3222  * source address (that violates hosts requirements RFC 1122)
3223  * The addresses valid for bind are:
3224  *      (1) - INADDR_ANY (0)
3225  *      (2) - IP address of an UP interface
3226  *      (3) - IP address of a DOWN interface
3227  *      (4) - valid local IP broadcast addresses. In this case
3228  *      the conn will only receive packets destined to
3229  *      the specified broadcast address.
3230  *      (5) - a multicast address. In this case
3231  *      the conn will only receive packets destined to
3232  *      the specified multicast address. Note: the
3233  *      application still has to issue an
3234  *      IP_ADD_MEMBERSHIP socket option.
3235  *
3236  * In all the above cases, the bound address must be valid in the current zone.
3237  * When the address is loopback, multicast or broadcast, there might be many
3238  * matching IREs so bind has to look up based on the zone.
3239  */
3240 ip_laddr_t
3241 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3242     ip_stack_t *ipst, boolean_t allow_mcbc)
3243 {
3244         ire_t *src_ire;
3245 
3246         ASSERT(src_addr != INADDR_ANY);
3247 
3248         src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3249             NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3250 
3251         /*
3252          * If an address other than in6addr_any is requested,
3253          * we verify that it is a valid address for bind
3254          * Note: Following code is in if-else-if form for
3255          * readability compared to a condition check.
3256          */
3257         if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3258                 /*
3259                  * (2) Bind to address of local UP interface
3260                  */
3261                 ire_refrele(src_ire);
3262                 return (IPVL_UNICAST_UP);
3263         } else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3264                 /*
3265                  * (4) Bind to broadcast address
3266                  */
3267                 ire_refrele(src_ire);
3268                 if (allow_mcbc)
3269                         return (IPVL_BCAST);
3270                 else
3271                         return (IPVL_BAD);
3272         } else if (CLASSD(src_addr)) {
3273                 /* (5) bind to multicast address. */
3274                 if (src_ire != NULL)
3275                         ire_refrele(src_ire);
3276 
3277                 if (allow_mcbc)
3278                         return (IPVL_MCAST);
3279                 else
3280                         return (IPVL_BAD);
3281         } else {
3282                 ipif_t *ipif;
3283 
3284                 /*
3285                  * (3) Bind to address of local DOWN interface?
3286                  * (ipif_lookup_addr() looks up all interfaces
3287                  * but we do not get here for UP interfaces
3288                  * - case (2) above)
3289                  */
3290                 if (src_ire != NULL)
3291                         ire_refrele(src_ire);
3292 
3293                 ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3294                 if (ipif == NULL)
3295                         return (IPVL_BAD);
3296 
3297                 /* Not a useful source? */
3298                 if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3299                         ipif_refrele(ipif);
3300                         return (IPVL_BAD);
3301                 }
3302                 ipif_refrele(ipif);
3303                 return (IPVL_UNICAST_DOWN);
3304         }
3305 }
3306 
3307 /*
3308  * Insert in the bind fanout for IPv4 and IPv6.
3309  * The caller should already have used ip_laddr_verify_v*() before calling
3310  * this.
3311  */
3312 int
3313 ip_laddr_fanout_insert(conn_t *connp)
3314 {
3315         int             error;
3316 
3317         /*
3318          * Allow setting new policies. For example, disconnects result
3319          * in us being called. As we would have set conn_policy_cached
3320          * to B_TRUE before, we should set it to B_FALSE, so that policy
3321          * can change after the disconnect.
3322          */
3323         connp->conn_policy_cached = B_FALSE;
3324 
3325         error = ipcl_bind_insert(connp);
3326         if (error != 0) {
3327                 if (connp->conn_anon_port) {
3328                         (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3329                             connp->conn_mlp_type, connp->conn_proto,
3330                             ntohs(connp->conn_lport), B_FALSE);
3331                 }
3332                 connp->conn_mlp_type = mlptSingle;
3333         }
3334         return (error);
3335 }
3336 
3337 /*
3338  * Verify that both the source and destination addresses are valid. If
3339  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3340  * i.e. have no route to it.  Protocols like TCP want to verify destination
3341  * reachability, while tunnels do not.
3342  *
3343  * Determine the route, the interface, and (optionally) the source address
3344  * to use to reach a given destination.
3345  * Note that we allow connect to broadcast and multicast addresses when
3346  * IPDF_ALLOW_MCBC is set.
3347  * first_hop and dst_addr are normally the same, but if source routing
3348  * they will differ; in that case the first_hop is what we'll use for the
3349  * routing lookup but the dce and label checks will be done on dst_addr,
3350  *
3351  * If uinfo is set, then we fill in the best available information
3352  * we have for the destination. This is based on (in priority order) any
3353  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3354  * ill_mtu/ill_mc_mtu.
3355  *
3356  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3357  * always do the label check on dst_addr.
3358  */
3359 int
3360 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3361     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3362 {
3363         ire_t           *ire = NULL;
3364         int             error = 0;
3365         ipaddr_t        setsrc;                         /* RTF_SETSRC */
3366         zoneid_t        zoneid = ixa->ixa_zoneid;    /* Honors SO_ALLZONES */
3367         ip_stack_t      *ipst = ixa->ixa_ipst;
3368         dce_t           *dce;
3369         uint_t          pmtu;
3370         uint_t          generation;
3371         nce_t           *nce;
3372         ill_t           *ill = NULL;
3373         boolean_t       multirt = B_FALSE;
3374 
3375         ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3376 
3377         /*
3378          * We never send to zero; the ULPs map it to the loopback address.
3379          * We can't allow it since we use zero to mean unitialized in some
3380          * places.
3381          */
3382         ASSERT(dst_addr != INADDR_ANY);
3383 
3384         if (is_system_labeled()) {
3385                 ts_label_t *tsl = NULL;
3386 
3387                 error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3388                     mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3389                 if (error != 0)
3390                         return (error);
3391                 if (tsl != NULL) {
3392                         /* Update the label */
3393                         ip_xmit_attr_replace_tsl(ixa, tsl);
3394                 }
3395         }
3396 
3397         setsrc = INADDR_ANY;
3398         /*
3399          * Select a route; For IPMP interfaces, we would only select
3400          * a "hidden" route (i.e., going through a specific under_ill)
3401          * if ixa_ifindex has been specified.
3402          */
3403         ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3404             &generation, &setsrc, &error, &multirt);
3405         ASSERT(ire != NULL);    /* IRE_NOROUTE if none found */
3406         if (error != 0)
3407                 goto bad_addr;
3408 
3409         /*
3410          * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3411          * If IPDF_VERIFY_DST is set, the destination must be reachable;
3412          * Otherwise the destination needn't be reachable.
3413          *
3414          * If we match on a reject or black hole, then we've got a
3415          * local failure.  May as well fail out the connect() attempt,
3416          * since it's never going to succeed.
3417          */
3418         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3419                 /*
3420                  * If we're verifying destination reachability, we always want
3421                  * to complain here.
3422                  *
3423                  * If we're not verifying destination reachability but the
3424                  * destination has a route, we still want to fail on the
3425                  * temporary address and broadcast address tests.
3426                  *
3427                  * In both cases do we let the code continue so some reasonable
3428                  * information is returned to the caller. That enables the
3429                  * caller to use (and even cache) the IRE. conn_ip_ouput will
3430                  * use the generation mismatch path to check for the unreachable
3431                  * case thereby avoiding any specific check in the main path.
3432                  */
3433                 ASSERT(generation == IRE_GENERATION_VERIFY);
3434                 if (flags & IPDF_VERIFY_DST) {
3435                         /*
3436                          * Set errno but continue to set up ixa_ire to be
3437                          * the RTF_REJECT|RTF_BLACKHOLE IRE.
3438                          * That allows callers to use ip_output to get an
3439                          * ICMP error back.
3440                          */
3441                         if (!(ire->ire_type & IRE_HOST))
3442                                 error = ENETUNREACH;
3443                         else
3444                                 error = EHOSTUNREACH;
3445                 }
3446         }
3447 
3448         if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3449             !(flags & IPDF_ALLOW_MCBC)) {
3450                 ire_refrele(ire);
3451                 ire = ire_reject(ipst, B_FALSE);
3452                 generation = IRE_GENERATION_VERIFY;
3453                 error = ENETUNREACH;
3454         }
3455 
3456         /* Cache things */
3457         if (ixa->ixa_ire != NULL)
3458                 ire_refrele_notr(ixa->ixa_ire);
3459 #ifdef DEBUG
3460         ire_refhold_notr(ire);
3461         ire_refrele(ire);
3462 #endif
3463         ixa->ixa_ire = ire;
3464         ixa->ixa_ire_generation = generation;
3465 
3466         /*
3467          * Ensure that ixa_dce is always set any time that ixa_ire is set,
3468          * since some callers will send a packet to conn_ip_output() even if
3469          * there's an error.
3470          */
3471         if (flags & IPDF_UNIQUE_DCE) {
3472                 /* Fallback to the default dce if allocation fails */
3473                 dce = dce_lookup_and_add_v4(dst_addr, ipst);
3474                 if (dce != NULL)
3475                         generation = dce->dce_generation;
3476                 else
3477                         dce = dce_lookup_v4(dst_addr, ipst, &generation);
3478         } else {
3479                 dce = dce_lookup_v4(dst_addr, ipst, &generation);
3480         }
3481         ASSERT(dce != NULL);
3482         if (ixa->ixa_dce != NULL)
3483                 dce_refrele_notr(ixa->ixa_dce);
3484 #ifdef DEBUG
3485         dce_refhold_notr(dce);
3486         dce_refrele(dce);
3487 #endif
3488         ixa->ixa_dce = dce;
3489         ixa->ixa_dce_generation = generation;
3490 
3491         /*
3492          * For multicast with multirt we have a flag passed back from
3493          * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3494          * possible multicast address.
3495          * We also need a flag for multicast since we can't check
3496          * whether RTF_MULTIRT is set in ixa_ire for multicast.
3497          */
3498         if (multirt) {
3499                 ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3500                 ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3501         } else {
3502                 ixa->ixa_postfragfn = ire->ire_postfragfn;
3503                 ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3504         }
3505         if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3506                 /* Get an nce to cache. */
3507                 nce = ire_to_nce(ire, firsthop, NULL);
3508                 if (nce == NULL) {
3509                         /* Allocation failure? */
3510                         ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3511                 } else {
3512                         if (ixa->ixa_nce != NULL)
3513                                 nce_refrele(ixa->ixa_nce);
3514                         ixa->ixa_nce = nce;
3515                 }
3516         }
3517 
3518         /*
3519          * If the source address is a loopback address, the
3520          * destination had best be local or multicast.
3521          * If we are sending to an IRE_LOCAL using a loopback source then
3522          * it had better be the same zoneid.
3523          */
3524         if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3525                 if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3526                         ire = NULL;     /* Stored in ixa_ire */
3527                         error = EADDRNOTAVAIL;
3528                         goto bad_addr;
3529                 }
3530                 if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3531                         ire = NULL;     /* Stored in ixa_ire */
3532                         error = EADDRNOTAVAIL;
3533                         goto bad_addr;
3534                 }
3535         }
3536         if (ire->ire_type & IRE_BROADCAST) {
3537                 /*
3538                  * If the ULP didn't have a specified source, then we
3539                  * make sure we reselect the source when sending
3540                  * broadcasts out different interfaces.
3541                  */
3542                 if (flags & IPDF_SELECT_SRC)
3543                         ixa->ixa_flags |= IXAF_SET_SOURCE;
3544                 else
3545                         ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3546         }
3547 
3548         /*
3549          * Does the caller want us to pick a source address?
3550          */
3551         if (flags & IPDF_SELECT_SRC) {
3552                 ipaddr_t        src_addr;
3553 
3554                 /*
3555                  * We use use ire_nexthop_ill to avoid the under ipmp
3556                  * interface for source address selection. Note that for ipmp
3557                  * probe packets, ixa_ifindex would have been specified, and
3558                  * the ip_select_route() invocation would have picked an ire
3559                  * will ire_ill pointing at an under interface.
3560                  */
3561                 ill = ire_nexthop_ill(ire);
3562 
3563                 /* If unreachable we have no ill but need some source */
3564                 if (ill == NULL) {
3565                         src_addr = htonl(INADDR_LOOPBACK);
3566                         /* Make sure we look for a better source address */
3567                         generation = SRC_GENERATION_VERIFY;
3568                 } else {
3569                         error = ip_select_source_v4(ill, setsrc, dst_addr,
3570                             ixa->ixa_multicast_ifaddr, zoneid,
3571                             ipst, &src_addr, &generation, NULL);
3572                         if (error != 0) {
3573                                 ire = NULL;     /* Stored in ixa_ire */
3574                                 goto bad_addr;
3575                         }
3576                 }
3577 
3578                 /*
3579                  * We allow the source address to to down.
3580                  * However, we check that we don't use the loopback address
3581                  * as a source when sending out on the wire.
3582                  */
3583                 if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3584                     !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3585                     !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3586                         ire = NULL;     /* Stored in ixa_ire */
3587                         error = EADDRNOTAVAIL;
3588                         goto bad_addr;
3589                 }
3590 
3591                 *src_addrp = src_addr;
3592                 ixa->ixa_src_generation = generation;
3593         }
3594 
3595         /*
3596          * Make sure we don't leave an unreachable ixa_nce in place
3597          * since ip_select_route is used when we unplumb i.e., remove
3598          * references on ixa_ire, ixa_nce, and ixa_dce.
3599          */
3600         nce = ixa->ixa_nce;
3601         if (nce != NULL && nce->nce_is_condemned) {
3602                 nce_refrele(nce);
3603                 ixa->ixa_nce = NULL;
3604                 ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3605         }
3606 
3607         /*
3608          * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3609          * However, we can't do it for IPv4 multicast or broadcast.
3610          */
3611         if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3612                 ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3613 
3614         /*
3615          * Set initial value for fragmentation limit. Either conn_ip_output
3616          * or ULP might updates it when there are routing changes.
3617          * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3618          */
3619         pmtu = ip_get_pmtu(ixa);
3620         ixa->ixa_fragsize = pmtu;
3621         /* Make sure ixa_fragsize and ixa_pmtu remain identical */
3622         if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3623                 ixa->ixa_pmtu = pmtu;
3624 
3625         /*
3626          * Extract information useful for some transports.
3627          * First we look for DCE metrics. Then we take what we have in
3628          * the metrics in the route, where the offlink is used if we have
3629          * one.
3630          */
3631         if (uinfo != NULL) {
3632                 bzero(uinfo, sizeof (*uinfo));
3633 
3634                 if (dce->dce_flags & DCEF_UINFO)
3635                         *uinfo = dce->dce_uinfo;
3636 
3637                 rts_merge_metrics(uinfo, &ire->ire_metrics);
3638 
3639                 /* Allow ire_metrics to decrease the path MTU from above */
3640                 if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3641                         uinfo->iulp_mtu = pmtu;
3642 
3643                 uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3644                 uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3645                 uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3646         }
3647 
3648         if (ill != NULL)
3649                 ill_refrele(ill);
3650 
3651         return (error);
3652 
3653 bad_addr:
3654         if (ire != NULL)
3655                 ire_refrele(ire);
3656 
3657         if (ill != NULL)
3658                 ill_refrele(ill);
3659 
3660         /*
3661          * Make sure we don't leave an unreachable ixa_nce in place
3662          * since ip_select_route is used when we unplumb i.e., remove
3663          * references on ixa_ire, ixa_nce, and ixa_dce.
3664          */
3665         nce = ixa->ixa_nce;
3666         if (nce != NULL && nce->nce_is_condemned) {
3667                 nce_refrele(nce);
3668                 ixa->ixa_nce = NULL;
3669                 ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3670         }
3671 
3672         return (error);
3673 }
3674 
3675 
3676 /*
3677  * Get the base MTU for the case when path MTU discovery is not used.
3678  * Takes the MTU of the IRE into account.
3679  */
3680 uint_t
3681 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3682 {
3683         uint_t mtu;
3684         uint_t iremtu = ire->ire_metrics.iulp_mtu;
3685 
3686         if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST))
3687                 mtu = ill->ill_mc_mtu;
3688         else
3689                 mtu = ill->ill_mtu;
3690 
3691         if (iremtu != 0 && iremtu < mtu)
3692                 mtu = iremtu;
3693 
3694         return (mtu);
3695 }
3696 
3697 /*
3698  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3699  * Assumes that ixa_ire, dce, and nce have already been set up.
3700  *
3701  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3702  * We avoid path MTU discovery if it is disabled with ndd.
3703  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3704  *
3705  * NOTE: We also used to turn it off for source routed packets. That
3706  * is no longer required since the dce is per final destination.
3707  */
3708 uint_t
3709 ip_get_pmtu(ip_xmit_attr_t *ixa)
3710 {
3711         ip_stack_t      *ipst = ixa->ixa_ipst;
3712         dce_t           *dce;
3713         nce_t           *nce;
3714         ire_t           *ire;
3715         uint_t          pmtu;
3716 
3717         ire = ixa->ixa_ire;
3718         dce = ixa->ixa_dce;
3719         nce = ixa->ixa_nce;
3720 
3721         /*
3722          * If path MTU discovery has been turned off by ndd, then we ignore
3723          * any dce_pmtu and for IPv4 we will not set DF.
3724          */
3725         if (!ipst->ips_ip_path_mtu_discovery)
3726                 ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3727 
3728         pmtu = IP_MAXPACKET;
3729         /*
3730          * Decide whether whether IPv4 sets DF
3731          * For IPv6 "no DF" means to use the 1280 mtu
3732          */
3733         if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3734                 ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3735         } else {
3736                 ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3737                 if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3738                         pmtu = IPV6_MIN_MTU;
3739         }
3740 
3741         /* Check if the PMTU is to old before we use it */
3742         if ((dce->dce_flags & DCEF_PMTU) &&
3743             TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3744             ipst->ips_ip_pathmtu_interval) {
3745                 /*
3746                  * Older than 20 minutes. Drop the path MTU information.
3747                  */
3748                 mutex_enter(&dce->dce_lock);
3749                 dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3750                 dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3751                 mutex_exit(&dce->dce_lock);
3752                 dce_increment_generation(dce);
3753         }
3754 
3755         /* The metrics on the route can lower the path MTU */
3756         if (ire->ire_metrics.iulp_mtu != 0 &&
3757             ire->ire_metrics.iulp_mtu < pmtu)
3758                 pmtu = ire->ire_metrics.iulp_mtu;
3759 
3760         /*
3761          * If the path MTU is smaller than some minimum, we still use dce_pmtu
3762          * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3763          * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3764          */
3765         if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3766                 if (dce->dce_flags & DCEF_PMTU) {
3767                         if (dce->dce_pmtu < pmtu)
3768                                 pmtu = dce->dce_pmtu;
3769 
3770                         if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3771                                 ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3772                                 ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3773                         } else {
3774                                 ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3775                                 ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3776                         }
3777                 } else {
3778                         ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3779                         ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3780                 }
3781         }
3782 
3783         /*
3784          * If we have an IRE_LOCAL we use the loopback mtu instead of
3785          * the ill for going out the wire i.e., IRE_LOCAL gets the same
3786          * mtu as IRE_LOOPBACK.
3787          */
3788         if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3789                 uint_t loopback_mtu;
3790 
3791                 loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3792                     ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3793 
3794                 if (loopback_mtu < pmtu)
3795                         pmtu = loopback_mtu;
3796         } else if (nce != NULL) {
3797                 /*
3798                  * Make sure we don't exceed the interface MTU.
3799                  * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3800                  * an ill. We'd use the above IP_MAXPACKET in that case just
3801                  * to tell the transport something larger than zero.
3802                  */
3803                 if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST)) {
3804                         if (nce->nce_common->ncec_ill->ill_mc_mtu < pmtu)
3805                                 pmtu = nce->nce_common->ncec_ill->ill_mc_mtu;
3806                         if (nce->nce_common->ncec_ill != nce->nce_ill &&
3807                             nce->nce_ill->ill_mc_mtu < pmtu) {
3808                                 /*
3809                                  * for interfaces in an IPMP group, the mtu of
3810                                  * the nce_ill (under_ill) could be different
3811                                  * from the mtu of the ncec_ill, so we take the
3812                                  * min of the two.
3813                                  */
3814                                 pmtu = nce->nce_ill->ill_mc_mtu;
3815                         }
3816                 } else {
3817                         if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3818                                 pmtu = nce->nce_common->ncec_ill->ill_mtu;
3819                         if (nce->nce_common->ncec_ill != nce->nce_ill &&
3820                             nce->nce_ill->ill_mtu < pmtu) {
3821                                 /*
3822                                  * for interfaces in an IPMP group, the mtu of
3823                                  * the nce_ill (under_ill) could be different
3824                                  * from the mtu of the ncec_ill, so we take the
3825                                  * min of the two.
3826                                  */
3827                                 pmtu = nce->nce_ill->ill_mtu;
3828                         }
3829                 }
3830         }
3831 
3832         /*
3833          * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3834          * Only applies to IPv6.
3835          */
3836         if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3837                 if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3838                         switch (ixa->ixa_use_min_mtu) {
3839                         case IPV6_USE_MIN_MTU_MULTICAST:
3840                                 if (ire->ire_type & IRE_MULTICAST)
3841                                         pmtu = IPV6_MIN_MTU;
3842                                 break;
3843                         case IPV6_USE_MIN_MTU_ALWAYS:
3844                                 pmtu = IPV6_MIN_MTU;
3845                                 break;
3846                         case IPV6_USE_MIN_MTU_NEVER:
3847                                 break;
3848                         }
3849                 } else {
3850                         /* Default is IPV6_USE_MIN_MTU_MULTICAST */
3851                         if (ire->ire_type & IRE_MULTICAST)
3852                                 pmtu = IPV6_MIN_MTU;
3853                 }
3854         }
3855 
3856         /*
3857          * For multirouted IPv6 packets, the IP layer will insert a 8-byte
3858          * fragment header in every packet. We compensate for those cases by
3859          * returning a smaller path MTU to the ULP.
3860          *
3861          * In the case of CGTP then ip_output will add a fragment header.
3862          * Make sure there is room for it by telling a smaller number
3863          * to the transport.
3864          *
3865          * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3866          * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3867          * which is the size of the packets it can send.
3868          */
3869         if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3870                 if ((ire->ire_flags & RTF_MULTIRT) ||
3871                     (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3872                         pmtu -= sizeof (ip6_frag_t);
3873                         ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3874                 }
3875         }
3876 
3877         return (pmtu);
3878 }
3879 
3880 /*
3881  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3882  * the final piece where we don't.  Return a pointer to the first mblk in the
3883  * result, and update the pointer to the next mblk to chew on.  If anything
3884  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3885  * NULL pointer.
3886  */
3887 mblk_t *
3888 ip_carve_mp(mblk_t **mpp, ssize_t len)
3889 {
3890         mblk_t  *mp0;
3891         mblk_t  *mp1;
3892         mblk_t  *mp2;
3893 
3894         if (!len || !mpp || !(mp0 = *mpp))
3895                 return (NULL);
3896         /* If we aren't going to consume the first mblk, we need a dup. */
3897         if (mp0->b_wptr - mp0->b_rptr > len) {
3898                 mp1 = dupb(mp0);
3899                 if (mp1) {
3900                         /* Partition the data between the two mblks. */
3901                         mp1->b_wptr = mp1->b_rptr + len;
3902                         mp0->b_rptr = mp1->b_wptr;
3903                         /*
3904                          * after adjustments if mblk not consumed is now
3905                          * unaligned, try to align it. If this fails free
3906                          * all messages and let upper layer recover.
3907                          */
3908                         if (!OK_32PTR(mp0->b_rptr)) {
3909                                 if (!pullupmsg(mp0, -1)) {
3910                                         freemsg(mp0);
3911                                         freemsg(mp1);
3912                                         *mpp = NULL;
3913                                         return (NULL);
3914                                 }
3915                         }
3916                 }
3917                 return (mp1);
3918         }
3919         /* Eat through as many mblks as we need to get len bytes. */
3920         len -= mp0->b_wptr - mp0->b_rptr;
3921         for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3922                 if (mp2->b_wptr - mp2->b_rptr > len) {
3923                         /*
3924                          * We won't consume the entire last mblk.  Like
3925                          * above, dup and partition it.
3926                          */
3927                         mp1->b_cont = dupb(mp2);
3928                         mp1 = mp1->b_cont;
3929                         if (!mp1) {
3930                                 /*
3931                                  * Trouble.  Rather than go to a lot of
3932                                  * trouble to clean up, we free the messages.
3933                                  * This won't be any worse than losing it on
3934                                  * the wire.
3935                                  */
3936                                 freemsg(mp0);
3937                                 freemsg(mp2);
3938                                 *mpp = NULL;
3939                                 return (NULL);
3940                         }
3941                         mp1->b_wptr = mp1->b_rptr + len;
3942                         mp2->b_rptr = mp1->b_wptr;
3943                         /*
3944                          * after adjustments if mblk not consumed is now
3945                          * unaligned, try to align it. If this fails free
3946                          * all messages and let upper layer recover.
3947                          */
3948                         if (!OK_32PTR(mp2->b_rptr)) {
3949                                 if (!pullupmsg(mp2, -1)) {
3950                                         freemsg(mp0);
3951                                         freemsg(mp2);
3952                                         *mpp = NULL;
3953                                         return (NULL);
3954                                 }
3955                         }
3956                         *mpp = mp2;
3957                         return (mp0);
3958                 }
3959                 /* Decrement len by the amount we just got. */
3960                 len -= mp2->b_wptr - mp2->b_rptr;
3961         }
3962         /*
3963          * len should be reduced to zero now.  If not our caller has
3964          * screwed up.
3965          */
3966         if (len) {
3967                 /* Shouldn't happen! */
3968                 freemsg(mp0);
3969                 *mpp = NULL;
3970                 return (NULL);
3971         }
3972         /*
3973          * We consumed up to exactly the end of an mblk.  Detach the part
3974          * we are returning from the rest of the chain.
3975          */
3976         mp1->b_cont = NULL;
3977         *mpp = mp2;
3978         return (mp0);
3979 }
3980 
3981 /* The ill stream is being unplumbed. Called from ip_close */
3982 int
3983 ip_modclose(ill_t *ill)
3984 {
3985         boolean_t success;
3986         ipsq_t  *ipsq;
3987         ipif_t  *ipif;
3988         queue_t *q = ill->ill_rq;
3989         ip_stack_t      *ipst = ill->ill_ipst;
3990         int     i;
3991         arl_ill_common_t *ai = ill->ill_common;
3992 
3993         /*
3994          * The punlink prior to this may have initiated a capability
3995          * negotiation. But ipsq_enter will block until that finishes or
3996          * times out.
3997          */
3998         success = ipsq_enter(ill, B_FALSE, NEW_OP);
3999 
4000         /*
4001          * Open/close/push/pop is guaranteed to be single threaded
4002          * per stream by STREAMS. FS guarantees that all references
4003          * from top are gone before close is called. So there can't
4004          * be another close thread that has set CONDEMNED on this ill.
4005          * and cause ipsq_enter to return failure.
4006          */
4007         ASSERT(success);
4008         ipsq = ill->ill_phyint->phyint_ipsq;
4009 
4010         /*
4011          * Mark it condemned. No new reference will be made to this ill.
4012          * Lookup functions will return an error. Threads that try to
4013          * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4014          * that the refcnt will drop down to zero.
4015          */
4016         mutex_enter(&ill->ill_lock);
4017         ill->ill_state_flags |= ILL_CONDEMNED;
4018         for (ipif = ill->ill_ipif; ipif != NULL;
4019             ipif = ipif->ipif_next) {
4020                 ipif->ipif_state_flags |= IPIF_CONDEMNED;
4021         }
4022         /*
4023          * Wake up anybody waiting to enter the ipsq. ipsq_enter
4024          * returns  error if ILL_CONDEMNED is set
4025          */
4026         cv_broadcast(&ill->ill_cv);
4027         mutex_exit(&ill->ill_lock);
4028 
4029         /*
4030          * Send all the deferred DLPI messages downstream which came in
4031          * during the small window right before ipsq_enter(). We do this
4032          * without waiting for the ACKs because all the ACKs for M_PROTO
4033          * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4034          */
4035         ill_dlpi_send_deferred(ill);
4036 
4037         /*
4038          * Shut down fragmentation reassembly.
4039          * ill_frag_timer won't start a timer again.
4040          * Now cancel any existing timer
4041          */
4042         (void) untimeout(ill->ill_frag_timer_id);
4043         (void) ill_frag_timeout(ill, 0);
4044 
4045         /*
4046          * Call ill_delete to bring down the ipifs, ilms and ill on
4047          * this ill. Then wait for the refcnts to drop to zero.
4048          * ill_is_freeable checks whether the ill is really quiescent.
4049          * Then make sure that threads that are waiting to enter the
4050          * ipsq have seen the error returned by ipsq_enter and have
4051          * gone away. Then we call ill_delete_tail which does the
4052          * DL_UNBIND_REQ with the driver and then qprocsoff.
4053          */
4054         ill_delete(ill);
4055         mutex_enter(&ill->ill_lock);
4056         while (!ill_is_freeable(ill))
4057                 cv_wait(&ill->ill_cv, &ill->ill_lock);
4058 
4059         while (ill->ill_waiters)
4060                 cv_wait(&ill->ill_cv, &ill->ill_lock);
4061 
4062         mutex_exit(&ill->ill_lock);
4063 
4064         /*
4065          * ill_delete_tail drops reference on ill_ipst, but we need to keep
4066          * it held until the end of the function since the cleanup
4067          * below needs to be able to use the ip_stack_t.
4068          */
4069         netstack_hold(ipst->ips_netstack);
4070 
4071         /* qprocsoff is done via ill_delete_tail */
4072         ill_delete_tail(ill);
4073         /*
4074          * synchronously wait for arp stream to unbind. After this, we
4075          * cannot get any data packets up from the driver.
4076          */
4077         arp_unbind_complete(ill);
4078         ASSERT(ill->ill_ipst == NULL);
4079 
4080         /*
4081          * Walk through all conns and qenable those that have queued data.
4082          * Close synchronization needs this to
4083          * be done to ensure that all upper layers blocked
4084          * due to flow control to the closing device
4085          * get unblocked.
4086          */
4087         ip1dbg(("ip_wsrv: walking\n"));
4088         for (i = 0; i < TX_FANOUT_SIZE; i++) {
4089                 conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4090         }
4091 
4092         /*
4093          * ai can be null if this is an IPv6 ill, or if the IPv4
4094          * stream is being torn down before ARP was plumbed (e.g.,
4095          * /sbin/ifconfig plumbing a stream twice, and encountering
4096          * an error
4097          */
4098         if (ai != NULL) {
4099                 ASSERT(!ill->ill_isv6);
4100                 mutex_enter(&ai->ai_lock);
4101                 ai->ai_ill = NULL;
4102                 if (ai->ai_arl == NULL) {
4103                         mutex_destroy(&ai->ai_lock);
4104                         kmem_free(ai, sizeof (*ai));
4105                 } else {
4106                         cv_signal(&ai->ai_ill_unplumb_done);
4107                         mutex_exit(&ai->ai_lock);
4108                 }
4109         }
4110 
4111         mutex_enter(&ipst->ips_ip_mi_lock);
4112         mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4113         mutex_exit(&ipst->ips_ip_mi_lock);
4114 
4115         /*
4116          * credp could be null if the open didn't succeed and ip_modopen
4117          * itself calls ip_close.
4118          */
4119         if (ill->ill_credp != NULL)
4120                 crfree(ill->ill_credp);
4121 
4122         mutex_destroy(&ill->ill_saved_ire_lock);
4123         mutex_destroy(&ill->ill_lock);
4124         rw_destroy(&ill->ill_mcast_lock);
4125         mutex_destroy(&ill->ill_mcast_serializer);
4126         list_destroy(&ill->ill_nce);
4127 
4128         /*
4129          * Now we are done with the module close pieces that
4130          * need the netstack_t.
4131          */
4132         netstack_rele(ipst->ips_netstack);
4133 
4134         mi_close_free((IDP)ill);
4135         q->q_ptr = WR(q)->q_ptr = NULL;
4136 
4137         ipsq_exit(ipsq);
4138 
4139         return (0);
4140 }
4141 
4142 /*
4143  * This is called as part of close() for IP, UDP, ICMP, and RTS
4144  * in order to quiesce the conn.
4145  */
4146 void
4147 ip_quiesce_conn(conn_t *connp)
4148 {
4149         boolean_t       drain_cleanup_reqd = B_FALSE;
4150         boolean_t       conn_ioctl_cleanup_reqd = B_FALSE;
4151         boolean_t       ilg_cleanup_reqd = B_FALSE;
4152         ip_stack_t      *ipst;
4153 
4154         ASSERT(!IPCL_IS_TCP(connp));
4155         ipst = connp->conn_netstack->netstack_ip;
4156 
4157         /*
4158          * Mark the conn as closing, and this conn must not be
4159          * inserted in future into any list. Eg. conn_drain_insert(),
4160          * won't insert this conn into the conn_drain_list.
4161          *
4162          * conn_idl, and conn_ilg cannot get set henceforth.
4163          */
4164         mutex_enter(&connp->conn_lock);
4165         ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4166         connp->conn_state_flags |= CONN_CLOSING;
4167         if (connp->conn_idl != NULL)
4168                 drain_cleanup_reqd = B_TRUE;
4169         if (connp->conn_oper_pending_ill != NULL)
4170                 conn_ioctl_cleanup_reqd = B_TRUE;
4171         if (connp->conn_dhcpinit_ill != NULL) {
4172                 ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4173                 atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4174                 ill_set_inputfn(connp->conn_dhcpinit_ill);
4175                 connp->conn_dhcpinit_ill = NULL;
4176         }
4177         if (connp->conn_ilg != NULL)
4178                 ilg_cleanup_reqd = B_TRUE;
4179         mutex_exit(&connp->conn_lock);
4180 
4181         if (conn_ioctl_cleanup_reqd)
4182                 conn_ioctl_cleanup(connp);
4183 
4184         if (is_system_labeled() && connp->conn_anon_port) {
4185                 (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4186                     connp->conn_mlp_type, connp->conn_proto,
4187                     ntohs(connp->conn_lport), B_FALSE);
4188                 connp->conn_anon_port = 0;
4189         }
4190         connp->conn_mlp_type = mlptSingle;
4191 
4192         /*
4193          * Remove this conn from any fanout list it is on.
4194          * and then wait for any threads currently operating
4195          * on this endpoint to finish
4196          */
4197         ipcl_hash_remove(connp);
4198 
4199         /*
4200          * Remove this conn from the drain list, and do any other cleanup that
4201          * may be required.  (TCP conns are never flow controlled, and
4202          * conn_idl will be NULL.)
4203          */
4204         if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4205                 idl_t *idl = connp->conn_idl;
4206 
4207                 mutex_enter(&idl->idl_lock);
4208                 conn_drain(connp, B_TRUE);
4209                 mutex_exit(&idl->idl_lock);
4210         }
4211 
4212         if (connp == ipst->ips_ip_g_mrouter)
4213                 (void) ip_mrouter_done(ipst);
4214 
4215         if (ilg_cleanup_reqd)
4216                 ilg_delete_all(connp);
4217 
4218         /*
4219          * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4220          * callers from write side can't be there now because close
4221          * is in progress. The only other caller is ipcl_walk
4222          * which checks for the condemned flag.
4223          */
4224         mutex_enter(&connp->conn_lock);
4225         connp->conn_state_flags |= CONN_CONDEMNED;
4226         while (connp->conn_ref != 1)
4227                 cv_wait(&connp->conn_cv, &connp->conn_lock);
4228         connp->conn_state_flags |= CONN_QUIESCED;
4229         mutex_exit(&connp->conn_lock);
4230 }
4231 
4232 /* ARGSUSED */
4233 int
4234 ip_close(queue_t *q, int flags, cred_t *credp __unused)
4235 {
4236         conn_t          *connp;
4237 
4238         /*
4239          * Call the appropriate delete routine depending on whether this is
4240          * a module or device.
4241          */
4242         if (WR(q)->q_next != NULL) {
4243                 /* This is a module close */
4244                 return (ip_modclose((ill_t *)q->q_ptr));
4245         }
4246 
4247         connp = q->q_ptr;
4248         ip_quiesce_conn(connp);
4249 
4250         qprocsoff(q);
4251 
4252         /*
4253          * Now we are truly single threaded on this stream, and can
4254          * delete the things hanging off the connp, and finally the connp.
4255          * We removed this connp from the fanout list, it cannot be
4256          * accessed thru the fanouts, and we already waited for the
4257          * conn_ref to drop to 0. We are already in close, so
4258          * there cannot be any other thread from the top. qprocsoff
4259          * has completed, and service has completed or won't run in
4260          * future.
4261          */
4262         ASSERT(connp->conn_ref == 1);
4263 
4264         inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4265 
4266         connp->conn_ref--;
4267         ipcl_conn_destroy(connp);
4268 
4269         q->q_ptr = WR(q)->q_ptr = NULL;
4270         return (0);
4271 }
4272 
4273 /*
4274  * Wapper around putnext() so that ip_rts_request can merely use
4275  * conn_recv.
4276  */
4277 /*ARGSUSED2*/
4278 static void
4279 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4280 {
4281         conn_t *connp = (conn_t *)arg1;
4282 
4283         putnext(connp->conn_rq, mp);
4284 }
4285 
4286 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4287 /* ARGSUSED */
4288 static void
4289 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4290 {
4291         freemsg(mp);
4292 }
4293 
4294 /*
4295  * Called when the module is about to be unloaded
4296  */
4297 void
4298 ip_ddi_destroy(void)
4299 {
4300         /* This needs to be called before destroying any transports. */
4301         mutex_enter(&cpu_lock);
4302         unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4303         mutex_exit(&cpu_lock);
4304 
4305         tnet_fini();
4306 
4307         icmp_ddi_g_destroy();
4308         rts_ddi_g_destroy();
4309         udp_ddi_g_destroy();
4310         sctp_ddi_g_destroy();
4311         tcp_ddi_g_destroy();
4312         ilb_ddi_g_destroy();
4313         dce_g_destroy();
4314         ipsec_policy_g_destroy();
4315         ipcl_g_destroy();
4316         ip_net_g_destroy();
4317         ip_ire_g_fini();
4318         inet_minor_destroy(ip_minor_arena_sa);
4319 #if defined(_LP64)
4320         inet_minor_destroy(ip_minor_arena_la);
4321 #endif
4322 
4323 #ifdef DEBUG
4324         list_destroy(&ip_thread_list);
4325         rw_destroy(&ip_thread_rwlock);
4326         tsd_destroy(&ip_thread_data);
4327 #endif
4328 
4329         netstack_unregister(NS_IP);
4330 }
4331 
4332 /*
4333  * First step in cleanup.
4334  */
4335 /* ARGSUSED */
4336 static void
4337 ip_stack_shutdown(netstackid_t stackid, void *arg)
4338 {
4339         ip_stack_t *ipst = (ip_stack_t *)arg;
4340         kt_did_t ktid;
4341 
4342 #ifdef NS_DEBUG
4343         printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4344 #endif
4345 
4346         /*
4347          * Perform cleanup for special interfaces (loopback and IPMP).
4348          */
4349         ip_interface_cleanup(ipst);
4350 
4351         /*
4352          * The *_hook_shutdown()s start the process of notifying any
4353          * consumers that things are going away.... nothing is destroyed.
4354          */
4355         ipv4_hook_shutdown(ipst);
4356         ipv6_hook_shutdown(ipst);
4357         arp_hook_shutdown(ipst);
4358 
4359         mutex_enter(&ipst->ips_capab_taskq_lock);
4360         ktid = ipst->ips_capab_taskq_thread->t_did;
4361         ipst->ips_capab_taskq_quit = B_TRUE;
4362         cv_signal(&ipst->ips_capab_taskq_cv);
4363         mutex_exit(&ipst->ips_capab_taskq_lock);
4364 
4365         /*
4366          * In rare occurrences, particularly on virtual hardware where CPUs can
4367          * be de-scheduled, the thread that we just signaled will not run until
4368          * after we have gotten through parts of ip_stack_fini. If that happens
4369          * then we'll try to grab the ips_capab_taskq_lock as part of returning
4370          * from cv_wait which no longer exists.
4371          */
4372         thread_join(ktid);
4373 }
4374 
4375 /*
4376  * Free the IP stack instance.
4377  */
4378 static void
4379 ip_stack_fini(netstackid_t stackid, void *arg)
4380 {
4381         ip_stack_t *ipst = (ip_stack_t *)arg;
4382         int ret;
4383 
4384 #ifdef NS_DEBUG
4385         printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4386 #endif
4387         /*
4388          * At this point, all of the notifications that the events and
4389          * protocols are going away have been run, meaning that we can
4390          * now set about starting to clean things up.
4391          */
4392         ipobs_fini(ipst);
4393         ipv4_hook_destroy(ipst);
4394         ipv6_hook_destroy(ipst);
4395         arp_hook_destroy(ipst);
4396         ip_net_destroy(ipst);
4397 
4398         ipmp_destroy(ipst);
4399 
4400         ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4401         ipst->ips_ip_mibkp = NULL;
4402         icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4403         ipst->ips_icmp_mibkp = NULL;
4404         ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4405         ipst->ips_ip_kstat = NULL;
4406         bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4407         ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4408         ipst->ips_ip6_kstat = NULL;
4409         bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4410 
4411         kmem_free(ipst->ips_propinfo_tbl,
4412             ip_propinfo_count * sizeof (mod_prop_info_t));
4413         ipst->ips_propinfo_tbl = NULL;
4414 
4415         dce_stack_destroy(ipst);
4416         ip_mrouter_stack_destroy(ipst);
4417 
4418         /*
4419          * Quiesce all of our timers. Note we set the quiesce flags before we
4420          * call untimeout. The slowtimers may actually kick off another instance
4421          * of the non-slow timers.
4422          */
4423         mutex_enter(&ipst->ips_igmp_timer_lock);
4424         ipst->ips_igmp_timer_quiesce = B_TRUE;
4425         mutex_exit(&ipst->ips_igmp_timer_lock);
4426 
4427         mutex_enter(&ipst->ips_mld_timer_lock);
4428         ipst->ips_mld_timer_quiesce = B_TRUE;
4429         mutex_exit(&ipst->ips_mld_timer_lock);
4430 
4431         mutex_enter(&ipst->ips_igmp_slowtimeout_lock);
4432         ipst->ips_igmp_slowtimeout_quiesce = B_TRUE;
4433         mutex_exit(&ipst->ips_igmp_slowtimeout_lock);
4434 
4435         mutex_enter(&ipst->ips_mld_slowtimeout_lock);
4436         ipst->ips_mld_slowtimeout_quiesce = B_TRUE;
4437         mutex_exit(&ipst->ips_mld_slowtimeout_lock);
4438 
4439         ret = untimeout(ipst->ips_igmp_timeout_id);
4440         if (ret == -1) {
4441                 ASSERT(ipst->ips_igmp_timeout_id == 0);
4442         } else {
4443                 ASSERT(ipst->ips_igmp_timeout_id != 0);
4444                 ipst->ips_igmp_timeout_id = 0;
4445         }
4446         ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4447         if (ret == -1) {
4448                 ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4449         } else {
4450                 ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4451                 ipst->ips_igmp_slowtimeout_id = 0;
4452         }
4453         ret = untimeout(ipst->ips_mld_timeout_id);
4454         if (ret == -1) {
4455                 ASSERT(ipst->ips_mld_timeout_id == 0);
4456         } else {
4457                 ASSERT(ipst->ips_mld_timeout_id != 0);
4458                 ipst->ips_mld_timeout_id = 0;
4459         }
4460         ret = untimeout(ipst->ips_mld_slowtimeout_id);
4461         if (ret == -1) {
4462                 ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4463         } else {
4464                 ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4465                 ipst->ips_mld_slowtimeout_id = 0;
4466         }
4467 
4468         ip_ire_fini(ipst);
4469         ip6_asp_free(ipst);
4470         conn_drain_fini(ipst);
4471         ipcl_destroy(ipst);
4472 
4473         mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4474         mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4475         kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4476         ipst->ips_ndp4 = NULL;
4477         kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4478         ipst->ips_ndp6 = NULL;
4479 
4480         if (ipst->ips_loopback_ksp != NULL) {
4481                 kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4482                 ipst->ips_loopback_ksp = NULL;
4483         }
4484 
4485         mutex_destroy(&ipst->ips_capab_taskq_lock);
4486         cv_destroy(&ipst->ips_capab_taskq_cv);
4487 
4488         rw_destroy(&ipst->ips_srcid_lock);
4489 
4490         mutex_destroy(&ipst->ips_ip_mi_lock);
4491         rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4492 
4493         mutex_destroy(&ipst->ips_igmp_timer_lock);
4494         mutex_destroy(&ipst->ips_mld_timer_lock);
4495         mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4496         mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4497         mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4498         rw_destroy(&ipst->ips_ill_g_lock);
4499 
4500         kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4501         ipst->ips_phyint_g_list = NULL;
4502         kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4503         ipst->ips_ill_g_heads = NULL;
4504 
4505         ldi_ident_release(ipst->ips_ldi_ident);
4506         kmem_free(ipst, sizeof (*ipst));
4507 }
4508 
4509 /*
4510  * This function is called from the TSD destructor, and is used to debug
4511  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4512  * details.
4513  */
4514 static void
4515 ip_thread_exit(void *phash)
4516 {
4517         th_hash_t *thh = phash;
4518 
4519         rw_enter(&ip_thread_rwlock, RW_WRITER);
4520         list_remove(&ip_thread_list, thh);
4521         rw_exit(&ip_thread_rwlock);
4522         mod_hash_destroy_hash(thh->thh_hash);
4523         kmem_free(thh, sizeof (*thh));
4524 }
4525 
4526 /*
4527  * Called when the IP kernel module is loaded into the kernel
4528  */
4529 void
4530 ip_ddi_init(void)
4531 {
4532         ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4533 
4534         /*
4535          * For IP and TCP the minor numbers should start from 2 since we have 4
4536          * initial devices: ip, ip6, tcp, tcp6.
4537          */
4538         /*
4539          * If this is a 64-bit kernel, then create two separate arenas -
4540          * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4541          * other for socket apps in the range 2^^18 through 2^^32-1.
4542          */
4543         ip_minor_arena_la = NULL;
4544         ip_minor_arena_sa = NULL;
4545 #if defined(_LP64)
4546         if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4547             INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4548                 cmn_err(CE_PANIC,
4549                     "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4550         }
4551         if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4552             MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4553                 cmn_err(CE_PANIC,
4554                     "ip_ddi_init: ip_minor_arena_la creation failed\n");
4555         }
4556 #else
4557         if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4558             INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4559                 cmn_err(CE_PANIC,
4560                     "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4561         }
4562 #endif
4563         ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4564 
4565         ipcl_g_init();
4566         ip_ire_g_init();
4567         ip_net_g_init();
4568 
4569 #ifdef DEBUG
4570         tsd_create(&ip_thread_data, ip_thread_exit);
4571         rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4572         list_create(&ip_thread_list, sizeof (th_hash_t),
4573             offsetof(th_hash_t, thh_link));
4574 #endif
4575         ipsec_policy_g_init();
4576         tcp_ddi_g_init();
4577         sctp_ddi_g_init();
4578         dce_g_init();
4579 
4580         /*
4581          * We want to be informed each time a stack is created or
4582          * destroyed in the kernel, so we can maintain the
4583          * set of udp_stack_t's.
4584          */
4585         netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4586             ip_stack_fini);
4587 
4588         tnet_init();
4589 
4590         udp_ddi_g_init();
4591         rts_ddi_g_init();
4592         icmp_ddi_g_init();
4593         ilb_ddi_g_init();
4594 
4595         /* This needs to be called after all transports are initialized. */
4596         mutex_enter(&cpu_lock);
4597         register_cpu_setup_func(ip_tp_cpu_update, NULL);
4598         mutex_exit(&cpu_lock);
4599 }
4600 
4601 /*
4602  * Initialize the IP stack instance.
4603  */
4604 static void *
4605 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4606 {
4607         ip_stack_t      *ipst;
4608         size_t          arrsz;
4609         major_t         major;
4610 
4611 #ifdef NS_DEBUG
4612         printf("ip_stack_init(stack %d)\n", stackid);
4613 #endif
4614 
4615         ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4616         ipst->ips_netstack = ns;
4617 
4618         ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4619             KM_SLEEP);
4620         ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4621             KM_SLEEP);
4622         ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4623         ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4624         mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4625         mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4626 
4627         mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4628         ipst->ips_igmp_deferred_next = INFINITY;
4629         mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4630         ipst->ips_mld_deferred_next = INFINITY;
4631         mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4632         mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4633         mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4634         mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4635         rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4636         rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4637 
4638         ipcl_init(ipst);
4639         ip_ire_init(ipst);
4640         ip6_asp_init(ipst);
4641         ipif_init(ipst);
4642         conn_drain_init(ipst);
4643         ip_mrouter_stack_init(ipst);
4644         dce_stack_init(ipst);
4645 
4646         ipst->ips_ip_multirt_log_interval = 1000;
4647 
4648         ipst->ips_ill_index = 1;
4649 
4650         ipst->ips_saved_ip_forwarding = -1;
4651         ipst->ips_reg_vif_num = ALL_VIFS;    /* Index to Register vif */
4652 
4653         arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4654         ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4655         bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4656 
4657         ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4658         ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4659         ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4660         ipst->ips_ip6_kstat =
4661             ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4662 
4663         ipst->ips_ip_src_id = 1;
4664         rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4665 
4666         ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4667 
4668         ip_net_init(ipst, ns);
4669         ipv4_hook_init(ipst);
4670         ipv6_hook_init(ipst);
4671         arp_hook_init(ipst);
4672         ipmp_init(ipst);
4673         ipobs_init(ipst);
4674 
4675         /*
4676          * Create the taskq dispatcher thread and initialize related stuff.
4677          */
4678         mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4679         cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4680         ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4681             ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4682 
4683         major = mod_name_to_major(INET_NAME);
4684         (void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4685         return (ipst);
4686 }
4687 
4688 /*
4689  * Allocate and initialize a DLPI template of the specified length.  (May be
4690  * called as writer.)
4691  */
4692 mblk_t *
4693 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4694 {
4695         mblk_t  *mp;
4696 
4697         mp = allocb(len, BPRI_MED);
4698         if (!mp)
4699                 return (NULL);
4700 
4701         /*
4702          * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4703          * of which we don't seem to use) are sent with M_PCPROTO, and
4704          * that other DLPI are M_PROTO.
4705          */
4706         if (prim == DL_INFO_REQ) {
4707                 mp->b_datap->db_type = M_PCPROTO;
4708         } else {
4709                 mp->b_datap->db_type = M_PROTO;
4710         }
4711 
4712         mp->b_wptr = mp->b_rptr + len;
4713         bzero(mp->b_rptr, len);
4714         ((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4715         return (mp);
4716 }
4717 
4718 /*
4719  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4720  */
4721 mblk_t *
4722 ip_dlnotify_alloc(uint_t notification, uint_t data)
4723 {
4724         dl_notify_ind_t *notifyp;
4725         mblk_t          *mp;
4726 
4727         if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4728                 return (NULL);
4729 
4730         notifyp = (dl_notify_ind_t *)mp->b_rptr;
4731         notifyp->dl_notification = notification;
4732         notifyp->dl_data = data;
4733         return (mp);
4734 }
4735 
4736 mblk_t *
4737 ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
4738 {
4739         dl_notify_ind_t *notifyp;
4740         mblk_t          *mp;
4741 
4742         if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4743                 return (NULL);
4744 
4745         notifyp = (dl_notify_ind_t *)mp->b_rptr;
4746         notifyp->dl_notification = notification;
4747         notifyp->dl_data1 = data1;
4748         notifyp->dl_data2 = data2;
4749         return (mp);
4750 }
4751 
4752 /*
4753  * Debug formatting routine.  Returns a character string representation of the
4754  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4755  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4756  *
4757  * Once the ndd table-printing interfaces are removed, this can be changed to
4758  * standard dotted-decimal form.
4759  */
4760 char *
4761 ip_dot_addr(ipaddr_t addr, char *buf)
4762 {
4763         uint8_t *ap = (uint8_t *)&addr;
4764 
4765         (void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4766             ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4767         return (buf);
4768 }
4769 
4770 /*
4771  * Write the given MAC address as a printable string in the usual colon-
4772  * separated format.
4773  */
4774 const char *
4775 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4776 {
4777         char *bp;
4778 
4779         if (alen == 0 || buflen < 4)
4780                 return ("?");
4781         bp = buf;
4782         for (;;) {
4783                 /*
4784                  * If there are more MAC address bytes available, but we won't
4785                  * have any room to print them, then add "..." to the string
4786                  * instead.  See below for the 'magic number' explanation.
4787                  */
4788                 if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4789                         (void) strcpy(bp, "...");
4790                         break;
4791                 }
4792                 (void) sprintf(bp, "%02x", *addr++);
4793                 bp += 2;
4794                 if (--alen == 0)
4795                         break;
4796                 *bp++ = ':';
4797                 buflen -= 3;
4798                 /*
4799                  * At this point, based on the first 'if' statement above,
4800                  * either alen == 1 and buflen >= 3, or alen > 1 and
4801                  * buflen >= 4.  The first case leaves room for the final "xx"
4802                  * number and trailing NUL byte.  The second leaves room for at
4803                  * least "...".  Thus the apparently 'magic' numbers chosen for
4804                  * that statement.
4805                  */
4806         }
4807         return (buf);
4808 }
4809 
4810 /*
4811  * Called when it is conceptually a ULP that would sent the packet
4812  * e.g., port unreachable and protocol unreachable. Check that the packet
4813  * would have passed the IPsec global policy before sending the error.
4814  *
4815  * Send an ICMP error after patching up the packet appropriately.
4816  * Uses ip_drop_input and bumps the appropriate MIB.
4817  */
4818 void
4819 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4820     ip_recv_attr_t *ira)
4821 {
4822         ipha_t          *ipha;
4823         boolean_t       secure;
4824         ill_t           *ill = ira->ira_ill;
4825         ip_stack_t      *ipst = ill->ill_ipst;
4826         netstack_t      *ns = ipst->ips_netstack;
4827         ipsec_stack_t   *ipss = ns->netstack_ipsec;
4828 
4829         secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4830 
4831         /*
4832          * We are generating an icmp error for some inbound packet.
4833          * Called from all ip_fanout_(udp, tcp, proto) functions.
4834          * Before we generate an error, check with global policy
4835          * to see whether this is allowed to enter the system. As
4836          * there is no "conn", we are checking with global policy.
4837          */
4838         ipha = (ipha_t *)mp->b_rptr;
4839         if (secure || ipss->ipsec_inbound_v4_policy_present) {
4840                 mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4841                 if (mp == NULL)
4842                         return;
4843         }
4844 
4845         /* We never send errors for protocols that we do implement */
4846         if (ira->ira_protocol == IPPROTO_ICMP ||
4847             ira->ira_protocol == IPPROTO_IGMP) {
4848                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4849                 ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4850                 freemsg(mp);
4851                 return;
4852         }
4853         /*
4854          * Have to correct checksum since
4855          * the packet might have been
4856          * fragmented and the reassembly code in ip_rput
4857          * does not restore the IP checksum.
4858          */
4859         ipha->ipha_hdr_checksum = 0;
4860         ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4861 
4862         switch (icmp_type) {
4863         case ICMP_DEST_UNREACHABLE:
4864                 switch (icmp_code) {
4865                 case ICMP_PROTOCOL_UNREACHABLE:
4866                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4867                         ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4868                         break;
4869                 case ICMP_PORT_UNREACHABLE:
4870                         BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4871                         ip_drop_input("ipIfStatsNoPorts", mp, ill);
4872                         break;
4873                 }
4874 
4875                 icmp_unreachable(mp, icmp_code, ira);
4876                 break;
4877         default:
4878 #ifdef DEBUG
4879                 panic("ip_fanout_send_icmp_v4: wrong type");
4880                 /*NOTREACHED*/
4881 #else
4882                 freemsg(mp);
4883                 break;
4884 #endif
4885         }
4886 }
4887 
4888 /*
4889  * Used to send an ICMP error message when a packet is received for
4890  * a protocol that is not supported. The mblk passed as argument
4891  * is consumed by this function.
4892  */
4893 void
4894 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4895 {
4896         ipha_t          *ipha;
4897 
4898         ipha = (ipha_t *)mp->b_rptr;
4899         if (ira->ira_flags & IRAF_IS_IPV4) {
4900                 ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4901                 ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4902                     ICMP_PROTOCOL_UNREACHABLE, ira);
4903         } else {
4904                 ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4905                 ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4906                     ICMP6_PARAMPROB_NEXTHEADER, ira);
4907         }
4908 }
4909 
4910 /*
4911  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4912  * Handles IPv4 and IPv6.
4913  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4914  * Caller is responsible for dropping references to the conn.
4915  */
4916 void
4917 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4918     ip_recv_attr_t *ira)
4919 {
4920         ill_t           *ill = ira->ira_ill;
4921         ip_stack_t      *ipst = ill->ill_ipst;
4922         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
4923         boolean_t       secure;
4924         uint_t          protocol = ira->ira_protocol;
4925         iaflags_t       iraflags = ira->ira_flags;
4926         queue_t         *rq;
4927 
4928         secure = iraflags & IRAF_IPSEC_SECURE;
4929 
4930         rq = connp->conn_rq;
4931         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4932                 switch (protocol) {
4933                 case IPPROTO_ICMPV6:
4934                         BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4935                         break;
4936                 case IPPROTO_ICMP:
4937                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4938                         break;
4939                 default:
4940                         BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4941                         break;
4942                 }
4943                 freemsg(mp);
4944                 return;
4945         }
4946 
4947         ASSERT(!(IPCL_IS_IPTUN(connp)));
4948 
4949         if (((iraflags & IRAF_IS_IPV4) ?
4950             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4951             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4952             secure) {
4953                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
4954                     ip6h, ira);
4955                 if (mp == NULL) {
4956                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4957                         /* Note that mp is NULL */
4958                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
4959                         return;
4960                 }
4961         }
4962 
4963         if (iraflags & IRAF_ICMP_ERROR) {
4964                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
4965         } else {
4966                 ill_t *rill = ira->ira_rill;
4967 
4968                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4969                 ira->ira_ill = ira->ira_rill = NULL;
4970                 /* Send it upstream */
4971                 (connp->conn_recv)(connp, mp, NULL, ira);
4972                 ira->ira_ill = ill;
4973                 ira->ira_rill = rill;
4974         }
4975 }
4976 
4977 /*
4978  * Handle protocols with which IP is less intimate.  There
4979  * can be more than one stream bound to a particular
4980  * protocol.  When this is the case, normally each one gets a copy
4981  * of any incoming packets.
4982  *
4983  * IPsec NOTE :
4984  *
4985  * Don't allow a secure packet going up a non-secure connection.
4986  * We don't allow this because
4987  *
4988  * 1) Reply might go out in clear which will be dropped at
4989  *    the sending side.
4990  * 2) If the reply goes out in clear it will give the
4991  *    adversary enough information for getting the key in
4992  *    most of the cases.
4993  *
4994  * Moreover getting a secure packet when we expect clear
4995  * implies that SA's were added without checking for
4996  * policy on both ends. This should not happen once ISAKMP
4997  * is used to negotiate SAs as SAs will be added only after
4998  * verifying the policy.
4999  *
5000  * Zones notes:
5001  * Earlier in ip_input on a system with multiple shared-IP zones we
5002  * duplicate the multicast and broadcast packets and send them up
5003  * with each explicit zoneid that exists on that ill.
5004  * This means that here we can match the zoneid with SO_ALLZONES being special.
5005  */
5006 void
5007 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5008 {
5009         mblk_t          *mp1;
5010         ipaddr_t        laddr;
5011         conn_t          *connp, *first_connp, *next_connp;
5012         connf_t         *connfp;
5013         ill_t           *ill = ira->ira_ill;
5014         ip_stack_t      *ipst = ill->ill_ipst;
5015 
5016         laddr = ipha->ipha_dst;
5017 
5018         connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5019         mutex_enter(&connfp->connf_lock);
5020         connp = connfp->connf_head;
5021         for (connp = connfp->connf_head; connp != NULL;
5022             connp = connp->conn_next) {
5023                 /* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5024                 if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5025                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5026                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5027                         break;
5028                 }
5029         }
5030 
5031         if (connp == NULL) {
5032                 /*
5033                  * No one bound to these addresses.  Is
5034                  * there a client that wants all
5035                  * unclaimed datagrams?
5036                  */
5037                 mutex_exit(&connfp->connf_lock);
5038                 ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5039                     ICMP_PROTOCOL_UNREACHABLE, ira);
5040                 return;
5041         }
5042 
5043         ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5044 
5045         CONN_INC_REF(connp);
5046         first_connp = connp;
5047         connp = connp->conn_next;
5048 
5049         for (;;) {
5050                 while (connp != NULL) {
5051                         /* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5052                         if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5053                             (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5054                             tsol_receive_local(mp, &laddr, IPV4_VERSION,
5055                             ira, connp)))
5056                                 break;
5057                         connp = connp->conn_next;
5058                 }
5059 
5060                 if (connp == NULL) {
5061                         /* No more interested clients */
5062                         connp = first_connp;
5063                         break;
5064                 }
5065                 if (((mp1 = dupmsg(mp)) == NULL) &&
5066                     ((mp1 = copymsg(mp)) == NULL)) {
5067                         /* Memory allocation failed */
5068                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5069                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
5070                         connp = first_connp;
5071                         break;
5072                 }
5073 
5074                 CONN_INC_REF(connp);
5075                 mutex_exit(&connfp->connf_lock);
5076 
5077                 ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5078                     ira);
5079 
5080                 mutex_enter(&connfp->connf_lock);
5081                 /* Follow the next pointer before releasing the conn. */
5082                 next_connp = connp->conn_next;
5083                 CONN_DEC_REF(connp);
5084                 connp = next_connp;
5085         }
5086 
5087         /* Last one.  Send it upstream. */
5088         mutex_exit(&connfp->connf_lock);
5089 
5090         ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5091 
5092         CONN_DEC_REF(connp);
5093 }
5094 
5095 /*
5096  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5097  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5098  * is not consumed.
5099  *
5100  * One of three things can happen, all of which affect the passed-in mblk:
5101  *
5102  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5103  *
5104  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5105  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5106  *
5107  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5108  */
5109 mblk_t *
5110 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5111 {
5112         int shift, plen, iph_len;
5113         ipha_t *ipha;
5114         udpha_t *udpha;
5115         uint32_t *spi;
5116         uint32_t esp_ports;
5117         uint8_t *orptr;
5118         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
5119         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
5120 
5121         ipha = (ipha_t *)mp->b_rptr;
5122         iph_len = ira->ira_ip_hdr_length;
5123         plen = ira->ira_pktlen;
5124 
5125         if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5126                 /*
5127                  * Most likely a keepalive for the benefit of an intervening
5128                  * NAT.  These aren't for us, per se, so drop it.
5129                  *
5130                  * RFC 3947/8 doesn't say for sure what to do for 2-3
5131                  * byte packets (keepalives are 1-byte), but we'll drop them
5132                  * also.
5133                  */
5134                 ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5135                     DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5136                 return (NULL);
5137         }
5138 
5139         if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5140                 /* might as well pull it all up - it might be ESP. */
5141                 if (!pullupmsg(mp, -1)) {
5142                         ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5143                             DROPPER(ipss, ipds_esp_nomem),
5144                             &ipss->ipsec_dropper);
5145                         return (NULL);
5146                 }
5147 
5148                 ipha = (ipha_t *)mp->b_rptr;
5149         }
5150         spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5151         if (*spi == 0) {
5152                 /* UDP packet - remove 0-spi. */
5153                 shift = sizeof (uint32_t);
5154         } else {
5155                 /* ESP-in-UDP packet - reduce to ESP. */
5156                 ipha->ipha_protocol = IPPROTO_ESP;
5157                 shift = sizeof (udpha_t);
5158         }
5159 
5160         /* Fix IP header */
5161         ira->ira_pktlen = (plen - shift);
5162         ipha->ipha_length = htons(ira->ira_pktlen);
5163         ipha->ipha_hdr_checksum = 0;
5164 
5165         orptr = mp->b_rptr;
5166         mp->b_rptr += shift;
5167 
5168         udpha = (udpha_t *)(orptr + iph_len);
5169         if (*spi == 0) {
5170                 ASSERT((uint8_t *)ipha == orptr);
5171                 udpha->uha_length = htons(plen - shift - iph_len);
5172                 iph_len += sizeof (udpha_t);    /* For the call to ovbcopy(). */
5173                 esp_ports = 0;
5174         } else {
5175                 esp_ports = *((uint32_t *)udpha);
5176                 ASSERT(esp_ports != 0);
5177         }
5178         ovbcopy(orptr, orptr + shift, iph_len);
5179         if (esp_ports != 0) /* Punt up for ESP processing. */ {
5180                 ipha = (ipha_t *)(orptr + shift);
5181 
5182                 ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5183                 ira->ira_esp_udp_ports = esp_ports;
5184                 ip_fanout_v4(mp, ipha, ira);
5185                 return (NULL);
5186         }
5187         return (mp);
5188 }
5189 
5190 /*
5191  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5192  * Handles IPv4 and IPv6.
5193  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5194  * Caller is responsible for dropping references to the conn.
5195  */
5196 void
5197 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5198     ip_recv_attr_t *ira)
5199 {
5200         ill_t           *ill = ira->ira_ill;
5201         ip_stack_t      *ipst = ill->ill_ipst;
5202         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
5203         boolean_t       secure;
5204         iaflags_t       iraflags = ira->ira_flags;
5205 
5206         secure = iraflags & IRAF_IPSEC_SECURE;
5207 
5208         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5209             !canputnext(connp->conn_rq)) {
5210                 BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5211                 freemsg(mp);
5212                 return;
5213         }
5214 
5215         if (((iraflags & IRAF_IS_IPV4) ?
5216             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5217             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5218             secure) {
5219                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
5220                     ip6h, ira);
5221                 if (mp == NULL) {
5222                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5223                         /* Note that mp is NULL */
5224                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
5225                         return;
5226                 }
5227         }
5228 
5229         /*
5230          * Since this code is not used for UDP unicast we don't need a NAT_T
5231          * check. Only ip_fanout_v4 has that check.
5232          */
5233         if (ira->ira_flags & IRAF_ICMP_ERROR) {
5234                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
5235         } else {
5236                 ill_t *rill = ira->ira_rill;
5237 
5238                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5239                 ira->ira_ill = ira->ira_rill = NULL;
5240                 /* Send it upstream */
5241                 (connp->conn_recv)(connp, mp, NULL, ira);
5242                 ira->ira_ill = ill;
5243                 ira->ira_rill = rill;
5244         }
5245 }
5246 
5247 /*
5248  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5249  * (Unicast fanout is handled in ip_input_v4.)
5250  *
5251  * If SO_REUSEADDR is set all multicast and broadcast packets
5252  * will be delivered to all conns bound to the same port.
5253  *
5254  * If there is at least one matching AF_INET receiver, then we will
5255  * ignore any AF_INET6 receivers.
5256  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5257  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5258  * packets.
5259  *
5260  * Zones notes:
5261  * Earlier in ip_input on a system with multiple shared-IP zones we
5262  * duplicate the multicast and broadcast packets and send them up
5263  * with each explicit zoneid that exists on that ill.
5264  * This means that here we can match the zoneid with SO_ALLZONES being special.
5265  */
5266 void
5267 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5268     ip_recv_attr_t *ira)
5269 {
5270         ipaddr_t        laddr;
5271         in6_addr_t      v6faddr;
5272         conn_t          *connp;
5273         connf_t         *connfp;
5274         ipaddr_t        faddr;
5275         ill_t           *ill = ira->ira_ill;
5276         ip_stack_t      *ipst = ill->ill_ipst;
5277 
5278         ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5279 
5280         laddr = ipha->ipha_dst;
5281         faddr = ipha->ipha_src;
5282 
5283         connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5284         mutex_enter(&connfp->connf_lock);
5285         connp = connfp->connf_head;
5286 
5287         /*
5288          * If SO_REUSEADDR has been set on the first we send the
5289          * packet to all clients that have joined the group and
5290          * match the port.
5291          */
5292         while (connp != NULL) {
5293                 if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5294                     conn_wantpacket(connp, ira, ipha) &&
5295                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5296                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5297                         break;
5298                 connp = connp->conn_next;
5299         }
5300 
5301         if (connp == NULL)
5302                 goto notfound;
5303 
5304         CONN_INC_REF(connp);
5305 
5306         if (connp->conn_reuseaddr) {
5307                 conn_t          *first_connp = connp;
5308                 conn_t          *next_connp;
5309                 mblk_t          *mp1;
5310 
5311                 connp = connp->conn_next;
5312                 for (;;) {
5313                         while (connp != NULL) {
5314                                 if (IPCL_UDP_MATCH(connp, lport, laddr,
5315                                     fport, faddr) &&
5316                                     conn_wantpacket(connp, ira, ipha) &&
5317                                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5318                                     tsol_receive_local(mp, &laddr, IPV4_VERSION,
5319                                     ira, connp)))
5320                                         break;
5321                                 connp = connp->conn_next;
5322                         }
5323                         if (connp == NULL) {
5324                                 /* No more interested clients */
5325                                 connp = first_connp;
5326                                 break;
5327                         }
5328                         if (((mp1 = dupmsg(mp)) == NULL) &&
5329                             ((mp1 = copymsg(mp)) == NULL)) {
5330                                 /* Memory allocation failed */
5331                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5332                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
5333                                 connp = first_connp;
5334                                 break;
5335                         }
5336                         CONN_INC_REF(connp);
5337                         mutex_exit(&connfp->connf_lock);
5338 
5339                         IP_STAT(ipst, ip_udp_fanmb);
5340                         ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5341                             NULL, ira);
5342                         mutex_enter(&connfp->connf_lock);
5343                         /* Follow the next pointer before releasing the conn */
5344                         next_connp = connp->conn_next;
5345                         CONN_DEC_REF(connp);
5346                         connp = next_connp;
5347                 }
5348         }
5349 
5350         /* Last one.  Send it upstream. */
5351         mutex_exit(&connfp->connf_lock);
5352         IP_STAT(ipst, ip_udp_fanmb);
5353         ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5354         CONN_DEC_REF(connp);
5355         return;
5356 
5357 notfound:
5358         mutex_exit(&connfp->connf_lock);
5359         /*
5360          * IPv6 endpoints bound to multicast IPv4-mapped addresses
5361          * have already been matched above, since they live in the IPv4
5362          * fanout tables. This implies we only need to
5363          * check for IPv6 in6addr_any endpoints here.
5364          * Thus we compare using ipv6_all_zeros instead of the destination
5365          * address, except for the multicast group membership lookup which
5366          * uses the IPv4 destination.
5367          */
5368         IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5369         connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5370         mutex_enter(&connfp->connf_lock);
5371         connp = connfp->connf_head;
5372         /*
5373          * IPv4 multicast packet being delivered to an AF_INET6
5374          * in6addr_any endpoint.
5375          * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5376          * and not conn_wantpacket_v6() since any multicast membership is
5377          * for an IPv4-mapped multicast address.
5378          */
5379         while (connp != NULL) {
5380                 if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5381                     fport, v6faddr) &&
5382                     conn_wantpacket(connp, ira, ipha) &&
5383                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5384                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5385                         break;
5386                 connp = connp->conn_next;
5387         }
5388 
5389         if (connp == NULL) {
5390                 /*
5391                  * No one bound to this port.  Is
5392                  * there a client that wants all
5393                  * unclaimed datagrams?
5394                  */
5395                 mutex_exit(&connfp->connf_lock);
5396 
5397                 if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5398                     NULL) {
5399                         ASSERT(ira->ira_protocol == IPPROTO_UDP);
5400                         ip_fanout_proto_v4(mp, ipha, ira);
5401                 } else {
5402                         /*
5403                          * We used to attempt to send an icmp error here, but
5404                          * since this is known to be a multicast packet
5405                          * and we don't send icmp errors in response to
5406                          * multicast, just drop the packet and give up sooner.
5407                          */
5408                         BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5409                         freemsg(mp);
5410                 }
5411                 return;
5412         }
5413         CONN_INC_REF(connp);
5414         ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5415 
5416         /*
5417          * If SO_REUSEADDR has been set on the first we send the
5418          * packet to all clients that have joined the group and
5419          * match the port.
5420          */
5421         if (connp->conn_reuseaddr) {
5422                 conn_t          *first_connp = connp;
5423                 conn_t          *next_connp;
5424                 mblk_t          *mp1;
5425 
5426                 connp = connp->conn_next;
5427                 for (;;) {
5428                         while (connp != NULL) {
5429                                 if (IPCL_UDP_MATCH_V6(connp, lport,
5430                                     ipv6_all_zeros, fport, v6faddr) &&
5431                                     conn_wantpacket(connp, ira, ipha) &&
5432                                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5433                                     tsol_receive_local(mp, &laddr, IPV4_VERSION,
5434                                     ira, connp)))
5435                                         break;
5436                                 connp = connp->conn_next;
5437                         }
5438                         if (connp == NULL) {
5439                                 /* No more interested clients */
5440                                 connp = first_connp;
5441                                 break;
5442                         }
5443                         if (((mp1 = dupmsg(mp)) == NULL) &&
5444                             ((mp1 = copymsg(mp)) == NULL)) {
5445                                 /* Memory allocation failed */
5446                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5447                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
5448                                 connp = first_connp;
5449                                 break;
5450                         }
5451                         CONN_INC_REF(connp);
5452                         mutex_exit(&connfp->connf_lock);
5453 
5454                         IP_STAT(ipst, ip_udp_fanmb);
5455                         ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5456                             NULL, ira);
5457                         mutex_enter(&connfp->connf_lock);
5458                         /* Follow the next pointer before releasing the conn */
5459                         next_connp = connp->conn_next;
5460                         CONN_DEC_REF(connp);
5461                         connp = next_connp;
5462                 }
5463         }
5464 
5465         /* Last one.  Send it upstream. */
5466         mutex_exit(&connfp->connf_lock);
5467         IP_STAT(ipst, ip_udp_fanmb);
5468         ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5469         CONN_DEC_REF(connp);
5470 }
5471 
5472 /*
5473  * Split an incoming packet's IPv4 options into the label and the other options.
5474  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5475  * clearing out any leftover label or options.
5476  * Otherwise it just makes ipp point into the packet.
5477  *
5478  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5479  */
5480 int
5481 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5482 {
5483         uchar_t         *opt;
5484         uint32_t        totallen;
5485         uint32_t        optval;
5486         uint32_t        optlen;
5487 
5488         ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5489         ipp->ipp_hoplimit = ipha->ipha_ttl;
5490         ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5491         IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5492 
5493         /*
5494          * Get length (in 4 byte octets) of IP header options.
5495          */
5496         totallen = ipha->ipha_version_and_hdr_length -
5497             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5498 
5499         if (totallen == 0) {
5500                 if (!allocate)
5501                         return (0);
5502 
5503                 /* Clear out anything from a previous packet */
5504                 if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5505                         kmem_free(ipp->ipp_ipv4_options,
5506                             ipp->ipp_ipv4_options_len);
5507                         ipp->ipp_ipv4_options = NULL;
5508                         ipp->ipp_ipv4_options_len = 0;
5509                         ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5510                 }
5511                 if (ipp->ipp_fields & IPPF_LABEL_V4) {
5512                         kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5513                         ipp->ipp_label_v4 = NULL;
5514                         ipp->ipp_label_len_v4 = 0;
5515                         ipp->ipp_fields &= ~IPPF_LABEL_V4;
5516                 }
5517                 return (0);
5518         }
5519 
5520         totallen <<= 2;
5521         opt = (uchar_t *)&ipha[1];
5522         if (!is_system_labeled()) {
5523 
5524         copyall:
5525                 if (!allocate) {
5526                         if (totallen != 0) {
5527                                 ipp->ipp_ipv4_options = opt;
5528                                 ipp->ipp_ipv4_options_len = totallen;
5529                                 ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5530                         }
5531                         return (0);
5532                 }
5533                 /* Just copy all of options */
5534                 if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5535                         if (totallen == ipp->ipp_ipv4_options_len) {
5536                                 bcopy(opt, ipp->ipp_ipv4_options, totallen);
5537                                 return (0);
5538                         }
5539                         kmem_free(ipp->ipp_ipv4_options,
5540                             ipp->ipp_ipv4_options_len);
5541                         ipp->ipp_ipv4_options = NULL;
5542                         ipp->ipp_ipv4_options_len = 0;
5543                         ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5544                 }
5545                 if (totallen == 0)
5546                         return (0);
5547 
5548                 ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5549                 if (ipp->ipp_ipv4_options == NULL)
5550                         return (ENOMEM);
5551                 ipp->ipp_ipv4_options_len = totallen;
5552                 ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5553                 bcopy(opt, ipp->ipp_ipv4_options, totallen);
5554                 return (0);
5555         }
5556 
5557         if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5558                 kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5559                 ipp->ipp_label_v4 = NULL;
5560                 ipp->ipp_label_len_v4 = 0;
5561                 ipp->ipp_fields &= ~IPPF_LABEL_V4;
5562         }
5563 
5564         /*
5565          * Search for CIPSO option.
5566          * We assume CIPSO is first in options if it is present.
5567          * If it isn't, then ipp_opt_ipv4_options will not include the options
5568          * prior to the CIPSO option.
5569          */
5570         while (totallen != 0) {
5571                 switch (optval = opt[IPOPT_OPTVAL]) {
5572                 case IPOPT_EOL:
5573                         return (0);
5574                 case IPOPT_NOP:
5575                         optlen = 1;
5576                         break;
5577                 default:
5578                         if (totallen <= IPOPT_OLEN)
5579                                 return (EINVAL);
5580                         optlen = opt[IPOPT_OLEN];
5581                         if (optlen < 2)
5582                                 return (EINVAL);
5583                 }
5584                 if (optlen > totallen)
5585                         return (EINVAL);
5586 
5587                 switch (optval) {
5588                 case IPOPT_COMSEC:
5589                         if (!allocate) {
5590                                 ipp->ipp_label_v4 = opt;
5591                                 ipp->ipp_label_len_v4 = optlen;
5592                                 ipp->ipp_fields |= IPPF_LABEL_V4;
5593                         } else {
5594                                 ipp->ipp_label_v4 = kmem_alloc(optlen,
5595                                     KM_NOSLEEP);
5596                                 if (ipp->ipp_label_v4 == NULL)
5597                                         return (ENOMEM);
5598                                 ipp->ipp_label_len_v4 = optlen;
5599                                 ipp->ipp_fields |= IPPF_LABEL_V4;
5600                                 bcopy(opt, ipp->ipp_label_v4, optlen);
5601                         }
5602                         totallen -= optlen;
5603                         opt += optlen;
5604 
5605                         /* Skip padding bytes until we get to a multiple of 4 */
5606                         while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5607                                 totallen--;
5608                                 opt++;
5609                         }
5610                         /* Remaining as ipp_ipv4_options */
5611                         goto copyall;
5612                 }
5613                 totallen -= optlen;
5614                 opt += optlen;
5615         }
5616         /* No CIPSO found; return everything as ipp_ipv4_options */
5617         totallen = ipha->ipha_version_and_hdr_length -
5618             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5619         totallen <<= 2;
5620         opt = (uchar_t *)&ipha[1];
5621         goto copyall;
5622 }
5623 
5624 /*
5625  * Efficient versions of lookup for an IRE when we only
5626  * match the address.
5627  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5628  * Does not handle multicast addresses.
5629  */
5630 uint_t
5631 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5632 {
5633         ire_t *ire;
5634         uint_t result;
5635 
5636         ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5637         ASSERT(ire != NULL);
5638         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5639                 result = IRE_NOROUTE;
5640         else
5641                 result = ire->ire_type;
5642         ire_refrele(ire);
5643         return (result);
5644 }
5645 
5646 /*
5647  * Efficient versions of lookup for an IRE when we only
5648  * match the address.
5649  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5650  * Does not handle multicast addresses.
5651  */
5652 uint_t
5653 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5654 {
5655         ire_t *ire;
5656         uint_t result;
5657 
5658         ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5659         ASSERT(ire != NULL);
5660         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5661                 result = IRE_NOROUTE;
5662         else
5663                 result = ire->ire_type;
5664         ire_refrele(ire);
5665         return (result);
5666 }
5667 
5668 /*
5669  * Nobody should be sending
5670  * packets up this stream
5671  */
5672 static int
5673 ip_lrput(queue_t *q, mblk_t *mp)
5674 {
5675         switch (mp->b_datap->db_type) {
5676         case M_FLUSH:
5677                 /* Turn around */
5678                 if (*mp->b_rptr & FLUSHW) {
5679                         *mp->b_rptr &= ~FLUSHR;
5680                         qreply(q, mp);
5681                         return (0);
5682                 }
5683                 break;
5684         }
5685         freemsg(mp);
5686         return (0);
5687 }
5688 
5689 /* Nobody should be sending packets down this stream */
5690 /* ARGSUSED */
5691 int
5692 ip_lwput(queue_t *q, mblk_t *mp)
5693 {
5694         freemsg(mp);
5695         return (0);
5696 }
5697 
5698 /*
5699  * Move the first hop in any source route to ipha_dst and remove that part of
5700  * the source route.  Called by other protocols.  Errors in option formatting
5701  * are ignored - will be handled by ip_output_options. Return the final
5702  * destination (either ipha_dst or the last entry in a source route.)
5703  */
5704 ipaddr_t
5705 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5706 {
5707         ipoptp_t        opts;
5708         uchar_t         *opt;
5709         uint8_t         optval;
5710         uint8_t         optlen;
5711         ipaddr_t        dst;
5712         int             i;
5713         ip_stack_t      *ipst = ns->netstack_ip;
5714 
5715         ip2dbg(("ip_massage_options\n"));
5716         dst = ipha->ipha_dst;
5717         for (optval = ipoptp_first(&opts, ipha);
5718             optval != IPOPT_EOL;
5719             optval = ipoptp_next(&opts)) {
5720                 opt = opts.ipoptp_cur;
5721                 switch (optval) {
5722                         uint8_t off;
5723                 case IPOPT_SSRR:
5724                 case IPOPT_LSRR:
5725                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5726                                 ip1dbg(("ip_massage_options: bad src route\n"));
5727                                 break;
5728                         }
5729                         optlen = opts.ipoptp_len;
5730                         off = opt[IPOPT_OFFSET];
5731                         off--;
5732                 redo_srr:
5733                         if (optlen < IP_ADDR_LEN ||
5734                             off > optlen - IP_ADDR_LEN) {
5735                                 /* End of source route */
5736                                 ip1dbg(("ip_massage_options: end of SR\n"));
5737                                 break;
5738                         }
5739                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5740                         ip1dbg(("ip_massage_options: next hop 0x%x\n",
5741                             ntohl(dst)));
5742                         /*
5743                          * Check if our address is present more than
5744                          * once as consecutive hops in source route.
5745                          * XXX verify per-interface ip_forwarding
5746                          * for source route?
5747                          */
5748                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5749                                 off += IP_ADDR_LEN;
5750                                 goto redo_srr;
5751                         }
5752                         if (dst == htonl(INADDR_LOOPBACK)) {
5753                                 ip1dbg(("ip_massage_options: loopback addr in "
5754                                     "source route!\n"));
5755                                 break;
5756                         }
5757                         /*
5758                          * Update ipha_dst to be the first hop and remove the
5759                          * first hop from the source route (by overwriting
5760                          * part of the option with NOP options).
5761                          */
5762                         ipha->ipha_dst = dst;
5763                         /* Put the last entry in dst */
5764                         off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5765                             3;
5766                         bcopy(&opt[off], &dst, IP_ADDR_LEN);
5767 
5768                         ip1dbg(("ip_massage_options: last hop 0x%x\n",
5769                             ntohl(dst)));
5770                         /* Move down and overwrite */
5771                         opt[IP_ADDR_LEN] = opt[0];
5772                         opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5773                         opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5774                         for (i = 0; i < IP_ADDR_LEN; i++)
5775                                 opt[i] = IPOPT_NOP;
5776                         break;
5777                 }
5778         }
5779         return (dst);
5780 }
5781 
5782 /*
5783  * Return the network mask
5784  * associated with the specified address.
5785  */
5786 ipaddr_t
5787 ip_net_mask(ipaddr_t addr)
5788 {
5789         uchar_t *up = (uchar_t *)&addr;
5790         ipaddr_t mask = 0;
5791         uchar_t *maskp = (uchar_t *)&mask;
5792 
5793 #if defined(__i386) || defined(__amd64)
5794 #define TOTALLY_BRAIN_DAMAGED_C_COMPILER
5795 #endif
5796 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5797         maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5798 #endif
5799         if (CLASSD(addr)) {
5800                 maskp[0] = 0xF0;
5801                 return (mask);
5802         }
5803 
5804         /* We assume Class E default netmask to be 32 */
5805         if (CLASSE(addr))
5806                 return (0xffffffffU);
5807 
5808         if (addr == 0)
5809                 return (0);
5810         maskp[0] = 0xFF;
5811         if ((up[0] & 0x80) == 0)
5812                 return (mask);
5813 
5814         maskp[1] = 0xFF;
5815         if ((up[0] & 0xC0) == 0x80)
5816                 return (mask);
5817 
5818         maskp[2] = 0xFF;
5819         if ((up[0] & 0xE0) == 0xC0)
5820                 return (mask);
5821 
5822         /* Otherwise return no mask */
5823         return ((ipaddr_t)0);
5824 }
5825 
5826 /* Name/Value Table Lookup Routine */
5827 char *
5828 ip_nv_lookup(nv_t *nv, int value)
5829 {
5830         if (!nv)
5831                 return (NULL);
5832         for (; nv->nv_name; nv++) {
5833                 if (nv->nv_value == value)
5834                         return (nv->nv_name);
5835         }
5836         return ("unknown");
5837 }
5838 
5839 static int
5840 ip_wait_for_info_ack(ill_t *ill)
5841 {
5842         int err;
5843 
5844         mutex_enter(&ill->ill_lock);
5845         while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5846                 /*
5847                  * Return value of 0 indicates a pending signal.
5848                  */
5849                 err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5850                 if (err == 0) {
5851                         mutex_exit(&ill->ill_lock);
5852                         return (EINTR);
5853                 }
5854         }
5855         mutex_exit(&ill->ill_lock);
5856         /*
5857          * ip_rput_other could have set an error  in ill_error on
5858          * receipt of M_ERROR.
5859          */
5860         return (ill->ill_error);
5861 }
5862 
5863 /*
5864  * This is a module open, i.e. this is a control stream for access
5865  * to a DLPI device.  We allocate an ill_t as the instance data in
5866  * this case.
5867  */
5868 static int
5869 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5870 {
5871         ill_t   *ill;
5872         int     err;
5873         zoneid_t zoneid;
5874         netstack_t *ns;
5875         ip_stack_t *ipst;
5876 
5877         /*
5878          * Prevent unprivileged processes from pushing IP so that
5879          * they can't send raw IP.
5880          */
5881         if (secpolicy_net_rawaccess(credp) != 0)
5882                 return (EPERM);
5883 
5884         ns = netstack_find_by_cred(credp);
5885         ASSERT(ns != NULL);
5886         ipst = ns->netstack_ip;
5887         ASSERT(ipst != NULL);
5888 
5889         /*
5890          * For exclusive stacks we set the zoneid to zero
5891          * to make IP operate as if in the global zone.
5892          */
5893         if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5894                 zoneid = GLOBAL_ZONEID;
5895         else
5896                 zoneid = crgetzoneid(credp);
5897 
5898         ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5899         q->q_ptr = WR(q)->q_ptr = ill;
5900         ill->ill_ipst = ipst;
5901         ill->ill_zoneid = zoneid;
5902 
5903         /*
5904          * ill_init initializes the ill fields and then sends down
5905          * down a DL_INFO_REQ after calling qprocson.
5906          */
5907         err = ill_init(q, ill);
5908 
5909         if (err != 0) {
5910                 mi_free(ill);
5911                 netstack_rele(ipst->ips_netstack);
5912                 q->q_ptr = NULL;
5913                 WR(q)->q_ptr = NULL;
5914                 return (err);
5915         }
5916 
5917         /*
5918          * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5919          *
5920          * ill_init initializes the ipsq marking this thread as
5921          * writer
5922          */
5923         ipsq_exit(ill->ill_phyint->phyint_ipsq);
5924         err = ip_wait_for_info_ack(ill);
5925         if (err == 0)
5926                 ill->ill_credp = credp;
5927         else
5928                 goto fail;
5929 
5930         crhold(credp);
5931 
5932         mutex_enter(&ipst->ips_ip_mi_lock);
5933         err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5934             sflag, credp);
5935         mutex_exit(&ipst->ips_ip_mi_lock);
5936 fail:
5937         if (err) {
5938                 (void) ip_close(q, 0, credp);
5939                 return (err);
5940         }
5941         return (0);
5942 }
5943 
5944 /* For /dev/ip aka AF_INET open */
5945 int
5946 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5947 {
5948         return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5949 }
5950 
5951 /* For /dev/ip6 aka AF_INET6 open */
5952 int
5953 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5954 {
5955         return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5956 }
5957 
5958 /* IP open routine. */
5959 int
5960 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5961     boolean_t isv6)
5962 {
5963         conn_t          *connp;
5964         major_t         maj;
5965         zoneid_t        zoneid;
5966         netstack_t      *ns;
5967         ip_stack_t      *ipst;
5968 
5969         /* Allow reopen. */
5970         if (q->q_ptr != NULL)
5971                 return (0);
5972 
5973         if (sflag & MODOPEN) {
5974                 /* This is a module open */
5975                 return (ip_modopen(q, devp, flag, sflag, credp));
5976         }
5977 
5978         if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5979                 /*
5980                  * Non streams based socket looking for a stream
5981                  * to access IP
5982                  */
5983                 return (ip_helper_stream_setup(q, devp, flag, sflag,
5984                     credp, isv6));
5985         }
5986 
5987         ns = netstack_find_by_cred(credp);
5988         ASSERT(ns != NULL);
5989         ipst = ns->netstack_ip;
5990         ASSERT(ipst != NULL);
5991 
5992         /*
5993          * For exclusive stacks we set the zoneid to zero
5994          * to make IP operate as if in the global zone.
5995          */
5996         if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5997                 zoneid = GLOBAL_ZONEID;
5998         else
5999                 zoneid = crgetzoneid(credp);
6000 
6001         /*
6002          * We are opening as a device. This is an IP client stream, and we
6003          * allocate an conn_t as the instance data.
6004          */
6005         connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6006 
6007         /*
6008          * ipcl_conn_create did a netstack_hold. Undo the hold that was
6009          * done by netstack_find_by_cred()
6010          */
6011         netstack_rele(ipst->ips_netstack);
6012 
6013         connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6014         /* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6015         connp->conn_ixa->ixa_zoneid = zoneid;
6016         connp->conn_zoneid = zoneid;
6017 
6018         connp->conn_rq = q;
6019         q->q_ptr = WR(q)->q_ptr = connp;
6020 
6021         /* Minor tells us which /dev entry was opened */
6022         if (isv6) {
6023                 connp->conn_family = AF_INET6;
6024                 connp->conn_ipversion = IPV6_VERSION;
6025                 connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6026                 connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6027         } else {
6028                 connp->conn_family = AF_INET;
6029                 connp->conn_ipversion = IPV4_VERSION;
6030                 connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6031         }
6032 
6033         if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6034             ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6035                 connp->conn_minor_arena = ip_minor_arena_la;
6036         } else {
6037                 /*
6038                  * Either minor numbers in the large arena were exhausted
6039                  * or a non socket application is doing the open.
6040                  * Try to allocate from the small arena.
6041                  */
6042                 if ((connp->conn_dev =
6043                     inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6044                         /* CONN_DEC_REF takes care of netstack_rele() */
6045                         q->q_ptr = WR(q)->q_ptr = NULL;
6046                         CONN_DEC_REF(connp);
6047                         return (EBUSY);
6048                 }
6049                 connp->conn_minor_arena = ip_minor_arena_sa;
6050         }
6051 
6052         maj = getemajor(*devp);
6053         *devp = makedevice(maj, (minor_t)connp->conn_dev);
6054 
6055         /*
6056          * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6057          */
6058         connp->conn_cred = credp;
6059         connp->conn_cpid = curproc->p_pid;
6060         /* Cache things in ixa without an extra refhold */
6061         ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6062         connp->conn_ixa->ixa_cred = connp->conn_cred;
6063         connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6064         if (is_system_labeled())
6065                 connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6066 
6067         /*
6068          * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6069          */
6070         connp->conn_recv = ip_conn_input;
6071         connp->conn_recvicmp = ip_conn_input_icmp;
6072 
6073         crhold(connp->conn_cred);
6074 
6075         /*
6076          * If the caller has the process-wide flag set, then default to MAC
6077          * exempt mode.  This allows read-down to unlabeled hosts.
6078          */
6079         if (getpflags(NET_MAC_AWARE, credp) != 0)
6080                 connp->conn_mac_mode = CONN_MAC_AWARE;
6081 
6082         connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6083 
6084         connp->conn_rq = q;
6085         connp->conn_wq = WR(q);
6086 
6087         /* Non-zero default values */
6088         connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6089 
6090         /*
6091          * Make the conn globally visible to walkers
6092          */
6093         ASSERT(connp->conn_ref == 1);
6094         mutex_enter(&connp->conn_lock);
6095         connp->conn_state_flags &= ~CONN_INCIPIENT;
6096         mutex_exit(&connp->conn_lock);
6097 
6098         qprocson(q);
6099 
6100         return (0);
6101 }
6102 
6103 /*
6104  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6105  * all of them are copied to the conn_t. If the req is "zero", the policy is
6106  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6107  * fields.
6108  * We keep only the latest setting of the policy and thus policy setting
6109  * is not incremental/cumulative.
6110  *
6111  * Requests to set policies with multiple alternative actions will
6112  * go through a different API.
6113  */
6114 int
6115 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6116 {
6117         uint_t ah_req = 0;
6118         uint_t esp_req = 0;
6119         uint_t se_req = 0;
6120         ipsec_act_t *actp = NULL;
6121         uint_t nact;
6122         ipsec_policy_head_t *ph;
6123         boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6124         int error = 0;
6125         netstack_t      *ns = connp->conn_netstack;
6126         ip_stack_t      *ipst = ns->netstack_ip;
6127         ipsec_stack_t   *ipss = ns->netstack_ipsec;
6128 
6129 #define REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6130 
6131         /*
6132          * The IP_SEC_OPT option does not allow variable length parameters,
6133          * hence a request cannot be NULL.
6134          */
6135         if (req == NULL)
6136                 return (EINVAL);
6137 
6138         ah_req = req->ipsr_ah_req;
6139         esp_req = req->ipsr_esp_req;
6140         se_req = req->ipsr_self_encap_req;
6141 
6142         /* Don't allow setting self-encap without one or more of AH/ESP. */
6143         if (se_req != 0 && esp_req == 0 && ah_req == 0)
6144                 return (EINVAL);
6145 
6146         /*
6147          * Are we dealing with a request to reset the policy (i.e.
6148          * zero requests).
6149          */
6150         is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6151             (esp_req & REQ_MASK) == 0 &&
6152             (se_req & REQ_MASK) == 0);
6153 
6154         if (!is_pol_reset) {
6155                 /*
6156                  * If we couldn't load IPsec, fail with "protocol
6157                  * not supported".
6158                  * IPsec may not have been loaded for a request with zero
6159                  * policies, so we don't fail in this case.
6160                  */
6161                 mutex_enter(&ipss->ipsec_loader_lock);
6162                 if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6163                         mutex_exit(&ipss->ipsec_loader_lock);
6164                         return (EPROTONOSUPPORT);
6165                 }
6166                 mutex_exit(&ipss->ipsec_loader_lock);
6167 
6168                 /*
6169                  * Test for valid requests. Invalid algorithms
6170                  * need to be tested by IPsec code because new
6171                  * algorithms can be added dynamically.
6172                  */
6173                 if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6174                     (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6175                     (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6176                         return (EINVAL);
6177                 }
6178 
6179                 /*
6180                  * Only privileged users can issue these
6181                  * requests.
6182                  */
6183                 if (((ah_req & IPSEC_PREF_NEVER) ||
6184                     (esp_req & IPSEC_PREF_NEVER) ||
6185                     (se_req & IPSEC_PREF_NEVER)) &&
6186                     secpolicy_ip_config(cr, B_FALSE) != 0) {
6187                         return (EPERM);
6188                 }
6189 
6190                 /*
6191                  * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6192                  * are mutually exclusive.
6193                  */
6194                 if (((ah_req & REQ_MASK) == REQ_MASK) ||
6195                     ((esp_req & REQ_MASK) == REQ_MASK) ||
6196                     ((se_req & REQ_MASK) == REQ_MASK)) {
6197                         /* Both of them are set */
6198                         return (EINVAL);
6199                 }
6200         }
6201 
6202         ASSERT(MUTEX_HELD(&connp->conn_lock));
6203 
6204         /*
6205          * If we have already cached policies in conn_connect(), don't
6206          * let them change now. We cache policies for connections
6207          * whose src,dst [addr, port] is known.
6208          */
6209         if (connp->conn_policy_cached) {
6210                 return (EINVAL);
6211         }
6212 
6213         /*
6214          * We have a zero policies, reset the connection policy if already
6215          * set. This will cause the connection to inherit the
6216          * global policy, if any.
6217          */
6218         if (is_pol_reset) {
6219                 if (connp->conn_policy != NULL) {
6220                         IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6221                         connp->conn_policy = NULL;
6222                 }
6223                 connp->conn_in_enforce_policy = B_FALSE;
6224                 connp->conn_out_enforce_policy = B_FALSE;
6225                 return (0);
6226         }
6227 
6228         ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6229             ipst->ips_netstack);
6230         if (ph == NULL)
6231                 goto enomem;
6232 
6233         ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6234         if (actp == NULL)
6235                 goto enomem;
6236 
6237         /*
6238          * Always insert IPv4 policy entries, since they can also apply to
6239          * ipv6 sockets being used in ipv4-compat mode.
6240          */
6241         if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6242             IPSEC_TYPE_INBOUND, ns))
6243                 goto enomem;
6244         is_pol_inserted = B_TRUE;
6245         if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6246             IPSEC_TYPE_OUTBOUND, ns))
6247                 goto enomem;
6248 
6249         /*
6250          * We're looking at a v6 socket, also insert the v6-specific
6251          * entries.
6252          */
6253         if (connp->conn_family == AF_INET6) {
6254                 if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6255                     IPSEC_TYPE_INBOUND, ns))
6256                         goto enomem;
6257                 if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6258                     IPSEC_TYPE_OUTBOUND, ns))
6259                         goto enomem;
6260         }
6261 
6262         ipsec_actvec_free(actp, nact);
6263 
6264         /*
6265          * If the requests need security, set enforce_policy.
6266          * If the requests are IPSEC_PREF_NEVER, one should
6267          * still set conn_out_enforce_policy so that ip_set_destination
6268          * marks the ip_xmit_attr_t appropriatly. This is needed so that
6269          * for connections that we don't cache policy in at connect time,
6270          * if global policy matches in ip_output_attach_policy, we
6271          * don't wrongly inherit global policy. Similarly, we need
6272          * to set conn_in_enforce_policy also so that we don't verify
6273          * policy wrongly.
6274          */
6275         if ((ah_req & REQ_MASK) != 0 ||
6276             (esp_req & REQ_MASK) != 0 ||
6277             (se_req & REQ_MASK) != 0) {
6278                 connp->conn_in_enforce_policy = B_TRUE;
6279                 connp->conn_out_enforce_policy = B_TRUE;
6280         }
6281 
6282         return (error);
6283 #undef REQ_MASK
6284 
6285         /*
6286          * Common memory-allocation-failure exit path.
6287          */
6288 enomem:
6289         if (actp != NULL)
6290                 ipsec_actvec_free(actp, nact);
6291         if (is_pol_inserted)
6292                 ipsec_polhead_flush(ph, ns);
6293         return (ENOMEM);
6294 }
6295 
6296 /*
6297  * Set socket options for joining and leaving multicast groups.
6298  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6299  * The caller has already check that the option name is consistent with
6300  * the address family of the socket.
6301  */
6302 int
6303 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6304     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6305 {
6306         int             *i1 = (int *)invalp;
6307         int             error = 0;
6308         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
6309         struct ip_mreq  *v4_mreqp;
6310         struct ipv6_mreq *v6_mreqp;
6311         struct group_req *greqp;
6312         ire_t *ire;
6313         boolean_t done = B_FALSE;
6314         ipaddr_t ifaddr;
6315         in6_addr_t v6group;
6316         uint_t ifindex;
6317         boolean_t mcast_opt = B_TRUE;
6318         mcast_record_t fmode;
6319         int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6320             ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6321 
6322         switch (name) {
6323         case IP_ADD_MEMBERSHIP:
6324         case IPV6_JOIN_GROUP:
6325                 mcast_opt = B_FALSE;
6326                 /* FALLTHROUGH */
6327         case MCAST_JOIN_GROUP:
6328                 fmode = MODE_IS_EXCLUDE;
6329                 optfn = ip_opt_add_group;
6330                 break;
6331 
6332         case IP_DROP_MEMBERSHIP:
6333         case IPV6_LEAVE_GROUP:
6334                 mcast_opt = B_FALSE;
6335                 /* FALLTHROUGH */
6336         case MCAST_LEAVE_GROUP:
6337                 fmode = MODE_IS_INCLUDE;
6338                 optfn = ip_opt_delete_group;
6339                 break;
6340         default:
6341                 ASSERT(0);
6342         }
6343 
6344         if (mcast_opt) {
6345                 struct sockaddr_in *sin;
6346                 struct sockaddr_in6 *sin6;
6347 
6348                 greqp = (struct group_req *)i1;
6349                 if (greqp->gr_group.ss_family == AF_INET) {
6350                         sin = (struct sockaddr_in *)&(greqp->gr_group);
6351                         IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6352                 } else {
6353                         if (!inet6)
6354                                 return (EINVAL);        /* Not on INET socket */
6355 
6356                         sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6357                         v6group = sin6->sin6_addr;
6358                 }
6359                 ifaddr = INADDR_ANY;
6360                 ifindex = greqp->gr_interface;
6361         } else if (inet6) {
6362                 v6_mreqp = (struct ipv6_mreq *)i1;
6363                 v6group = v6_mreqp->ipv6mr_multiaddr;
6364                 ifaddr = INADDR_ANY;
6365                 ifindex = v6_mreqp->ipv6mr_interface;
6366         } else {
6367                 v4_mreqp = (struct ip_mreq *)i1;
6368                 IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6369                 ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6370                 ifindex = 0;
6371         }
6372 
6373         /*
6374          * In the multirouting case, we need to replicate
6375          * the request on all interfaces that will take part
6376          * in replication.  We do so because multirouting is
6377          * reflective, thus we will probably receive multi-
6378          * casts on those interfaces.
6379          * The ip_multirt_apply_membership() succeeds if
6380          * the operation succeeds on at least one interface.
6381          */
6382         if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6383                 ipaddr_t group;
6384 
6385                 IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6386 
6387                 ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6388                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6389                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6390         } else {
6391                 ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6392                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6393                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6394         }
6395         if (ire != NULL) {
6396                 if (ire->ire_flags & RTF_MULTIRT) {
6397                         error = ip_multirt_apply_membership(optfn, ire, connp,
6398                             checkonly, &v6group, fmode, &ipv6_all_zeros);
6399                         done = B_TRUE;
6400                 }
6401                 ire_refrele(ire);
6402         }
6403 
6404         if (!done) {
6405                 error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6406                     fmode, &ipv6_all_zeros);
6407         }
6408         return (error);
6409 }
6410 
6411 /*
6412  * Set socket options for joining and leaving multicast groups
6413  * for specific sources.
6414  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6415  * The caller has already check that the option name is consistent with
6416  * the address family of the socket.
6417  */
6418 int
6419 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6420     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6421 {
6422         int             *i1 = (int *)invalp;
6423         int             error = 0;
6424         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
6425         struct ip_mreq_source *imreqp;
6426         struct group_source_req *gsreqp;
6427         in6_addr_t v6group, v6src;
6428         uint32_t ifindex;
6429         ipaddr_t ifaddr;
6430         boolean_t mcast_opt = B_TRUE;
6431         mcast_record_t fmode;
6432         ire_t *ire;
6433         boolean_t done = B_FALSE;
6434         int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6435             ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6436 
6437         switch (name) {
6438         case IP_BLOCK_SOURCE:
6439                 mcast_opt = B_FALSE;
6440                 /* FALLTHROUGH */
6441         case MCAST_BLOCK_SOURCE:
6442                 fmode = MODE_IS_EXCLUDE;
6443                 optfn = ip_opt_add_group;
6444                 break;
6445 
6446         case IP_UNBLOCK_SOURCE:
6447                 mcast_opt = B_FALSE;
6448                 /* FALLTHROUGH */
6449         case MCAST_UNBLOCK_SOURCE:
6450                 fmode = MODE_IS_EXCLUDE;
6451                 optfn = ip_opt_delete_group;
6452                 break;
6453 
6454         case IP_ADD_SOURCE_MEMBERSHIP:
6455                 mcast_opt = B_FALSE;
6456                 /* FALLTHROUGH */
6457         case MCAST_JOIN_SOURCE_GROUP:
6458                 fmode = MODE_IS_INCLUDE;
6459                 optfn = ip_opt_add_group;
6460                 break;
6461 
6462         case IP_DROP_SOURCE_MEMBERSHIP:
6463                 mcast_opt = B_FALSE;
6464                 /* FALLTHROUGH */
6465         case MCAST_LEAVE_SOURCE_GROUP:
6466                 fmode = MODE_IS_INCLUDE;
6467                 optfn = ip_opt_delete_group;
6468                 break;
6469         default:
6470                 ASSERT(0);
6471         }
6472 
6473         if (mcast_opt) {
6474                 gsreqp = (struct group_source_req *)i1;
6475                 ifindex = gsreqp->gsr_interface;
6476                 if (gsreqp->gsr_group.ss_family == AF_INET) {
6477                         struct sockaddr_in *s;
6478                         s = (struct sockaddr_in *)&gsreqp->gsr_group;
6479                         IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6480                         s = (struct sockaddr_in *)&gsreqp->gsr_source;
6481                         IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6482                 } else {
6483                         struct sockaddr_in6 *s6;
6484 
6485                         if (!inet6)
6486                                 return (EINVAL);        /* Not on INET socket */
6487 
6488                         s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6489                         v6group = s6->sin6_addr;
6490                         s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6491                         v6src = s6->sin6_addr;
6492                 }
6493                 ifaddr = INADDR_ANY;
6494         } else {
6495                 imreqp = (struct ip_mreq_source *)i1;
6496                 IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6497                 IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6498                 ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6499                 ifindex = 0;
6500         }
6501 
6502         /*
6503          * Handle src being mapped INADDR_ANY by changing it to unspecified.
6504          */
6505         if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6506                 v6src = ipv6_all_zeros;
6507 
6508         /*
6509          * In the multirouting case, we need to replicate
6510          * the request as noted in the mcast cases above.
6511          */
6512         if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6513                 ipaddr_t group;
6514 
6515                 IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6516 
6517                 ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6518                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6519                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6520         } else {
6521                 ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6522                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6523                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6524         }
6525         if (ire != NULL) {
6526                 if (ire->ire_flags & RTF_MULTIRT) {
6527                         error = ip_multirt_apply_membership(optfn, ire, connp,
6528                             checkonly, &v6group, fmode, &v6src);
6529                         done = B_TRUE;
6530                 }
6531                 ire_refrele(ire);
6532         }
6533         if (!done) {
6534                 error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6535                     fmode, &v6src);
6536         }
6537         return (error);
6538 }
6539 
6540 /*
6541  * Given a destination address and a pointer to where to put the information
6542  * this routine fills in the mtuinfo.
6543  * The socket must be connected.
6544  * For sctp conn_faddr is the primary address.
6545  */
6546 int
6547 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6548 {
6549         uint32_t        pmtu = IP_MAXPACKET;
6550         uint_t          scopeid;
6551 
6552         if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6553                 return (-1);
6554 
6555         /* In case we never sent or called ip_set_destination_v4/v6 */
6556         if (ixa->ixa_ire != NULL)
6557                 pmtu = ip_get_pmtu(ixa);
6558 
6559         if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6560                 scopeid = ixa->ixa_scopeid;
6561         else
6562                 scopeid = 0;
6563 
6564         bzero(mtuinfo, sizeof (*mtuinfo));
6565         mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6566         mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6567         mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6568         mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6569         mtuinfo->ip6m_mtu = pmtu;
6570 
6571         return (sizeof (struct ip6_mtuinfo));
6572 }
6573 
6574 /*
6575  * When the src multihoming is changed from weak to [strong, preferred]
6576  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6577  * and identify routes that were created by user-applications in the
6578  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6579  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6580  * is selected by finding an interface route for the gateway.
6581  */
6582 /* ARGSUSED */
6583 void
6584 ip_ire_rebind_walker(ire_t *ire, void *notused)
6585 {
6586         if (!ire->ire_unbound || ire->ire_ill != NULL)
6587                 return;
6588         ire_rebind(ire);
6589         ire_delete(ire);
6590 }
6591 
6592 /*
6593  * When the src multihoming is changed from  [strong, preferred] to weak,
6594  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6595  * set any entries that were created by user-applications in the unbound state
6596  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6597  */
6598 /* ARGSUSED */
6599 void
6600 ip_ire_unbind_walker(ire_t *ire, void *notused)
6601 {
6602         ire_t *new_ire;
6603 
6604         if (!ire->ire_unbound || ire->ire_ill == NULL)
6605                 return;
6606         if (ire->ire_ipversion == IPV6_VERSION) {
6607                 new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6608                     &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6609                     ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6610         } else {
6611                 new_ire = ire_create((uchar_t *)&ire->ire_addr,
6612                     (uchar_t *)&ire->ire_mask,
6613                     (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6614                     ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6615         }
6616         if (new_ire == NULL)
6617                 return;
6618         new_ire->ire_unbound = B_TRUE;
6619         /*
6620          * The bound ire must first be deleted so that we don't return
6621          * the existing one on the attempt to add the unbound new_ire.
6622          */
6623         ire_delete(ire);
6624         new_ire = ire_add(new_ire);
6625         if (new_ire != NULL)
6626                 ire_refrele(new_ire);
6627 }
6628 
6629 /*
6630  * When the settings of ip*_strict_src_multihoming tunables are changed,
6631  * all cached routes need to be recomputed. This recomputation needs to be
6632  * done when going from weaker to stronger modes so that the cached ire
6633  * for the connection does not violate the current ip*_strict_src_multihoming
6634  * setting. It also needs to be done when going from stronger to weaker modes,
6635  * so that we fall back to matching on the longest-matching-route (as opposed
6636  * to a shorter match that may have been selected in the strong mode
6637  * to satisfy src_multihoming settings).
6638  *
6639  * The cached ixa_ire entires for all conn_t entries are marked as
6640  * "verify" so that they will be recomputed for the next packet.
6641  */
6642 void
6643 conn_ire_revalidate(conn_t *connp, void *arg)
6644 {
6645         boolean_t isv6 = (boolean_t)arg;
6646 
6647         if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6648             (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6649                 return;
6650         connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6651 }
6652 
6653 /*
6654  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6655  * When an ipf is passed here for the first time, if
6656  * we already have in-order fragments on the queue, we convert from the fast-
6657  * path reassembly scheme to the hard-case scheme.  From then on, additional
6658  * fragments are reassembled here.  We keep track of the start and end offsets
6659  * of each piece, and the number of holes in the chain.  When the hole count
6660  * goes to zero, we are done!
6661  *
6662  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6663  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6664  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6665  * after the call to ip_reassemble().
6666  */
6667 int
6668 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6669     size_t msg_len)
6670 {
6671         uint_t  end;
6672         mblk_t  *next_mp;
6673         mblk_t  *mp1;
6674         uint_t  offset;
6675         boolean_t incr_dups = B_TRUE;
6676         boolean_t offset_zero_seen = B_FALSE;
6677         boolean_t pkt_boundary_checked = B_FALSE;
6678 
6679         /* If start == 0 then ipf_nf_hdr_len has to be set. */
6680         ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6681 
6682         /* Add in byte count */
6683         ipf->ipf_count += msg_len;
6684         if (ipf->ipf_end) {
6685                 /*
6686                  * We were part way through in-order reassembly, but now there
6687                  * is a hole.  We walk through messages already queued, and
6688                  * mark them for hard case reassembly.  We know that up till
6689                  * now they were in order starting from offset zero.
6690                  */
6691                 offset = 0;
6692                 for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6693                         IP_REASS_SET_START(mp1, offset);
6694                         if (offset == 0) {
6695                                 ASSERT(ipf->ipf_nf_hdr_len != 0);
6696                                 offset = -ipf->ipf_nf_hdr_len;
6697                         }
6698                         offset += mp1->b_wptr - mp1->b_rptr;
6699                         IP_REASS_SET_END(mp1, offset);
6700                 }
6701                 /* One hole at the end. */
6702                 ipf->ipf_hole_cnt = 1;
6703                 /* Brand it as a hard case, forever. */
6704                 ipf->ipf_end = 0;
6705         }
6706         /* Walk through all the new pieces. */
6707         do {
6708                 end = start + (mp->b_wptr - mp->b_rptr);
6709                 /*
6710                  * If start is 0, decrease 'end' only for the first mblk of
6711                  * the fragment. Otherwise 'end' can get wrong value in the
6712                  * second pass of the loop if first mblk is exactly the
6713                  * size of ipf_nf_hdr_len.
6714                  */
6715                 if (start == 0 && !offset_zero_seen) {
6716                         /* First segment */
6717                         ASSERT(ipf->ipf_nf_hdr_len != 0);
6718                         end -= ipf->ipf_nf_hdr_len;
6719                         offset_zero_seen = B_TRUE;
6720                 }
6721                 next_mp = mp->b_cont;
6722                 /*
6723                  * We are checking to see if there is any interesing data
6724                  * to process.  If there isn't and the mblk isn't the
6725                  * one which carries the unfragmentable header then we
6726                  * drop it.  It's possible to have just the unfragmentable
6727                  * header come through without any data.  That needs to be
6728                  * saved.
6729                  *
6730                  * If the assert at the top of this function holds then the
6731                  * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6732                  * is infrequently traveled enough that the test is left in
6733                  * to protect against future code changes which break that
6734                  * invariant.
6735                  */
6736                 if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6737                         /* Empty.  Blast it. */
6738                         IP_REASS_SET_START(mp, 0);
6739                         IP_REASS_SET_END(mp, 0);
6740                         /*
6741                          * If the ipf points to the mblk we are about to free,
6742                          * update ipf to point to the next mblk (or NULL
6743                          * if none).
6744                          */
6745                         if (ipf->ipf_mp->b_cont == mp)
6746                                 ipf->ipf_mp->b_cont = next_mp;
6747                         freeb(mp);
6748                         continue;
6749                 }
6750                 mp->b_cont = NULL;
6751                 IP_REASS_SET_START(mp, start);
6752                 IP_REASS_SET_END(mp, end);
6753                 if (!ipf->ipf_tail_mp) {
6754                         ipf->ipf_tail_mp = mp;
6755                         ipf->ipf_mp->b_cont = mp;
6756                         if (start == 0 || !more) {
6757                                 ipf->ipf_hole_cnt = 1;
6758                                 /*
6759                                  * if the first fragment comes in more than one
6760                                  * mblk, this loop will be executed for each
6761                                  * mblk. Need to adjust hole count so exiting
6762                                  * this routine will leave hole count at 1.
6763                                  */
6764                                 if (next_mp)
6765                                         ipf->ipf_hole_cnt++;
6766                         } else
6767                                 ipf->ipf_hole_cnt = 2;
6768                         continue;
6769                 } else if (ipf->ipf_last_frag_seen && !more &&
6770                     !pkt_boundary_checked) {
6771                         /*
6772                          * We check datagram boundary only if this fragment
6773                          * claims to be the last fragment and we have seen a
6774                          * last fragment in the past too. We do this only
6775                          * once for a given fragment.
6776                          *
6777                          * start cannot be 0 here as fragments with start=0
6778                          * and MF=0 gets handled as a complete packet. These
6779                          * fragments should not reach here.
6780                          */
6781 
6782                         if (start + msgdsize(mp) !=
6783                             IP_REASS_END(ipf->ipf_tail_mp)) {
6784                                 /*
6785                                  * We have two fragments both of which claim
6786                                  * to be the last fragment but gives conflicting
6787                                  * information about the whole datagram size.
6788                                  * Something fishy is going on. Drop the
6789                                  * fragment and free up the reassembly list.
6790                                  */
6791                                 return (IP_REASS_FAILED);
6792                         }
6793 
6794                         /*
6795                          * We shouldn't come to this code block again for this
6796                          * particular fragment.
6797                          */
6798                         pkt_boundary_checked = B_TRUE;
6799                 }
6800 
6801                 /* New stuff at or beyond tail? */
6802                 offset = IP_REASS_END(ipf->ipf_tail_mp);
6803                 if (start >= offset) {
6804                         if (ipf->ipf_last_frag_seen) {
6805                                 /* current fragment is beyond last fragment */
6806                                 return (IP_REASS_FAILED);
6807                         }
6808                         /* Link it on end. */
6809                         ipf->ipf_tail_mp->b_cont = mp;
6810                         ipf->ipf_tail_mp = mp;
6811                         if (more) {
6812                                 if (start != offset)
6813                                         ipf->ipf_hole_cnt++;
6814                         } else if (start == offset && next_mp == NULL)
6815                                         ipf->ipf_hole_cnt--;
6816                         continue;
6817                 }
6818                 mp1 = ipf->ipf_mp->b_cont;
6819                 offset = IP_REASS_START(mp1);
6820                 /* New stuff at the front? */
6821                 if (start < offset) {
6822                         if (start == 0) {
6823                                 if (end >= offset) {
6824                                         /* Nailed the hole at the begining. */
6825                                         ipf->ipf_hole_cnt--;
6826                                 }
6827                         } else if (end < offset) {
6828                                 /*
6829                                  * A hole, stuff, and a hole where there used
6830                                  * to be just a hole.
6831                                  */
6832                                 ipf->ipf_hole_cnt++;
6833                         }
6834                         mp->b_cont = mp1;
6835                         /* Check for overlap. */
6836                         while (end > offset) {
6837                                 if (end < IP_REASS_END(mp1)) {
6838                                         mp->b_wptr -= end - offset;
6839                                         IP_REASS_SET_END(mp, offset);
6840                                         BUMP_MIB(ill->ill_ip_mib,
6841                                             ipIfStatsReasmPartDups);
6842                                         break;
6843                                 }
6844                                 /* Did we cover another hole? */
6845                                 if ((mp1->b_cont &&
6846                                     IP_REASS_END(mp1) !=
6847                                     IP_REASS_START(mp1->b_cont) &&
6848                                     end >= IP_REASS_START(mp1->b_cont)) ||
6849                                     (!ipf->ipf_last_frag_seen && !more)) {
6850                                         ipf->ipf_hole_cnt--;
6851                                 }
6852                                 /* Clip out mp1. */
6853                                 if ((mp->b_cont = mp1->b_cont) == NULL) {
6854                                         /*
6855                                          * After clipping out mp1, this guy
6856                                          * is now hanging off the end.
6857                                          */
6858                                         ipf->ipf_tail_mp = mp;
6859                                 }
6860                                 IP_REASS_SET_START(mp1, 0);
6861                                 IP_REASS_SET_END(mp1, 0);
6862                                 /* Subtract byte count */
6863                                 ipf->ipf_count -= mp1->b_datap->db_lim -
6864                                     mp1->b_datap->db_base;
6865                                 freeb(mp1);
6866                                 BUMP_MIB(ill->ill_ip_mib,
6867                                     ipIfStatsReasmPartDups);
6868                                 mp1 = mp->b_cont;
6869                                 if (!mp1)
6870                                         break;
6871                                 offset = IP_REASS_START(mp1);
6872                         }
6873                         ipf->ipf_mp->b_cont = mp;
6874                         continue;
6875                 }
6876                 /*
6877                  * The new piece starts somewhere between the start of the head
6878                  * and before the end of the tail.
6879                  */
6880                 for (; mp1; mp1 = mp1->b_cont) {
6881                         offset = IP_REASS_END(mp1);
6882                         if (start < offset) {
6883                                 if (end <= offset) {
6884                                         /* Nothing new. */
6885                                         IP_REASS_SET_START(mp, 0);
6886                                         IP_REASS_SET_END(mp, 0);
6887                                         /* Subtract byte count */
6888                                         ipf->ipf_count -= mp->b_datap->db_lim -
6889                                             mp->b_datap->db_base;
6890                                         if (incr_dups) {
6891                                                 ipf->ipf_num_dups++;
6892                                                 incr_dups = B_FALSE;
6893                                         }
6894                                         freeb(mp);
6895                                         BUMP_MIB(ill->ill_ip_mib,
6896                                             ipIfStatsReasmDuplicates);
6897                                         break;
6898                                 }
6899                                 /*
6900                                  * Trim redundant stuff off beginning of new
6901                                  * piece.
6902                                  */
6903                                 IP_REASS_SET_START(mp, offset);
6904                                 mp->b_rptr += offset - start;
6905                                 BUMP_MIB(ill->ill_ip_mib,
6906                                     ipIfStatsReasmPartDups);
6907                                 start = offset;
6908                                 if (!mp1->b_cont) {
6909                                         /*
6910                                          * After trimming, this guy is now
6911                                          * hanging off the end.
6912                                          */
6913                                         mp1->b_cont = mp;
6914                                         ipf->ipf_tail_mp = mp;
6915                                         if (!more) {
6916                                                 ipf->ipf_hole_cnt--;
6917                                         }
6918                                         break;
6919                                 }
6920                         }
6921                         if (start >= IP_REASS_START(mp1->b_cont))
6922                                 continue;
6923                         /* Fill a hole */
6924                         if (start > offset)
6925                                 ipf->ipf_hole_cnt++;
6926                         mp->b_cont = mp1->b_cont;
6927                         mp1->b_cont = mp;
6928                         mp1 = mp->b_cont;
6929                         offset = IP_REASS_START(mp1);
6930                         if (end >= offset) {
6931                                 ipf->ipf_hole_cnt--;
6932                                 /* Check for overlap. */
6933                                 while (end > offset) {
6934                                         if (end < IP_REASS_END(mp1)) {
6935                                                 mp->b_wptr -= end - offset;
6936                                                 IP_REASS_SET_END(mp, offset);
6937                                                 /*
6938                                                  * TODO we might bump
6939                                                  * this up twice if there is
6940                                                  * overlap at both ends.
6941                                                  */
6942                                                 BUMP_MIB(ill->ill_ip_mib,
6943                                                     ipIfStatsReasmPartDups);
6944                                                 break;
6945                                         }
6946                                         /* Did we cover another hole? */
6947                                         if ((mp1->b_cont &&
6948                                             IP_REASS_END(mp1)
6949                                             != IP_REASS_START(mp1->b_cont) &&
6950                                             end >=
6951                                             IP_REASS_START(mp1->b_cont)) ||
6952                                             (!ipf->ipf_last_frag_seen &&
6953                                             !more)) {
6954                                                 ipf->ipf_hole_cnt--;
6955                                         }
6956                                         /* Clip out mp1. */
6957                                         if ((mp->b_cont = mp1->b_cont) ==
6958                                             NULL) {
6959                                                 /*
6960                                                  * After clipping out mp1,
6961                                                  * this guy is now hanging
6962                                                  * off the end.
6963                                                  */
6964                                                 ipf->ipf_tail_mp = mp;
6965                                         }
6966                                         IP_REASS_SET_START(mp1, 0);
6967                                         IP_REASS_SET_END(mp1, 0);
6968                                         /* Subtract byte count */
6969                                         ipf->ipf_count -=
6970                                             mp1->b_datap->db_lim -
6971                                             mp1->b_datap->db_base;
6972                                         freeb(mp1);
6973                                         BUMP_MIB(ill->ill_ip_mib,
6974                                             ipIfStatsReasmPartDups);
6975                                         mp1 = mp->b_cont;
6976                                         if (!mp1)
6977                                                 break;
6978                                         offset = IP_REASS_START(mp1);
6979                                 }
6980                         }
6981                         break;
6982                 }
6983         } while (start = end, mp = next_mp);
6984 
6985         /* Fragment just processed could be the last one. Remember this fact */
6986         if (!more)
6987                 ipf->ipf_last_frag_seen = B_TRUE;
6988 
6989         /* Still got holes? */
6990         if (ipf->ipf_hole_cnt)
6991                 return (IP_REASS_PARTIAL);
6992         /* Clean up overloaded fields to avoid upstream disasters. */
6993         for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6994                 IP_REASS_SET_START(mp1, 0);
6995                 IP_REASS_SET_END(mp1, 0);
6996         }
6997         return (IP_REASS_COMPLETE);
6998 }
6999 
7000 /*
7001  * Fragmentation reassembly.  Each ILL has a hash table for
7002  * queuing packets undergoing reassembly for all IPIFs
7003  * associated with the ILL.  The hash is based on the packet
7004  * IP ident field.  The ILL frag hash table was allocated
7005  * as a timer block at the time the ILL was created.  Whenever
7006  * there is anything on the reassembly queue, the timer will
7007  * be running.  Returns the reassembled packet if reassembly completes.
7008  */
7009 mblk_t *
7010 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7011 {
7012         uint32_t        frag_offset_flags;
7013         mblk_t          *t_mp;
7014         ipaddr_t        dst;
7015         uint8_t         proto = ipha->ipha_protocol;
7016         uint32_t        sum_val;
7017         uint16_t        sum_flags;
7018         ipf_t           *ipf;
7019         ipf_t           **ipfp;
7020         ipfb_t          *ipfb;
7021         uint16_t        ident;
7022         uint32_t        offset;
7023         ipaddr_t        src;
7024         uint_t          hdr_length;
7025         uint32_t        end;
7026         mblk_t          *mp1;
7027         mblk_t          *tail_mp;
7028         size_t          count;
7029         size_t          msg_len;
7030         uint8_t         ecn_info = 0;
7031         uint32_t        packet_size;
7032         boolean_t       pruned = B_FALSE;
7033         ill_t           *ill = ira->ira_ill;
7034         ip_stack_t      *ipst = ill->ill_ipst;
7035 
7036         /*
7037          * Drop the fragmented as early as possible, if
7038          * we don't have resource(s) to re-assemble.
7039          */
7040         if (ipst->ips_ip_reass_queue_bytes == 0) {
7041                 freemsg(mp);
7042                 return (NULL);
7043         }
7044 
7045         /* Check for fragmentation offset; return if there's none */
7046         if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7047             (IPH_MF | IPH_OFFSET)) == 0)
7048                 return (mp);
7049 
7050         /*
7051          * We utilize hardware computed checksum info only for UDP since
7052          * IP fragmentation is a normal occurrence for the protocol.  In
7053          * addition, checksum offload support for IP fragments carrying
7054          * UDP payload is commonly implemented across network adapters.
7055          */
7056         ASSERT(ira->ira_rill != NULL);
7057         if (proto == IPPROTO_UDP && dohwcksum &&
7058             ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7059             (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7060                 mblk_t *mp1 = mp->b_cont;
7061                 int32_t len;
7062 
7063                 /* Record checksum information from the packet */
7064                 sum_val = (uint32_t)DB_CKSUM16(mp);
7065                 sum_flags = DB_CKSUMFLAGS(mp);
7066 
7067                 /* IP payload offset from beginning of mblk */
7068                 offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7069 
7070                 if ((sum_flags & HCK_PARTIALCKSUM) &&
7071                     (mp1 == NULL || mp1->b_cont == NULL) &&
7072                     offset >= DB_CKSUMSTART(mp) &&
7073                     ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7074                         uint32_t adj;
7075                         /*
7076                          * Partial checksum has been calculated by hardware
7077                          * and attached to the packet; in addition, any
7078                          * prepended extraneous data is even byte aligned.
7079                          * If any such data exists, we adjust the checksum;
7080                          * this would also handle any postpended data.
7081                          */
7082                         IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7083                             mp, mp1, len, adj);
7084 
7085                         /* One's complement subtract extraneous checksum */
7086                         if (adj >= sum_val)
7087                                 sum_val = ~(adj - sum_val) & 0xFFFF;
7088                         else
7089                                 sum_val -= adj;
7090                 }
7091         } else {
7092                 sum_val = 0;
7093                 sum_flags = 0;
7094         }
7095 
7096         /* Clear hardware checksumming flag */
7097         DB_CKSUMFLAGS(mp) = 0;
7098 
7099         ident = ipha->ipha_ident;
7100         offset = (frag_offset_flags << 3) & 0xFFFF;
7101         src = ipha->ipha_src;
7102         dst = ipha->ipha_dst;
7103         hdr_length = IPH_HDR_LENGTH(ipha);
7104         end = ntohs(ipha->ipha_length) - hdr_length;
7105 
7106         /* If end == 0 then we have a packet with no data, so just free it */
7107         if (end == 0) {
7108                 freemsg(mp);
7109                 return (NULL);
7110         }
7111 
7112         /* Record the ECN field info. */
7113         ecn_info = (ipha->ipha_type_of_service & 0x3);
7114         if (offset != 0) {
7115                 /*
7116                  * If this isn't the first piece, strip the header, and
7117                  * add the offset to the end value.
7118                  */
7119                 mp->b_rptr += hdr_length;
7120                 end += offset;
7121         }
7122 
7123         /* Handle vnic loopback of fragments */
7124         if (mp->b_datap->db_ref > 2)
7125                 msg_len = 0;
7126         else
7127                 msg_len = MBLKSIZE(mp);
7128 
7129         tail_mp = mp;
7130         while (tail_mp->b_cont != NULL) {
7131                 tail_mp = tail_mp->b_cont;
7132                 if (tail_mp->b_datap->db_ref <= 2)
7133                         msg_len += MBLKSIZE(tail_mp);
7134         }
7135 
7136         /* If the reassembly list for this ILL will get too big, prune it */
7137         if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7138             ipst->ips_ip_reass_queue_bytes) {
7139                 DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7140                     uint_t, ill->ill_frag_count,
7141                     uint_t, ipst->ips_ip_reass_queue_bytes);
7142                 ill_frag_prune(ill,
7143                     (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7144                     (ipst->ips_ip_reass_queue_bytes - msg_len));
7145                 pruned = B_TRUE;
7146         }
7147 
7148         ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7149         mutex_enter(&ipfb->ipfb_lock);
7150 
7151         ipfp = &ipfb->ipfb_ipf;
7152         /* Try to find an existing fragment queue for this packet. */
7153         for (;;) {
7154                 ipf = ipfp[0];
7155                 if (ipf != NULL) {
7156                         /*
7157                          * It has to match on ident and src/dst address.
7158                          */
7159                         if (ipf->ipf_ident == ident &&
7160                             ipf->ipf_src == src &&
7161                             ipf->ipf_dst == dst &&
7162                             ipf->ipf_protocol == proto) {
7163                                 /*
7164                                  * If we have received too many
7165                                  * duplicate fragments for this packet
7166                                  * free it.
7167                                  */
7168                                 if (ipf->ipf_num_dups > ip_max_frag_dups) {
7169                                         ill_frag_free_pkts(ill, ipfb, ipf, 1);
7170                                         freemsg(mp);
7171                                         mutex_exit(&ipfb->ipfb_lock);
7172                                         return (NULL);
7173                                 }
7174                                 /* Found it. */
7175                                 break;
7176                         }
7177                         ipfp = &ipf->ipf_hash_next;
7178                         continue;
7179                 }
7180 
7181                 /*
7182                  * If we pruned the list, do we want to store this new
7183                  * fragment?. We apply an optimization here based on the
7184                  * fact that most fragments will be received in order.
7185                  * So if the offset of this incoming fragment is zero,
7186                  * it is the first fragment of a new packet. We will
7187                  * keep it.  Otherwise drop the fragment, as we have
7188                  * probably pruned the packet already (since the
7189                  * packet cannot be found).
7190                  */
7191                 if (pruned && offset != 0) {
7192                         mutex_exit(&ipfb->ipfb_lock);
7193                         freemsg(mp);
7194                         return (NULL);
7195                 }
7196 
7197                 if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7198                         /*
7199                          * Too many fragmented packets in this hash
7200                          * bucket. Free the oldest.
7201                          */
7202                         ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7203                 }
7204 
7205                 /* New guy.  Allocate a frag message. */
7206                 mp1 = allocb(sizeof (*ipf), BPRI_MED);
7207                 if (mp1 == NULL) {
7208                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7209                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7210                         freemsg(mp);
7211 reass_done:
7212                         mutex_exit(&ipfb->ipfb_lock);
7213                         return (NULL);
7214                 }
7215 
7216                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7217                 mp1->b_cont = mp;
7218 
7219                 /* Initialize the fragment header. */
7220                 ipf = (ipf_t *)mp1->b_rptr;
7221                 ipf->ipf_mp = mp1;
7222                 ipf->ipf_ptphn = ipfp;
7223                 ipfp[0] = ipf;
7224                 ipf->ipf_hash_next = NULL;
7225                 ipf->ipf_ident = ident;
7226                 ipf->ipf_protocol = proto;
7227                 ipf->ipf_src = src;
7228                 ipf->ipf_dst = dst;
7229                 ipf->ipf_nf_hdr_len = 0;
7230                 /* Record reassembly start time. */
7231                 ipf->ipf_timestamp = gethrestime_sec();
7232                 /* Record ipf generation and account for frag header */
7233                 ipf->ipf_gen = ill->ill_ipf_gen++;
7234                 ipf->ipf_count = MBLKSIZE(mp1);
7235                 ipf->ipf_last_frag_seen = B_FALSE;
7236                 ipf->ipf_ecn = ecn_info;
7237                 ipf->ipf_num_dups = 0;
7238                 ipfb->ipfb_frag_pkts++;
7239                 ipf->ipf_checksum = 0;
7240                 ipf->ipf_checksum_flags = 0;
7241 
7242                 /* Store checksum value in fragment header */
7243                 if (sum_flags != 0) {
7244                         sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7245                         sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7246                         ipf->ipf_checksum = sum_val;
7247                         ipf->ipf_checksum_flags = sum_flags;
7248                 }
7249 
7250                 /*
7251                  * We handle reassembly two ways.  In the easy case,
7252                  * where all the fragments show up in order, we do
7253                  * minimal bookkeeping, and just clip new pieces on
7254                  * the end.  If we ever see a hole, then we go off
7255                  * to ip_reassemble which has to mark the pieces and
7256                  * keep track of the number of holes, etc.  Obviously,
7257                  * the point of having both mechanisms is so we can
7258                  * handle the easy case as efficiently as possible.
7259                  */
7260                 if (offset == 0) {
7261                         /* Easy case, in-order reassembly so far. */
7262                         ipf->ipf_count += msg_len;
7263                         ipf->ipf_tail_mp = tail_mp;
7264                         /*
7265                          * Keep track of next expected offset in
7266                          * ipf_end.
7267                          */
7268                         ipf->ipf_end = end;
7269                         ipf->ipf_nf_hdr_len = hdr_length;
7270                 } else {
7271                         /* Hard case, hole at the beginning. */
7272                         ipf->ipf_tail_mp = NULL;
7273                         /*
7274                          * ipf_end == 0 means that we have given up
7275                          * on easy reassembly.
7276                          */
7277                         ipf->ipf_end = 0;
7278 
7279                         /* Forget checksum offload from now on */
7280                         ipf->ipf_checksum_flags = 0;
7281 
7282                         /*
7283                          * ipf_hole_cnt is set by ip_reassemble.
7284                          * ipf_count is updated by ip_reassemble.
7285                          * No need to check for return value here
7286                          * as we don't expect reassembly to complete
7287                          * or fail for the first fragment itself.
7288                          */
7289                         (void) ip_reassemble(mp, ipf,
7290                             (frag_offset_flags & IPH_OFFSET) << 3,
7291                             (frag_offset_flags & IPH_MF), ill, msg_len);
7292                 }
7293                 /* Update per ipfb and ill byte counts */
7294                 ipfb->ipfb_count += ipf->ipf_count;
7295                 ASSERT(ipfb->ipfb_count > 0);     /* Wraparound */
7296                 atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7297                 /* If the frag timer wasn't already going, start it. */
7298                 mutex_enter(&ill->ill_lock);
7299                 ill_frag_timer_start(ill);
7300                 mutex_exit(&ill->ill_lock);
7301                 goto reass_done;
7302         }
7303 
7304         /*
7305          * If the packet's flag has changed (it could be coming up
7306          * from an interface different than the previous, therefore
7307          * possibly different checksum capability), then forget about
7308          * any stored checksum states.  Otherwise add the value to
7309          * the existing one stored in the fragment header.
7310          */
7311         if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7312                 sum_val += ipf->ipf_checksum;
7313                 sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7314                 sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7315                 ipf->ipf_checksum = sum_val;
7316         } else if (ipf->ipf_checksum_flags != 0) {
7317                 /* Forget checksum offload from now on */
7318                 ipf->ipf_checksum_flags = 0;
7319         }
7320 
7321         /*
7322          * We have a new piece of a datagram which is already being
7323          * reassembled.  Update the ECN info if all IP fragments
7324          * are ECN capable.  If there is one which is not, clear
7325          * all the info.  If there is at least one which has CE
7326          * code point, IP needs to report that up to transport.
7327          */
7328         if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7329                 if (ecn_info == IPH_ECN_CE)
7330                         ipf->ipf_ecn = IPH_ECN_CE;
7331         } else {
7332                 ipf->ipf_ecn = IPH_ECN_NECT;
7333         }
7334         if (offset && ipf->ipf_end == offset) {
7335                 /* The new fragment fits at the end */
7336                 ipf->ipf_tail_mp->b_cont = mp;
7337                 /* Update the byte count */
7338                 ipf->ipf_count += msg_len;
7339                 /* Update per ipfb and ill byte counts */
7340                 ipfb->ipfb_count += msg_len;
7341                 ASSERT(ipfb->ipfb_count > 0);     /* Wraparound */
7342                 atomic_add_32(&ill->ill_frag_count, msg_len);
7343                 if (frag_offset_flags & IPH_MF) {
7344                         /* More to come. */
7345                         ipf->ipf_end = end;
7346                         ipf->ipf_tail_mp = tail_mp;
7347                         goto reass_done;
7348                 }
7349         } else {
7350                 /* Go do the hard cases. */
7351                 int ret;
7352 
7353                 if (offset == 0)
7354                         ipf->ipf_nf_hdr_len = hdr_length;
7355 
7356                 /* Save current byte count */
7357                 count = ipf->ipf_count;
7358                 ret = ip_reassemble(mp, ipf,
7359                     (frag_offset_flags & IPH_OFFSET) << 3,
7360                     (frag_offset_flags & IPH_MF), ill, msg_len);
7361                 /* Count of bytes added and subtracted (freeb()ed) */
7362                 count = ipf->ipf_count - count;
7363                 if (count) {
7364                         /* Update per ipfb and ill byte counts */
7365                         ipfb->ipfb_count += count;
7366                         ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7367                         atomic_add_32(&ill->ill_frag_count, count);
7368                 }
7369                 if (ret == IP_REASS_PARTIAL) {
7370                         goto reass_done;
7371                 } else if (ret == IP_REASS_FAILED) {
7372                         /* Reassembly failed. Free up all resources */
7373                         ill_frag_free_pkts(ill, ipfb, ipf, 1);
7374                         for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7375                                 IP_REASS_SET_START(t_mp, 0);
7376                                 IP_REASS_SET_END(t_mp, 0);
7377                         }
7378                         freemsg(mp);
7379                         goto reass_done;
7380                 }
7381                 /* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7382         }
7383         /*
7384          * We have completed reassembly.  Unhook the frag header from
7385          * the reassembly list.
7386          *
7387          * Before we free the frag header, record the ECN info
7388          * to report back to the transport.
7389          */
7390         ecn_info = ipf->ipf_ecn;
7391         BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7392         ipfp = ipf->ipf_ptphn;
7393 
7394         /* We need to supply these to caller */
7395         if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7396                 sum_val = ipf->ipf_checksum;
7397         else
7398                 sum_val = 0;
7399 
7400         mp1 = ipf->ipf_mp;
7401         count = ipf->ipf_count;
7402         ipf = ipf->ipf_hash_next;
7403         if (ipf != NULL)
7404                 ipf->ipf_ptphn = ipfp;
7405         ipfp[0] = ipf;
7406         atomic_add_32(&ill->ill_frag_count, -count);
7407         ASSERT(ipfb->ipfb_count >= count);
7408         ipfb->ipfb_count -= count;
7409         ipfb->ipfb_frag_pkts--;
7410         mutex_exit(&ipfb->ipfb_lock);
7411         /* Ditch the frag header. */
7412         mp = mp1->b_cont;
7413 
7414         freeb(mp1);
7415 
7416         /* Restore original IP length in header. */
7417         packet_size = (uint32_t)msgdsize(mp);
7418         if (packet_size > IP_MAXPACKET) {
7419                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7420                 ip_drop_input("Reassembled packet too large", mp, ill);
7421                 freemsg(mp);
7422                 return (NULL);
7423         }
7424 
7425         if (DB_REF(mp) > 1) {
7426                 mblk_t *mp2 = copymsg(mp);
7427 
7428                 if (mp2 == NULL) {
7429                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7430                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7431                         freemsg(mp);
7432                         return (NULL);
7433                 }
7434                 freemsg(mp);
7435                 mp = mp2;
7436         }
7437         ipha = (ipha_t *)mp->b_rptr;
7438 
7439         ipha->ipha_length = htons((uint16_t)packet_size);
7440         /* We're now complete, zip the frag state */
7441         ipha->ipha_fragment_offset_and_flags = 0;
7442         /* Record the ECN info. */
7443         ipha->ipha_type_of_service &= 0xFC;
7444         ipha->ipha_type_of_service |= ecn_info;
7445 
7446         /* Update the receive attributes */
7447         ira->ira_pktlen = packet_size;
7448         ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7449 
7450         /* Reassembly is successful; set checksum information in packet */
7451         DB_CKSUM16(mp) = (uint16_t)sum_val;
7452         DB_CKSUMFLAGS(mp) = sum_flags;
7453         DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7454 
7455         return (mp);
7456 }
7457 
7458 /*
7459  * Pullup function that should be used for IP input in order to
7460  * ensure we do not loose the L2 source address; we need the l2 source
7461  * address for IP_RECVSLLA and for ndp_input.
7462  *
7463  * We return either NULL or b_rptr.
7464  */
7465 void *
7466 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7467 {
7468         ill_t           *ill = ira->ira_ill;
7469 
7470         if (ip_rput_pullups++ == 0) {
7471                 (void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7472                     "ip_pullup: %s forced us to "
7473                     " pullup pkt, hdr len %ld, hdr addr %p",
7474                     ill->ill_name, len, (void *)mp->b_rptr);
7475         }
7476         if (!(ira->ira_flags & IRAF_L2SRC_SET))
7477                 ip_setl2src(mp, ira, ira->ira_rill);
7478         ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7479         if (!pullupmsg(mp, len))
7480                 return (NULL);
7481         else
7482                 return (mp->b_rptr);
7483 }
7484 
7485 /*
7486  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7487  * When called from the ULP ira_rill will be NULL hence the caller has to
7488  * pass in the ill.
7489  */
7490 /* ARGSUSED */
7491 void
7492 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7493 {
7494         const uchar_t *addr;
7495         int alen;
7496 
7497         if (ira->ira_flags & IRAF_L2SRC_SET)
7498                 return;
7499 
7500         ASSERT(ill != NULL);
7501         alen = ill->ill_phys_addr_length;
7502         ASSERT(alen <= sizeof (ira->ira_l2src));
7503         if (ira->ira_mhip != NULL &&
7504             (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7505                 bcopy(addr, ira->ira_l2src, alen);
7506         } else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7507             (addr = ill->ill_phys_addr) != NULL) {
7508                 bcopy(addr, ira->ira_l2src, alen);
7509         } else {
7510                 bzero(ira->ira_l2src, alen);
7511         }
7512         ira->ira_flags |= IRAF_L2SRC_SET;
7513 }
7514 
7515 /*
7516  * check ip header length and align it.
7517  */
7518 mblk_t *
7519 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7520 {
7521         ill_t   *ill = ira->ira_ill;
7522         ssize_t len;
7523 
7524         len = MBLKL(mp);
7525 
7526         if (!OK_32PTR(mp->b_rptr))
7527                 IP_STAT(ill->ill_ipst, ip_notaligned);
7528         else
7529                 IP_STAT(ill->ill_ipst, ip_recv_pullup);
7530 
7531         /* Guard against bogus device drivers */
7532         if (len < 0) {
7533                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7534                 ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7535                 freemsg(mp);
7536                 return (NULL);
7537         }
7538 
7539         if (len == 0) {
7540                 /* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7541                 mblk_t *mp1 = mp->b_cont;
7542 
7543                 if (!(ira->ira_flags & IRAF_L2SRC_SET))
7544                         ip_setl2src(mp, ira, ira->ira_rill);
7545                 ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7546 
7547                 freeb(mp);
7548                 mp = mp1;
7549                 if (mp == NULL)
7550                         return (NULL);
7551 
7552                 if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7553                         return (mp);
7554         }
7555         if (ip_pullup(mp, min_size, ira) == NULL) {
7556                 if (msgdsize(mp) < min_size) {
7557                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7558                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7559                 } else {
7560                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7561                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7562                 }
7563                 freemsg(mp);
7564                 return (NULL);
7565         }
7566         return (mp);
7567 }
7568 
7569 /*
7570  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7571  */
7572 mblk_t *
7573 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len, uint_t pkt_len,
7574     uint_t min_size, ip_recv_attr_t *ira)
7575 {
7576         ill_t   *ill = ira->ira_ill;
7577 
7578         /*
7579          * Make sure we have data length consistent
7580          * with the IP header.
7581          */
7582         if (mp->b_cont == NULL) {
7583                 /* pkt_len is based on ipha_len, not the mblk length */
7584                 if (pkt_len < min_size) {
7585                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7586                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7587                         freemsg(mp);
7588                         return (NULL);
7589                 }
7590                 if (len < 0) {
7591                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7592                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7593                         freemsg(mp);
7594                         return (NULL);
7595                 }
7596                 /* Drop any pad */
7597                 mp->b_wptr = rptr + pkt_len;
7598         } else if ((len += msgdsize(mp->b_cont)) != 0) {
7599                 ASSERT(pkt_len >= min_size);
7600                 if (pkt_len < min_size) {
7601                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7602                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7603                         freemsg(mp);
7604                         return (NULL);
7605                 }
7606                 if (len < 0) {
7607                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7608                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7609                         freemsg(mp);
7610                         return (NULL);
7611                 }
7612                 /* Drop any pad */
7613                 (void) adjmsg(mp, -len);
7614                 /*
7615                  * adjmsg may have freed an mblk from the chain, hence
7616                  * invalidate any hw checksum here. This will force IP to
7617                  * calculate the checksum in sw, but only for this packet.
7618                  */
7619                 DB_CKSUMFLAGS(mp) = 0;
7620                 IP_STAT(ill->ill_ipst, ip_multimblk);
7621         }
7622         return (mp);
7623 }
7624 
7625 /*
7626  * Check that the IPv4 opt_len is consistent with the packet and pullup
7627  * the options.
7628  */
7629 mblk_t *
7630 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7631     ip_recv_attr_t *ira)
7632 {
7633         ill_t   *ill = ira->ira_ill;
7634         ssize_t len;
7635 
7636         /* Assume no IPv6 packets arrive over the IPv4 queue */
7637         if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7638                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7639                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7640                 ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7641                 freemsg(mp);
7642                 return (NULL);
7643         }
7644 
7645         if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7646                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7647                 ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7648                 freemsg(mp);
7649                 return (NULL);
7650         }
7651         /*
7652          * Recompute complete header length and make sure we
7653          * have access to all of it.
7654          */
7655         len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7656         if (len > (mp->b_wptr - mp->b_rptr)) {
7657                 if (len > pkt_len) {
7658                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7659                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7660                         freemsg(mp);
7661                         return (NULL);
7662                 }
7663                 if (ip_pullup(mp, len, ira) == NULL) {
7664                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7665                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7666                         freemsg(mp);
7667                         return (NULL);
7668                 }
7669         }
7670         return (mp);
7671 }
7672 
7673 /*
7674  * Returns a new ire, or the same ire, or NULL.
7675  * If a different IRE is returned, then it is held; the caller
7676  * needs to release it.
7677  * In no case is there any hold/release on the ire argument.
7678  */
7679 ire_t *
7680 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7681 {
7682         ire_t           *new_ire;
7683         ill_t           *ire_ill;
7684         uint_t          ifindex;
7685         ip_stack_t      *ipst = ill->ill_ipst;
7686         boolean_t       strict_check = B_FALSE;
7687 
7688         /*
7689          * IPMP common case: if IRE and ILL are in the same group, there's no
7690          * issue (e.g. packet received on an underlying interface matched an
7691          * IRE_LOCAL on its associated group interface).
7692          */
7693         ASSERT(ire->ire_ill != NULL);
7694         if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7695                 return (ire);
7696 
7697         /*
7698          * Do another ire lookup here, using the ingress ill, to see if the
7699          * interface is in a usesrc group.
7700          * As long as the ills belong to the same group, we don't consider
7701          * them to be arriving on the wrong interface. Thus, if the switch
7702          * is doing inbound load spreading, we won't drop packets when the
7703          * ip*_strict_dst_multihoming switch is on.
7704          * We also need to check for IPIF_UNNUMBERED point2point interfaces
7705          * where the local address may not be unique. In this case we were
7706          * at the mercy of the initial ire lookup and the IRE_LOCAL it
7707          * actually returned. The new lookup, which is more specific, should
7708          * only find the IRE_LOCAL associated with the ingress ill if one
7709          * exists.
7710          */
7711         if (ire->ire_ipversion == IPV4_VERSION) {
7712                 if (ipst->ips_ip_strict_dst_multihoming)
7713                         strict_check = B_TRUE;
7714                 new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7715                     IRE_LOCAL, ill, ALL_ZONES, NULL,
7716                     (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7717         } else {
7718                 ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7719                 if (ipst->ips_ipv6_strict_dst_multihoming)
7720                         strict_check = B_TRUE;
7721                 new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7722                     IRE_LOCAL, ill, ALL_ZONES, NULL,
7723                     (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7724         }
7725         /*
7726          * If the same ire that was returned in ip_input() is found then this
7727          * is an indication that usesrc groups are in use. The packet
7728          * arrived on a different ill in the group than the one associated with
7729          * the destination address.  If a different ire was found then the same
7730          * IP address must be hosted on multiple ills. This is possible with
7731          * unnumbered point2point interfaces. We switch to use this new ire in
7732          * order to have accurate interface statistics.
7733          */
7734         if (new_ire != NULL) {
7735                 /* Note: held in one case but not the other? Caller handles */
7736                 if (new_ire != ire)
7737                         return (new_ire);
7738                 /* Unchanged */
7739                 ire_refrele(new_ire);
7740                 return (ire);
7741         }
7742 
7743         /*
7744          * Chase pointers once and store locally.
7745          */
7746         ASSERT(ire->ire_ill != NULL);
7747         ire_ill = ire->ire_ill;
7748         ifindex = ill->ill_usesrc_ifindex;
7749 
7750         /*
7751          * Check if it's a legal address on the 'usesrc' interface.
7752          * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7753          * can just check phyint_ifindex.
7754          */
7755         if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7756                 return (ire);
7757         }
7758 
7759         /*
7760          * If the ip*_strict_dst_multihoming switch is on then we can
7761          * only accept this packet if the interface is marked as routing.
7762          */
7763         if (!(strict_check))
7764                 return (ire);
7765 
7766         if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7767                 return (ire);
7768         }
7769         return (NULL);
7770 }
7771 
7772 /*
7773  * This function is used to construct a mac_header_info_s from a
7774  * DL_UNITDATA_IND message.
7775  * The address fields in the mhi structure points into the message,
7776  * thus the caller can't use those fields after freeing the message.
7777  *
7778  * We determine whether the packet received is a non-unicast packet
7779  * and in doing so, determine whether or not it is broadcast vs multicast.
7780  * For it to be a broadcast packet, we must have the appropriate mblk_t
7781  * hanging off the ill_t.  If this is either not present or doesn't match
7782  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7783  * to be multicast.  Thus NICs that have no broadcast address (or no
7784  * capability for one, such as point to point links) cannot return as
7785  * the packet being broadcast.
7786  */
7787 void
7788 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7789 {
7790         dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7791         mblk_t *bmp;
7792         uint_t extra_offset;
7793 
7794         bzero(mhip, sizeof (struct mac_header_info_s));
7795 
7796         mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7797 
7798         if (ill->ill_sap_length < 0)
7799                 extra_offset = 0;
7800         else
7801                 extra_offset = ill->ill_sap_length;
7802 
7803         mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7804             extra_offset;
7805         mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7806             extra_offset;
7807 
7808         if (!ind->dl_group_address)
7809                 return;
7810 
7811         /* Multicast or broadcast */
7812         mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7813 
7814         if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7815             ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7816             (bmp = ill->ill_bcast_mp) != NULL) {
7817                 dl_unitdata_req_t *dlur;
7818                 uint8_t *bphys_addr;
7819 
7820                 dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7821                 bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7822                     extra_offset;
7823 
7824                 if (bcmp(mhip->mhi_daddr, bphys_addr,
7825                     ind->dl_dest_addr_length) == 0)
7826                         mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7827         }
7828 }
7829 
7830 /*
7831  * This function is used to construct a mac_header_info_s from a
7832  * M_DATA fastpath message from a DLPI driver.
7833  * The address fields in the mhi structure points into the message,
7834  * thus the caller can't use those fields after freeing the message.
7835  *
7836  * We determine whether the packet received is a non-unicast packet
7837  * and in doing so, determine whether or not it is broadcast vs multicast.
7838  * For it to be a broadcast packet, we must have the appropriate mblk_t
7839  * hanging off the ill_t.  If this is either not present or doesn't match
7840  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7841  * to be multicast.  Thus NICs that have no broadcast address (or no
7842  * capability for one, such as point to point links) cannot return as
7843  * the packet being broadcast.
7844  */
7845 void
7846 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7847 {
7848         mblk_t *bmp;
7849         struct ether_header *pether;
7850 
7851         bzero(mhip, sizeof (struct mac_header_info_s));
7852 
7853         mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7854 
7855         pether = (struct ether_header *)((char *)mp->b_rptr
7856             - sizeof (struct ether_header));
7857 
7858         /*
7859          * Make sure the interface is an ethernet type, since we don't
7860          * know the header format for anything but Ethernet. Also make
7861          * sure we are pointing correctly above db_base.
7862          */
7863         if (ill->ill_type != IFT_ETHER)
7864                 return;
7865 
7866 retry:
7867         if ((uchar_t *)pether < mp->b_datap->db_base)
7868                 return;
7869 
7870         /* Is there a VLAN tag? */
7871         if (ill->ill_isv6) {
7872                 if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7873                         pether = (struct ether_header *)((char *)pether - 4);
7874                         goto retry;
7875                 }
7876         } else {
7877                 if (pether->ether_type != htons(ETHERTYPE_IP)) {
7878                         pether = (struct ether_header *)((char *)pether - 4);
7879                         goto retry;
7880                 }
7881         }
7882         mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7883         mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7884 
7885         if (!(mhip->mhi_daddr[0] & 0x01))
7886                 return;
7887 
7888         /* Multicast or broadcast */
7889         mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7890 
7891         if ((bmp = ill->ill_bcast_mp) != NULL) {
7892                 dl_unitdata_req_t *dlur;
7893                 uint8_t *bphys_addr;
7894                 uint_t  addrlen;
7895 
7896                 dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7897                 addrlen = dlur->dl_dest_addr_length;
7898                 if (ill->ill_sap_length < 0) {
7899                         bphys_addr = (uchar_t *)dlur +
7900                             dlur->dl_dest_addr_offset;
7901                         addrlen += ill->ill_sap_length;
7902                 } else {
7903                         bphys_addr = (uchar_t *)dlur +
7904                             dlur->dl_dest_addr_offset +
7905                             ill->ill_sap_length;
7906                         addrlen -= ill->ill_sap_length;
7907                 }
7908                 if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7909                         mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7910         }
7911 }
7912 
7913 /*
7914  * Handle anything but M_DATA messages
7915  * We see the DL_UNITDATA_IND which are part
7916  * of the data path, and also the other messages from the driver.
7917  */
7918 void
7919 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7920 {
7921         mblk_t          *first_mp;
7922         struct iocblk   *iocp;
7923         struct mac_header_info_s mhi;
7924 
7925         switch (DB_TYPE(mp)) {
7926         case M_PROTO:
7927         case M_PCPROTO: {
7928                 if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7929                     DL_UNITDATA_IND) {
7930                         /* Go handle anything other than data elsewhere. */
7931                         ip_rput_dlpi(ill, mp);
7932                         return;
7933                 }
7934 
7935                 first_mp = mp;
7936                 mp = first_mp->b_cont;
7937                 first_mp->b_cont = NULL;
7938 
7939                 if (mp == NULL) {
7940                         freeb(first_mp);
7941                         return;
7942                 }
7943                 ip_dlur_to_mhi(ill, first_mp, &mhi);
7944                 if (ill->ill_isv6)
7945                         ip_input_v6(ill, NULL, mp, &mhi);
7946                 else
7947                         ip_input(ill, NULL, mp, &mhi);
7948 
7949                 /* Ditch the DLPI header. */
7950                 freeb(first_mp);
7951                 return;
7952         }
7953         case M_IOCACK:
7954                 iocp = (struct iocblk *)mp->b_rptr;
7955                 switch (iocp->ioc_cmd) {
7956                 case DL_IOC_HDR_INFO:
7957                         ill_fastpath_ack(ill, mp);
7958                         return;
7959                 default:
7960                         putnext(ill->ill_rq, mp);
7961                         return;
7962                 }
7963                 /* FALLTHROUGH */
7964         case M_ERROR:
7965         case M_HANGUP:
7966                 mutex_enter(&ill->ill_lock);
7967                 if (ill->ill_state_flags & ILL_CONDEMNED) {
7968                         mutex_exit(&ill->ill_lock);
7969                         freemsg(mp);
7970                         return;
7971                 }
7972                 ill_refhold_locked(ill);
7973                 mutex_exit(&ill->ill_lock);
7974                 qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7975                     B_FALSE);
7976                 return;
7977         case M_CTL:
7978                 putnext(ill->ill_rq, mp);
7979                 return;
7980         case M_IOCNAK:
7981                 ip1dbg(("got iocnak "));
7982                 iocp = (struct iocblk *)mp->b_rptr;
7983                 switch (iocp->ioc_cmd) {
7984                 case DL_IOC_HDR_INFO:
7985                         ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7986                         return;
7987                 default:
7988                         break;
7989                 }
7990                 /* FALLTHROUGH */
7991         default:
7992                 putnext(ill->ill_rq, mp);
7993                 return;
7994         }
7995 }
7996 
7997 /* Read side put procedure.  Packets coming from the wire arrive here. */
7998 int
7999 ip_rput(queue_t *q, mblk_t *mp)
8000 {
8001         ill_t   *ill;
8002         union DL_primitives *dl;
8003 
8004         ill = (ill_t *)q->q_ptr;
8005 
8006         if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8007                 /*
8008                  * If things are opening or closing, only accept high-priority
8009                  * DLPI messages.  (On open ill->ill_ipif has not yet been
8010                  * created; on close, things hanging off the ill may have been
8011                  * freed already.)
8012                  */
8013                 dl = (union DL_primitives *)mp->b_rptr;
8014                 if (DB_TYPE(mp) != M_PCPROTO ||
8015                     dl->dl_primitive == DL_UNITDATA_IND) {
8016                         inet_freemsg(mp);
8017                         return (0);
8018                 }
8019         }
8020         if (DB_TYPE(mp) == M_DATA) {
8021                 struct mac_header_info_s mhi;
8022 
8023                 ip_mdata_to_mhi(ill, mp, &mhi);
8024                 ip_input(ill, NULL, mp, &mhi);
8025         } else {
8026                 ip_rput_notdata(ill, mp);
8027         }
8028         return (0);
8029 }
8030 
8031 /*
8032  * Move the information to a copy.
8033  */
8034 mblk_t *
8035 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8036 {
8037         mblk_t          *mp1;
8038         ill_t           *ill = ira->ira_ill;
8039         ip_stack_t      *ipst = ill->ill_ipst;
8040 
8041         IP_STAT(ipst, ip_db_ref);
8042 
8043         /* Make sure we have ira_l2src before we loose the original mblk */
8044         if (!(ira->ira_flags & IRAF_L2SRC_SET))
8045                 ip_setl2src(mp, ira, ira->ira_rill);
8046 
8047         mp1 = copymsg(mp);
8048         if (mp1 == NULL) {
8049                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8050                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
8051                 freemsg(mp);
8052                 return (NULL);
8053         }
8054         /* preserve the hardware checksum flags and data, if present */
8055         if (DB_CKSUMFLAGS(mp) != 0) {
8056                 DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8057                 DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8058                 DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8059                 DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8060                 DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8061         }
8062         freemsg(mp);
8063         return (mp1);
8064 }
8065 
8066 static void
8067 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8068     t_uscalar_t err)
8069 {
8070         if (dl_err == DL_SYSERR) {
8071                 (void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8072                     "%s: %s failed: DL_SYSERR (errno %u)\n",
8073                     ill->ill_name, dl_primstr(prim), err);
8074                 return;
8075         }
8076 
8077         (void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8078             "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8079             dl_errstr(dl_err));
8080 }
8081 
8082 /*
8083  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8084  * than DL_UNITDATA_IND messages. If we need to process this message
8085  * exclusively, we call qwriter_ip, in which case we also need to call
8086  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8087  */
8088 void
8089 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8090 {
8091         dl_ok_ack_t     *dloa = (dl_ok_ack_t *)mp->b_rptr;
8092         dl_error_ack_t  *dlea = (dl_error_ack_t *)dloa;
8093         queue_t         *q = ill->ill_rq;
8094         t_uscalar_t     prim = dloa->dl_primitive;
8095         t_uscalar_t     reqprim = DL_PRIM_INVAL;
8096 
8097         DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8098             char *, dl_primstr(prim), ill_t *, ill);
8099         ip1dbg(("ip_rput_dlpi"));
8100 
8101         /*
8102          * If we received an ACK but didn't send a request for it, then it
8103          * can't be part of any pending operation; discard up-front.
8104          */
8105         switch (prim) {
8106         case DL_ERROR_ACK:
8107                 reqprim = dlea->dl_error_primitive;
8108                 ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8109                     "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8110                     reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8111                     dlea->dl_unix_errno));
8112                 break;
8113         case DL_OK_ACK:
8114                 reqprim = dloa->dl_correct_primitive;
8115                 break;
8116         case DL_INFO_ACK:
8117                 reqprim = DL_INFO_REQ;
8118                 break;
8119         case DL_BIND_ACK:
8120                 reqprim = DL_BIND_REQ;
8121                 break;
8122         case DL_PHYS_ADDR_ACK:
8123                 reqprim = DL_PHYS_ADDR_REQ;
8124                 break;
8125         case DL_NOTIFY_ACK:
8126                 reqprim = DL_NOTIFY_REQ;
8127                 break;
8128         case DL_CAPABILITY_ACK:
8129                 reqprim = DL_CAPABILITY_REQ;
8130                 break;
8131         }
8132 
8133         if (prim != DL_NOTIFY_IND) {
8134                 if (reqprim == DL_PRIM_INVAL ||
8135                     !ill_dlpi_pending(ill, reqprim)) {
8136                         /* Not a DLPI message we support or expected */
8137                         freemsg(mp);
8138                         return;
8139                 }
8140                 ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8141                     dl_primstr(reqprim)));
8142         }
8143 
8144         switch (reqprim) {
8145         case DL_UNBIND_REQ:
8146                 /*
8147                  * NOTE: we mark the unbind as complete even if we got a
8148                  * DL_ERROR_ACK, since there's not much else we can do.
8149                  */
8150                 mutex_enter(&ill->ill_lock);
8151                 ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8152                 cv_signal(&ill->ill_cv);
8153                 mutex_exit(&ill->ill_lock);
8154                 break;
8155 
8156         case DL_ENABMULTI_REQ:
8157                 if (prim == DL_OK_ACK) {
8158                         if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8159                                 ill->ill_dlpi_multicast_state = IDS_OK;
8160                 }
8161                 break;
8162         }
8163 
8164         /*
8165          * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8166          * need to become writer to continue to process it.  Because an
8167          * exclusive operation doesn't complete until replies to all queued
8168          * DLPI messages have been received, we know we're in the middle of an
8169          * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8170          *
8171          * As required by qwriter_ip(), we refhold the ill; it will refrele.
8172          * Since this is on the ill stream we unconditionally bump up the
8173          * refcount without doing ILL_CAN_LOOKUP().
8174          */
8175         ill_refhold(ill);
8176         if (prim == DL_NOTIFY_IND)
8177                 qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8178         else
8179                 qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8180 }
8181 
8182 /*
8183  * Handling of DLPI messages that require exclusive access to the ipsq.
8184  *
8185  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8186  * happen here. (along with mi_copy_done)
8187  */
8188 /* ARGSUSED */
8189 static void
8190 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8191 {
8192         dl_ok_ack_t     *dloa = (dl_ok_ack_t *)mp->b_rptr;
8193         dl_error_ack_t  *dlea = (dl_error_ack_t *)dloa;
8194         int             err = 0;
8195         ill_t           *ill = (ill_t *)q->q_ptr;
8196         ipif_t          *ipif = NULL;
8197         mblk_t          *mp1 = NULL;
8198         conn_t          *connp = NULL;
8199         t_uscalar_t     paddrreq;
8200         mblk_t          *mp_hw;
8201         boolean_t       ioctl_aborted = B_FALSE;
8202         boolean_t       log = B_TRUE;
8203 
8204         DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8205             char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8206 
8207         ip1dbg(("ip_rput_dlpi_writer .."));
8208         ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8209         ASSERT(IAM_WRITER_ILL(ill));
8210 
8211         ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8212         /*
8213          * The current ioctl could have been aborted by the user and a new
8214          * ioctl to bring up another ill could have started. We could still
8215          * get a response from the driver later.
8216          */
8217         if (ipif != NULL && ipif->ipif_ill != ill)
8218                 ioctl_aborted = B_TRUE;
8219 
8220         switch (dloa->dl_primitive) {
8221         case DL_ERROR_ACK:
8222                 ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8223                     dl_primstr(dlea->dl_error_primitive)));
8224 
8225                 DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8226                     char *, dl_primstr(dlea->dl_error_primitive),
8227                     ill_t *, ill);
8228 
8229                 switch (dlea->dl_error_primitive) {
8230                 case DL_DISABMULTI_REQ:
8231                         ill_dlpi_done(ill, dlea->dl_error_primitive);
8232                         break;
8233                 case DL_PROMISCON_REQ:
8234                 case DL_PROMISCOFF_REQ:
8235                 case DL_UNBIND_REQ:
8236                 case DL_ATTACH_REQ:
8237                 case DL_INFO_REQ:
8238                         ill_dlpi_done(ill, dlea->dl_error_primitive);
8239                         break;
8240                 case DL_NOTIFY_REQ:
8241                         ill_dlpi_done(ill, DL_NOTIFY_REQ);
8242                         log = B_FALSE;
8243                         break;
8244                 case DL_PHYS_ADDR_REQ:
8245                         /*
8246                          * For IPv6 only, there are two additional
8247                          * phys_addr_req's sent to the driver to get the
8248                          * IPv6 token and lla. This allows IP to acquire
8249                          * the hardware address format for a given interface
8250                          * without having built in knowledge of the hardware
8251                          * address. ill_phys_addr_pend keeps track of the last
8252                          * DL_PAR sent so we know which response we are
8253                          * dealing with. ill_dlpi_done will update
8254                          * ill_phys_addr_pend when it sends the next req.
8255                          * We don't complete the IOCTL until all three DL_PARs
8256                          * have been attempted, so set *_len to 0 and break.
8257                          */
8258                         paddrreq = ill->ill_phys_addr_pend;
8259                         ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8260                         if (paddrreq == DL_IPV6_TOKEN) {
8261                                 ill->ill_token_length = 0;
8262                                 log = B_FALSE;
8263                                 break;
8264                         } else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8265                                 ill->ill_nd_lla_len = 0;
8266                                 log = B_FALSE;
8267                                 break;
8268                         }
8269                         /*
8270                          * Something went wrong with the DL_PHYS_ADDR_REQ.
8271                          * We presumably have an IOCTL hanging out waiting
8272                          * for completion. Find it and complete the IOCTL
8273                          * with the error noted.
8274                          * However, ill_dl_phys was called on an ill queue
8275                          * (from SIOCSLIFNAME), thus conn_pending_ill is not
8276                          * set. But the ioctl is known to be pending on ill_wq.
8277                          */
8278                         if (!ill->ill_ifname_pending)
8279                                 break;
8280                         ill->ill_ifname_pending = 0;
8281                         if (!ioctl_aborted)
8282                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8283                         if (mp1 != NULL) {
8284                                 /*
8285                                  * This operation (SIOCSLIFNAME) must have
8286                                  * happened on the ill. Assert there is no conn
8287                                  */
8288                                 ASSERT(connp == NULL);
8289                                 q = ill->ill_wq;
8290                         }
8291                         break;
8292                 case DL_BIND_REQ:
8293                         ill_dlpi_done(ill, DL_BIND_REQ);
8294                         if (ill->ill_ifname_pending)
8295                                 break;
8296                         mutex_enter(&ill->ill_lock);
8297                         ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8298                         mutex_exit(&ill->ill_lock);
8299                         /*
8300                          * Something went wrong with the bind. If this was the
8301                          * result of a DL_NOTE_REPLUMB, then we presumably
8302                          * have an IOCTL hanging out waiting for completion.
8303                          * Find it, take down the interface that was coming
8304                          * up, and complete the IOCTL with the error noted.
8305                          */
8306                         if (!ioctl_aborted)
8307                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8308                         if (mp1 != NULL) {
8309                                 /*
8310                                  * This might be a result of a DL_NOTE_REPLUMB
8311                                  * notification. In that case, connp is NULL.
8312                                  */
8313                                 if (connp != NULL)
8314                                         q = CONNP_TO_WQ(connp);
8315 
8316                                 (void) ipif_down(ipif, NULL, NULL);
8317                                 /* error is set below the switch */
8318                         } else {
8319                                 /*
8320                                  * There's no pending IOCTL, so the bind was
8321                                  * most likely started by ill_dl_up(). We save
8322                                  * the error and let it take care of responding
8323                                  * to the IOCTL.
8324                                  */
8325                                 ill->ill_dl_bind_err = dlea->dl_unix_errno ?
8326                                     dlea->dl_unix_errno : ENXIO;
8327                         }
8328                         break;
8329                 case DL_ENABMULTI_REQ:
8330                         ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8331 
8332                         if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8333                                 ill->ill_dlpi_multicast_state = IDS_FAILED;
8334                         if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8335 
8336                                 printf("ip: joining multicasts failed (%d)"
8337                                     " on %s - will use link layer "
8338                                     "broadcasts for multicast\n",
8339                                     dlea->dl_errno, ill->ill_name);
8340 
8341                                 /*
8342                                  * Set up for multi_bcast; We are the
8343                                  * writer, so ok to access ill->ill_ipif
8344                                  * without any lock.
8345                                  */
8346                                 mutex_enter(&ill->ill_phyint->phyint_lock);
8347                                 ill->ill_phyint->phyint_flags |=
8348                                     PHYI_MULTI_BCAST;
8349                                 mutex_exit(&ill->ill_phyint->phyint_lock);
8350 
8351                         }
8352                         freemsg(mp);    /* Don't want to pass this up */
8353                         return;
8354                 case DL_CAPABILITY_REQ:
8355                         ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8356                             "DL_CAPABILITY REQ\n"));
8357                         if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8358                                 ill->ill_dlpi_capab_state = IDCS_FAILED;
8359                         ill_capability_done(ill);
8360                         freemsg(mp);
8361                         return;
8362                 }
8363                 /*
8364                  * Note the error for IOCTL completion (mp1 is set when
8365                  * ready to complete ioctl). If ill_ifname_pending_err is
8366                  * set, an error occured during plumbing (ill_ifname_pending),
8367                  * so we want to report that error.
8368                  *
8369                  * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8370                  * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8371                  * expected to get errack'd if the driver doesn't support
8372                  * these flags (e.g. ethernet). log will be set to B_FALSE
8373                  * if these error conditions are encountered.
8374                  */
8375                 if (mp1 != NULL) {
8376                         if (ill->ill_ifname_pending_err != 0)  {
8377                                 err = ill->ill_ifname_pending_err;
8378                                 ill->ill_ifname_pending_err = 0;
8379                         } else {
8380                                 err = dlea->dl_unix_errno ?
8381                                     dlea->dl_unix_errno : ENXIO;
8382                         }
8383                 /*
8384                  * If we're plumbing an interface and an error hasn't already
8385                  * been saved, set ill_ifname_pending_err to the error passed
8386                  * up. Ignore the error if log is B_FALSE (see comment above).
8387                  */
8388                 } else if (log && ill->ill_ifname_pending &&
8389                     ill->ill_ifname_pending_err == 0) {
8390                         ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8391                             dlea->dl_unix_errno : ENXIO;
8392                 }
8393 
8394                 if (log)
8395                         ip_dlpi_error(ill, dlea->dl_error_primitive,
8396                             dlea->dl_errno, dlea->dl_unix_errno);
8397                 break;
8398         case DL_CAPABILITY_ACK:
8399                 ill_capability_ack(ill, mp);
8400                 /*
8401                  * The message has been handed off to ill_capability_ack
8402                  * and must not be freed below
8403                  */
8404                 mp = NULL;
8405                 break;
8406 
8407         case DL_INFO_ACK:
8408                 /* Call a routine to handle this one. */
8409                 ill_dlpi_done(ill, DL_INFO_REQ);
8410                 ip_ll_subnet_defaults(ill, mp);
8411                 ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8412                 return;
8413         case DL_BIND_ACK:
8414                 /*
8415                  * We should have an IOCTL waiting on this unless
8416                  * sent by ill_dl_phys, in which case just return
8417                  */
8418                 ill_dlpi_done(ill, DL_BIND_REQ);
8419 
8420                 if (ill->ill_ifname_pending) {
8421                         DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8422                             ill_t *, ill, mblk_t *, mp);
8423                         break;
8424                 }
8425                 mutex_enter(&ill->ill_lock);
8426                 ill->ill_dl_up = 1;
8427                 ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8428                 mutex_exit(&ill->ill_lock);
8429 
8430                 if (!ioctl_aborted)
8431                         mp1 = ipsq_pending_mp_get(ipsq, &connp);
8432                 if (mp1 == NULL) {
8433                         DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8434                         break;
8435                 }
8436                 /*
8437                  * mp1 was added by ill_dl_up(). if that is a result of
8438                  * a DL_NOTE_REPLUMB notification, connp could be NULL.
8439                  */
8440                 if (connp != NULL)
8441                         q = CONNP_TO_WQ(connp);
8442                 /*
8443                  * We are exclusive. So nothing can change even after
8444                  * we get the pending mp.
8445                  */
8446                 ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8447                 DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8448                 ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8449 
8450                 if (ill->ill_up_ipifs) {
8451                         err = ill_up_ipifs(ill, q, mp1);
8452                         if (err == EINPROGRESS) {
8453                                 freemsg(mp);
8454                                 return;
8455                         }
8456                 }
8457 
8458                 break;
8459 
8460         case DL_NOTIFY_IND: {
8461                 dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8462                 uint_t orig_mtu, orig_mc_mtu;
8463 
8464                 switch (notify->dl_notification) {
8465                 case DL_NOTE_PHYS_ADDR:
8466                         err = ill_set_phys_addr(ill, mp);
8467                         break;
8468 
8469                 case DL_NOTE_REPLUMB:
8470                         /*
8471                          * Directly return after calling ill_replumb().
8472                          * Note that we should not free mp as it is reused
8473                          * in the ill_replumb() function.
8474                          */
8475                         err = ill_replumb(ill, mp);
8476                         return;
8477 
8478                 case DL_NOTE_FASTPATH_FLUSH:
8479                         nce_flush(ill, B_FALSE);
8480                         break;
8481 
8482                 case DL_NOTE_SDU_SIZE:
8483                 case DL_NOTE_SDU_SIZE2:
8484                         /*
8485                          * The dce and fragmentation code can cope with
8486                          * this changing while packets are being sent.
8487                          * When packets are sent ip_output will discover
8488                          * a change.
8489                          *
8490                          * Change the MTU size of the interface.
8491                          */
8492                         mutex_enter(&ill->ill_lock);
8493                         orig_mtu = ill->ill_mtu;
8494                         orig_mc_mtu = ill->ill_mc_mtu;
8495                         switch (notify->dl_notification) {
8496                         case DL_NOTE_SDU_SIZE:
8497                                 ill->ill_current_frag =
8498                                     (uint_t)notify->dl_data;
8499                                 ill->ill_mc_mtu = (uint_t)notify->dl_data;
8500                                 break;
8501                         case DL_NOTE_SDU_SIZE2:
8502                                 ill->ill_current_frag =
8503                                     (uint_t)notify->dl_data1;
8504                                 ill->ill_mc_mtu = (uint_t)notify->dl_data2;
8505                                 break;
8506                         }
8507                         if (ill->ill_current_frag > ill->ill_max_frag)
8508                                 ill->ill_max_frag = ill->ill_current_frag;
8509 
8510                         if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8511                                 ill->ill_mtu = ill->ill_current_frag;
8512 
8513                                 /*
8514                                  * If ill_user_mtu was set (via
8515                                  * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8516                                  */
8517                                 if (ill->ill_user_mtu != 0 &&
8518                                     ill->ill_user_mtu < ill->ill_mtu)
8519                                         ill->ill_mtu = ill->ill_user_mtu;
8520 
8521                                 if (ill->ill_user_mtu != 0 &&
8522                                     ill->ill_user_mtu < ill->ill_mc_mtu)
8523                                         ill->ill_mc_mtu = ill->ill_user_mtu;
8524 
8525                                 if (ill->ill_isv6) {
8526                                         if (ill->ill_mtu < IPV6_MIN_MTU)
8527                                                 ill->ill_mtu = IPV6_MIN_MTU;
8528                                         if (ill->ill_mc_mtu < IPV6_MIN_MTU)
8529                                                 ill->ill_mc_mtu = IPV6_MIN_MTU;
8530                                 } else {
8531                                         if (ill->ill_mtu < IP_MIN_MTU)
8532                                                 ill->ill_mtu = IP_MIN_MTU;
8533                                         if (ill->ill_mc_mtu < IP_MIN_MTU)
8534                                                 ill->ill_mc_mtu = IP_MIN_MTU;
8535                                 }
8536                         } else if (ill->ill_mc_mtu > ill->ill_mtu) {
8537                                 ill->ill_mc_mtu = ill->ill_mtu;
8538                         }
8539 
8540                         mutex_exit(&ill->ill_lock);
8541                         /*
8542                          * Make sure all dce_generation checks find out
8543                          * that ill_mtu/ill_mc_mtu has changed.
8544                          */
8545                         if (orig_mtu != ill->ill_mtu ||
8546                             orig_mc_mtu != ill->ill_mc_mtu) {
8547                                 dce_increment_all_generations(ill->ill_isv6,
8548                                     ill->ill_ipst);
8549                         }
8550 
8551                         /*
8552                          * Refresh IPMP meta-interface MTU if necessary.
8553                          */
8554                         if (IS_UNDER_IPMP(ill))
8555                                 ipmp_illgrp_refresh_mtu(ill->ill_grp);
8556                         break;
8557 
8558                 case DL_NOTE_LINK_UP:
8559                 case DL_NOTE_LINK_DOWN: {
8560                         /*
8561                          * We are writer. ill / phyint / ipsq assocs stable.
8562                          * The RUNNING flag reflects the state of the link.
8563                          */
8564                         phyint_t *phyint = ill->ill_phyint;
8565                         uint64_t new_phyint_flags;
8566                         boolean_t changed = B_FALSE;
8567                         boolean_t went_up;
8568 
8569                         went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8570                         mutex_enter(&phyint->phyint_lock);
8571 
8572                         new_phyint_flags = went_up ?
8573                             phyint->phyint_flags | PHYI_RUNNING :
8574                             phyint->phyint_flags & ~PHYI_RUNNING;
8575 
8576                         if (IS_IPMP(ill)) {
8577                                 new_phyint_flags = went_up ?
8578                                     new_phyint_flags & ~PHYI_FAILED :
8579                                     new_phyint_flags | PHYI_FAILED;
8580                         }
8581 
8582                         if (new_phyint_flags != phyint->phyint_flags) {
8583                                 phyint->phyint_flags = new_phyint_flags;
8584                                 changed = B_TRUE;
8585                         }
8586                         mutex_exit(&phyint->phyint_lock);
8587                         /*
8588                          * ill_restart_dad handles the DAD restart and routing
8589                          * socket notification logic.
8590                          */
8591                         if (changed) {
8592                                 ill_restart_dad(phyint->phyint_illv4, went_up);
8593                                 ill_restart_dad(phyint->phyint_illv6, went_up);
8594                         }
8595                         break;
8596                 }
8597                 case DL_NOTE_PROMISC_ON_PHYS: {
8598                         phyint_t *phyint = ill->ill_phyint;
8599 
8600                         mutex_enter(&phyint->phyint_lock);
8601                         phyint->phyint_flags |= PHYI_PROMISC;
8602                         mutex_exit(&phyint->phyint_lock);
8603                         break;
8604                 }
8605                 case DL_NOTE_PROMISC_OFF_PHYS: {
8606                         phyint_t *phyint = ill->ill_phyint;
8607 
8608                         mutex_enter(&phyint->phyint_lock);
8609                         phyint->phyint_flags &= ~PHYI_PROMISC;
8610                         mutex_exit(&phyint->phyint_lock);
8611                         break;
8612                 }
8613                 case DL_NOTE_CAPAB_RENEG:
8614                         /*
8615                          * Something changed on the driver side.
8616                          * It wants us to renegotiate the capabilities
8617                          * on this ill. One possible cause is the aggregation
8618                          * interface under us where a port got added or
8619                          * went away.
8620                          *
8621                          * If the capability negotiation is already done
8622                          * or is in progress, reset the capabilities and
8623                          * mark the ill's ill_capab_reneg to be B_TRUE,
8624                          * so that when the ack comes back, we can start
8625                          * the renegotiation process.
8626                          *
8627                          * Note that if ill_capab_reneg is already B_TRUE
8628                          * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8629                          * the capability resetting request has been sent
8630                          * and the renegotiation has not been started yet;
8631                          * nothing needs to be done in this case.
8632                          */
8633                         ipsq_current_start(ipsq, ill->ill_ipif, 0);
8634                         ill_capability_reset(ill, B_TRUE);
8635                         ipsq_current_finish(ipsq);
8636                         break;
8637 
8638                 case DL_NOTE_ALLOWED_IPS:
8639                         ill_set_allowed_ips(ill, mp);
8640                         break;
8641                 default:
8642                         ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8643                             "type 0x%x for DL_NOTIFY_IND\n",
8644                             notify->dl_notification));
8645                         break;
8646                 }
8647 
8648                 /*
8649                  * As this is an asynchronous operation, we
8650                  * should not call ill_dlpi_done
8651                  */
8652                 break;
8653         }
8654         case DL_NOTIFY_ACK: {
8655                 dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8656 
8657                 if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8658                         ill->ill_note_link = 1;
8659                 ill_dlpi_done(ill, DL_NOTIFY_REQ);
8660                 break;
8661         }
8662         case DL_PHYS_ADDR_ACK: {
8663                 /*
8664                  * As part of plumbing the interface via SIOCSLIFNAME,
8665                  * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8666                  * whose answers we receive here.  As each answer is received,
8667                  * we call ill_dlpi_done() to dispatch the next request as
8668                  * we're processing the current one.  Once all answers have
8669                  * been received, we use ipsq_pending_mp_get() to dequeue the
8670                  * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8671                  * is invoked from an ill queue, conn_oper_pending_ill is not
8672                  * available, but we know the ioctl is pending on ill_wq.)
8673                  */
8674                 uint_t  paddrlen, paddroff;
8675                 uint8_t *addr;
8676 
8677                 paddrreq = ill->ill_phys_addr_pend;
8678                 paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8679                 paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8680                 addr = mp->b_rptr + paddroff;
8681 
8682                 ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8683                 if (paddrreq == DL_IPV6_TOKEN) {
8684                         /*
8685                          * bcopy to low-order bits of ill_token
8686                          *
8687                          * XXX Temporary hack - currently, all known tokens
8688                          * are 64 bits, so I'll cheat for the moment.
8689                          */
8690                         bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8691                         ill->ill_token_length = paddrlen;
8692                         break;
8693                 } else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8694                         ASSERT(ill->ill_nd_lla_mp == NULL);
8695                         ill_set_ndmp(ill, mp, paddroff, paddrlen);
8696                         mp = NULL;
8697                         break;
8698                 } else if (paddrreq == DL_CURR_DEST_ADDR) {
8699                         ASSERT(ill->ill_dest_addr_mp == NULL);
8700                         ill->ill_dest_addr_mp = mp;
8701                         ill->ill_dest_addr = addr;
8702                         mp = NULL;
8703                         if (ill->ill_isv6) {
8704                                 ill_setdesttoken(ill);
8705                                 ipif_setdestlinklocal(ill->ill_ipif);
8706                         }
8707                         break;
8708                 }
8709 
8710                 ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8711                 ASSERT(ill->ill_phys_addr_mp == NULL);
8712                 if (!ill->ill_ifname_pending)
8713                         break;
8714                 ill->ill_ifname_pending = 0;
8715                 if (!ioctl_aborted)
8716                         mp1 = ipsq_pending_mp_get(ipsq, &connp);
8717                 if (mp1 != NULL) {
8718                         ASSERT(connp == NULL);
8719                         q = ill->ill_wq;
8720                 }
8721                 /*
8722                  * If any error acks received during the plumbing sequence,
8723                  * ill_ifname_pending_err will be set. Break out and send up
8724                  * the error to the pending ioctl.
8725                  */
8726                 if (ill->ill_ifname_pending_err != 0) {
8727                         err = ill->ill_ifname_pending_err;
8728                         ill->ill_ifname_pending_err = 0;
8729                         break;
8730                 }
8731 
8732                 ill->ill_phys_addr_mp = mp;
8733                 ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8734                 mp = NULL;
8735 
8736                 /*
8737                  * If paddrlen or ill_phys_addr_length is zero, the DLPI
8738                  * provider doesn't support physical addresses.  We check both
8739                  * paddrlen and ill_phys_addr_length because sppp (PPP) does
8740                  * not have physical addresses, but historically adversises a
8741                  * physical address length of 0 in its DL_INFO_ACK, but 6 in
8742                  * its DL_PHYS_ADDR_ACK.
8743                  */
8744                 if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8745                         ill->ill_phys_addr = NULL;
8746                 } else if (paddrlen != ill->ill_phys_addr_length) {
8747                         ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8748                             paddrlen, ill->ill_phys_addr_length));
8749                         err = EINVAL;
8750                         break;
8751                 }
8752 
8753                 if (ill->ill_nd_lla_mp == NULL) {
8754                         if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8755                                 err = ENOMEM;
8756                                 break;
8757                         }
8758                         ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8759                 }
8760 
8761                 if (ill->ill_isv6) {
8762                         ill_setdefaulttoken(ill);
8763                         ipif_setlinklocal(ill->ill_ipif);
8764                 }
8765                 break;
8766         }
8767         case DL_OK_ACK:
8768                 ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8769                     dl_primstr((int)dloa->dl_correct_primitive),
8770                     dloa->dl_correct_primitive));
8771                 DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8772                     char *, dl_primstr(dloa->dl_correct_primitive),
8773                     ill_t *, ill);
8774 
8775                 switch (dloa->dl_correct_primitive) {
8776                 case DL_ENABMULTI_REQ:
8777                 case DL_DISABMULTI_REQ:
8778                         ill_dlpi_done(ill, dloa->dl_correct_primitive);
8779                         break;
8780                 case DL_PROMISCON_REQ:
8781                 case DL_PROMISCOFF_REQ:
8782                 case DL_UNBIND_REQ:
8783                 case DL_ATTACH_REQ:
8784                         ill_dlpi_done(ill, dloa->dl_correct_primitive);
8785                         break;
8786                 }
8787                 break;
8788         default:
8789                 break;
8790         }
8791 
8792         freemsg(mp);
8793         if (mp1 == NULL)
8794                 return;
8795 
8796         /*
8797          * The operation must complete without EINPROGRESS since
8798          * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8799          * the operation will be stuck forever inside the IPSQ.
8800          */
8801         ASSERT(err != EINPROGRESS);
8802 
8803         DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8804             int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8805             ipif_t *, NULL);
8806 
8807         switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8808         case 0:
8809                 ipsq_current_finish(ipsq);
8810                 break;
8811 
8812         case SIOCSLIFNAME:
8813         case IF_UNITSEL: {
8814                 ill_t *ill_other = ILL_OTHER(ill);
8815 
8816                 /*
8817                  * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8818                  * ill has a peer which is in an IPMP group, then place ill
8819                  * into the same group.  One catch: although ifconfig plumbs
8820                  * the appropriate IPMP meta-interface prior to plumbing this
8821                  * ill, it is possible for multiple ifconfig applications to
8822                  * race (or for another application to adjust plumbing), in
8823                  * which case the IPMP meta-interface we need will be missing.
8824                  * If so, kick the phyint out of the group.
8825                  */
8826                 if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8827                         ipmp_grp_t      *grp = ill->ill_phyint->phyint_grp;
8828                         ipmp_illgrp_t   *illg;
8829 
8830                         illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8831                         if (illg == NULL)
8832                                 ipmp_phyint_leave_grp(ill->ill_phyint);
8833                         else
8834                                 ipmp_ill_join_illgrp(ill, illg);
8835                 }
8836 
8837                 if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8838                         ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8839                 else
8840                         ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8841                 break;
8842         }
8843         case SIOCLIFADDIF:
8844                 ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8845                 break;
8846 
8847         default:
8848                 ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8849                 break;
8850         }
8851 }
8852 
8853 /*
8854  * ip_rput_other is called by ip_rput to handle messages modifying the global
8855  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8856  */
8857 /* ARGSUSED */
8858 void
8859 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8860 {
8861         ill_t           *ill = q->q_ptr;
8862         struct iocblk   *iocp;
8863 
8864         ip1dbg(("ip_rput_other "));
8865         if (ipsq != NULL) {
8866                 ASSERT(IAM_WRITER_IPSQ(ipsq));
8867                 ASSERT(ipsq->ipsq_xop ==
8868                     ill->ill_phyint->phyint_ipsq->ipsq_xop);
8869         }
8870 
8871         switch (mp->b_datap->db_type) {
8872         case M_ERROR:
8873         case M_HANGUP:
8874                 /*
8875                  * The device has a problem.  We force the ILL down.  It can
8876                  * be brought up again manually using SIOCSIFFLAGS (via
8877                  * ifconfig or equivalent).
8878                  */
8879                 ASSERT(ipsq != NULL);
8880                 if (mp->b_rptr < mp->b_wptr)
8881                         ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8882                 if (ill->ill_error == 0)
8883                         ill->ill_error = ENXIO;
8884                 if (!ill_down_start(q, mp))
8885                         return;
8886                 ipif_all_down_tail(ipsq, q, mp, NULL);
8887                 break;
8888         case M_IOCNAK: {
8889                 iocp = (struct iocblk *)mp->b_rptr;
8890 
8891                 ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8892                 /*
8893                  * If this was the first attempt, turn off the fastpath
8894                  * probing.
8895                  */
8896                 mutex_enter(&ill->ill_lock);
8897                 if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8898                         ill->ill_dlpi_fastpath_state = IDS_FAILED;
8899                         mutex_exit(&ill->ill_lock);
8900                         /*
8901                          * don't flush the nce_t entries: we use them
8902                          * as an index to the ncec itself.
8903                          */
8904                         ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8905                             ill->ill_name));
8906                 } else {
8907                         mutex_exit(&ill->ill_lock);
8908                 }
8909                 freemsg(mp);
8910                 break;
8911         }
8912         default:
8913                 ASSERT(0);
8914                 break;
8915         }
8916 }
8917 
8918 /*
8919  * Update any source route, record route or timestamp options
8920  * When it fails it has consumed the message and BUMPed the MIB.
8921  */
8922 boolean_t
8923 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8924     ip_recv_attr_t *ira)
8925 {
8926         ipoptp_t        opts;
8927         uchar_t         *opt;
8928         uint8_t         optval;
8929         uint8_t         optlen;
8930         ipaddr_t        dst;
8931         ipaddr_t        ifaddr;
8932         uint32_t        ts;
8933         timestruc_t     now;
8934         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
8935 
8936         ip2dbg(("ip_forward_options\n"));
8937         dst = ipha->ipha_dst;
8938         for (optval = ipoptp_first(&opts, ipha);
8939             optval != IPOPT_EOL;
8940             optval = ipoptp_next(&opts)) {
8941                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8942                 opt = opts.ipoptp_cur;
8943                 optlen = opts.ipoptp_len;
8944                 ip2dbg(("ip_forward_options: opt %d, len %d\n",
8945                     optval, opts.ipoptp_len));
8946                 switch (optval) {
8947                         uint32_t off;
8948                 case IPOPT_SSRR:
8949                 case IPOPT_LSRR:
8950                         /* Check if adminstratively disabled */
8951                         if (!ipst->ips_ip_forward_src_routed) {
8952                                 BUMP_MIB(dst_ill->ill_ip_mib,
8953                                     ipIfStatsForwProhibits);
8954                                 ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8955                                     mp, dst_ill);
8956                                 icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8957                                     ira);
8958                                 return (B_FALSE);
8959                         }
8960                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
8961                                 /*
8962                                  * Must be partial since ip_input_options
8963                                  * checked for strict.
8964                                  */
8965                                 break;
8966                         }
8967                         off = opt[IPOPT_OFFSET];
8968                         off--;
8969                 redo_srr:
8970                         if (optlen < IP_ADDR_LEN ||
8971                             off > optlen - IP_ADDR_LEN) {
8972                                 /* End of source route */
8973                                 ip1dbg((
8974                                     "ip_forward_options: end of SR\n"));
8975                                 break;
8976                         }
8977                         /* Pick a reasonable address on the outbound if */
8978                         ASSERT(dst_ill != NULL);
8979                         if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
8980                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
8981                             NULL) != 0) {
8982                                 /* No source! Shouldn't happen */
8983                                 ifaddr = INADDR_ANY;
8984                         }
8985                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
8986                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
8987                         ip1dbg(("ip_forward_options: next hop 0x%x\n",
8988                             ntohl(dst)));
8989 
8990                         /*
8991                          * Check if our address is present more than
8992                          * once as consecutive hops in source route.
8993                          */
8994                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
8995                                 off += IP_ADDR_LEN;
8996                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
8997                                 goto redo_srr;
8998                         }
8999                         ipha->ipha_dst = dst;
9000                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9001                         break;
9002                 case IPOPT_RR:
9003                         off = opt[IPOPT_OFFSET];
9004                         off--;
9005                         if (optlen < IP_ADDR_LEN ||
9006                             off > optlen - IP_ADDR_LEN) {
9007                                 /* No more room - ignore */
9008                                 ip1dbg((
9009                                     "ip_forward_options: end of RR\n"));
9010                                 break;
9011                         }
9012                         /* Pick a reasonable address on the outbound if */
9013                         ASSERT(dst_ill != NULL);
9014                         if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9015                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9016                             NULL) != 0) {
9017                                 /* No source! Shouldn't happen */
9018                                 ifaddr = INADDR_ANY;
9019                         }
9020                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9021                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9022                         break;
9023                 case IPOPT_TS:
9024                         /* Insert timestamp if there is room */
9025                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9026                         case IPOPT_TS_TSONLY:
9027                                 off = IPOPT_TS_TIMELEN;
9028                                 break;
9029                         case IPOPT_TS_PRESPEC:
9030                         case IPOPT_TS_PRESPEC_RFC791:
9031                                 /* Verify that the address matched */
9032                                 off = opt[IPOPT_OFFSET] - 1;
9033                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9034                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9035                                         /* Not for us */
9036                                         break;
9037                                 }
9038                                 /* FALLTHROUGH */
9039                         case IPOPT_TS_TSANDADDR:
9040                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9041                                 break;
9042                         default:
9043                                 /*
9044                                  * ip_*put_options should have already
9045                                  * dropped this packet.
9046                                  */
9047                                 cmn_err(CE_PANIC, "ip_forward_options: "
9048                                     "unknown IT - bug in ip_input_options?\n");
9049                         }
9050                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9051                                 /* Increase overflow counter */
9052                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9053                                 opt[IPOPT_POS_OV_FLG] =
9054                                     (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9055                                     (off << 4));
9056                                 break;
9057                         }
9058                         off = opt[IPOPT_OFFSET] - 1;
9059                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9060                         case IPOPT_TS_PRESPEC:
9061                         case IPOPT_TS_PRESPEC_RFC791:
9062                         case IPOPT_TS_TSANDADDR:
9063                                 /* Pick a reasonable addr on the outbound if */
9064                                 ASSERT(dst_ill != NULL);
9065                                 if (ip_select_source_v4(dst_ill, INADDR_ANY,
9066                                     dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9067                                     NULL, NULL) != 0) {
9068                                         /* No source! Shouldn't happen */
9069                                         ifaddr = INADDR_ANY;
9070                                 }
9071                                 bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9072                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9073                                 /* FALLTHROUGH */
9074                         case IPOPT_TS_TSONLY:
9075                                 off = opt[IPOPT_OFFSET] - 1;
9076                                 /* Compute # of milliseconds since midnight */
9077                                 gethrestime(&now);
9078                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9079                                     NSEC2MSEC(now.tv_nsec);
9080                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9081                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9082                                 break;
9083                         }
9084                         break;
9085                 }
9086         }
9087         return (B_TRUE);
9088 }
9089 
9090 /*
9091  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9092  * returns 'true' if there are still fragments left on the queue, in
9093  * which case we restart the timer.
9094  */
9095 void
9096 ill_frag_timer(void *arg)
9097 {
9098         ill_t   *ill = (ill_t *)arg;
9099         boolean_t frag_pending;
9100         ip_stack_t *ipst = ill->ill_ipst;
9101         time_t  timeout;
9102 
9103         mutex_enter(&ill->ill_lock);
9104         ASSERT(!ill->ill_fragtimer_executing);
9105         if (ill->ill_state_flags & ILL_CONDEMNED) {
9106                 ill->ill_frag_timer_id = 0;
9107                 mutex_exit(&ill->ill_lock);
9108                 return;
9109         }
9110         ill->ill_fragtimer_executing = 1;
9111         mutex_exit(&ill->ill_lock);
9112 
9113         timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9114             ipst->ips_ip_reassembly_timeout);
9115 
9116         frag_pending = ill_frag_timeout(ill, timeout);
9117 
9118         /*
9119          * Restart the timer, if we have fragments pending or if someone
9120          * wanted us to be scheduled again.
9121          */
9122         mutex_enter(&ill->ill_lock);
9123         ill->ill_fragtimer_executing = 0;
9124         ill->ill_frag_timer_id = 0;
9125         if (frag_pending || ill->ill_fragtimer_needrestart)
9126                 ill_frag_timer_start(ill);
9127         mutex_exit(&ill->ill_lock);
9128 }
9129 
9130 void
9131 ill_frag_timer_start(ill_t *ill)
9132 {
9133         ip_stack_t *ipst = ill->ill_ipst;
9134         clock_t timeo_ms;
9135 
9136         ASSERT(MUTEX_HELD(&ill->ill_lock));
9137 
9138         /* If the ill is closing or opening don't proceed */
9139         if (ill->ill_state_flags & ILL_CONDEMNED)
9140                 return;
9141 
9142         if (ill->ill_fragtimer_executing) {
9143                 /*
9144                  * ill_frag_timer is currently executing. Just record the
9145                  * the fact that we want the timer to be restarted.
9146                  * ill_frag_timer will post a timeout before it returns,
9147                  * ensuring it will be called again.
9148                  */
9149                 ill->ill_fragtimer_needrestart = 1;
9150                 return;
9151         }
9152 
9153         if (ill->ill_frag_timer_id == 0) {
9154                 timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9155                     ipst->ips_ip_reassembly_timeout) * SECONDS;
9156 
9157                 /*
9158                  * The timer is neither running nor is the timeout handler
9159                  * executing. Post a timeout so that ill_frag_timer will be
9160                  * called
9161                  */
9162                 ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9163                     MSEC_TO_TICK(timeo_ms >> 1));
9164                 ill->ill_fragtimer_needrestart = 0;
9165         }
9166 }
9167 
9168 /*
9169  * Update any source route, record route or timestamp options.
9170  * Check that we are at end of strict source route.
9171  * The options have already been checked for sanity in ip_input_options().
9172  */
9173 boolean_t
9174 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9175 {
9176         ipoptp_t        opts;
9177         uchar_t         *opt;
9178         uint8_t         optval;
9179         uint8_t         optlen;
9180         ipaddr_t        dst;
9181         ipaddr_t        ifaddr;
9182         uint32_t        ts;
9183         timestruc_t     now;
9184         ill_t           *ill = ira->ira_ill;
9185         ip_stack_t      *ipst = ill->ill_ipst;
9186 
9187         ip2dbg(("ip_input_local_options\n"));
9188 
9189         for (optval = ipoptp_first(&opts, ipha);
9190             optval != IPOPT_EOL;
9191             optval = ipoptp_next(&opts)) {
9192                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9193                 opt = opts.ipoptp_cur;
9194                 optlen = opts.ipoptp_len;
9195                 ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9196                     optval, optlen));
9197                 switch (optval) {
9198                         uint32_t off;
9199                 case IPOPT_SSRR:
9200                 case IPOPT_LSRR:
9201                         off = opt[IPOPT_OFFSET];
9202                         off--;
9203                         if (optlen < IP_ADDR_LEN ||
9204                             off > optlen - IP_ADDR_LEN) {
9205                                 /* End of source route */
9206                                 ip1dbg(("ip_input_local_options: end of SR\n"));
9207                                 break;
9208                         }
9209                         /*
9210                          * This will only happen if two consecutive entries
9211                          * in the source route contains our address or if
9212                          * it is a packet with a loose source route which
9213                          * reaches us before consuming the whole source route
9214                          */
9215                         ip1dbg(("ip_input_local_options: not end of SR\n"));
9216                         if (optval == IPOPT_SSRR) {
9217                                 goto bad_src_route;
9218                         }
9219                         /*
9220                          * Hack: instead of dropping the packet truncate the
9221                          * source route to what has been used by filling the
9222                          * rest with IPOPT_NOP.
9223                          */
9224                         opt[IPOPT_OLEN] = (uint8_t)off;
9225                         while (off < optlen) {
9226                                 opt[off++] = IPOPT_NOP;
9227                         }
9228                         break;
9229                 case IPOPT_RR:
9230                         off = opt[IPOPT_OFFSET];
9231                         off--;
9232                         if (optlen < IP_ADDR_LEN ||
9233                             off > optlen - IP_ADDR_LEN) {
9234                                 /* No more room - ignore */
9235                                 ip1dbg((
9236                                     "ip_input_local_options: end of RR\n"));
9237                                 break;
9238                         }
9239                         /* Pick a reasonable address on the outbound if */
9240                         if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9241                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9242                             NULL) != 0) {
9243                                 /* No source! Shouldn't happen */
9244                                 ifaddr = INADDR_ANY;
9245                         }
9246                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9247                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9248                         break;
9249                 case IPOPT_TS:
9250                         /* Insert timestamp if there is romm */
9251                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9252                         case IPOPT_TS_TSONLY:
9253                                 off = IPOPT_TS_TIMELEN;
9254                                 break;
9255                         case IPOPT_TS_PRESPEC:
9256                         case IPOPT_TS_PRESPEC_RFC791:
9257                                 /* Verify that the address matched */
9258                                 off = opt[IPOPT_OFFSET] - 1;
9259                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9260                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9261                                         /* Not for us */
9262                                         break;
9263                                 }
9264                                 /* FALLTHROUGH */
9265                         case IPOPT_TS_TSANDADDR:
9266                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9267                                 break;
9268                         default:
9269                                 /*
9270                                  * ip_*put_options should have already
9271                                  * dropped this packet.
9272                                  */
9273                                 cmn_err(CE_PANIC, "ip_input_local_options: "
9274                                     "unknown IT - bug in ip_input_options?\n");
9275                         }
9276                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9277                                 /* Increase overflow counter */
9278                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9279                                 opt[IPOPT_POS_OV_FLG] =
9280                                     (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9281                                     (off << 4));
9282                                 break;
9283                         }
9284                         off = opt[IPOPT_OFFSET] - 1;
9285                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9286                         case IPOPT_TS_PRESPEC:
9287                         case IPOPT_TS_PRESPEC_RFC791:
9288                         case IPOPT_TS_TSANDADDR:
9289                                 /* Pick a reasonable addr on the outbound if */
9290                                 if (ip_select_source_v4(ill, INADDR_ANY,
9291                                     ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9292                                     &ifaddr, NULL, NULL) != 0) {
9293                                         /* No source! Shouldn't happen */
9294                                         ifaddr = INADDR_ANY;
9295                                 }
9296                                 bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9297                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9298                                 /* FALLTHROUGH */
9299                         case IPOPT_TS_TSONLY:
9300                                 off = opt[IPOPT_OFFSET] - 1;
9301                                 /* Compute # of milliseconds since midnight */
9302                                 gethrestime(&now);
9303                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9304                                     NSEC2MSEC(now.tv_nsec);
9305                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9306                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9307                                 break;
9308                         }
9309                         break;
9310                 }
9311         }
9312         return (B_TRUE);
9313 
9314 bad_src_route:
9315         /* make sure we clear any indication of a hardware checksum */
9316         DB_CKSUMFLAGS(mp) = 0;
9317         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9318         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9319         return (B_FALSE);
9320 
9321 }
9322 
9323 /*
9324  * Process IP options in an inbound packet.  Always returns the nexthop.
9325  * Normally this is the passed in nexthop, but if there is an option
9326  * that effects the nexthop (such as a source route) that will be returned.
9327  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9328  * and mp freed.
9329  */
9330 ipaddr_t
9331 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9332     ip_recv_attr_t *ira, int *errorp)
9333 {
9334         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
9335         ipoptp_t        opts;
9336         uchar_t         *opt;
9337         uint8_t         optval;
9338         uint8_t         optlen;
9339         intptr_t        code = 0;
9340         ire_t           *ire;
9341 
9342         ip2dbg(("ip_input_options\n"));
9343         *errorp = 0;
9344         for (optval = ipoptp_first(&opts, ipha);
9345             optval != IPOPT_EOL;
9346             optval = ipoptp_next(&opts)) {
9347                 opt = opts.ipoptp_cur;
9348                 optlen = opts.ipoptp_len;
9349                 ip2dbg(("ip_input_options: opt %d, len %d\n",
9350                     optval, optlen));
9351                 /*
9352                  * Note: we need to verify the checksum before we
9353                  * modify anything thus this routine only extracts the next
9354                  * hop dst from any source route.
9355                  */
9356                 switch (optval) {
9357                         uint32_t off;
9358                 case IPOPT_SSRR:
9359                 case IPOPT_LSRR:
9360                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9361                                 if (optval == IPOPT_SSRR) {
9362                                         ip1dbg(("ip_input_options: not next"
9363                                             " strict source route 0x%x\n",
9364                                             ntohl(dst)));
9365                                         code = (char *)&ipha->ipha_dst -
9366                                             (char *)ipha;
9367                                         goto param_prob; /* RouterReq's */
9368                                 }
9369                                 ip2dbg(("ip_input_options: "
9370                                     "not next source route 0x%x\n",
9371                                     ntohl(dst)));
9372                                 break;
9373                         }
9374 
9375                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9376                                 ip1dbg((
9377                                     "ip_input_options: bad option offset\n"));
9378                                 code = (char *)&opt[IPOPT_OLEN] -
9379                                     (char *)ipha;
9380                                 goto param_prob;
9381                         }
9382                         off = opt[IPOPT_OFFSET];
9383                         off--;
9384                 redo_srr:
9385                         if (optlen < IP_ADDR_LEN ||
9386                             off > optlen - IP_ADDR_LEN) {
9387                                 /* End of source route */
9388                                 ip1dbg(("ip_input_options: end of SR\n"));
9389                                 break;
9390                         }
9391                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9392                         ip1dbg(("ip_input_options: next hop 0x%x\n",
9393                             ntohl(dst)));
9394 
9395                         /*
9396                          * Check if our address is present more than
9397                          * once as consecutive hops in source route.
9398                          * XXX verify per-interface ip_forwarding
9399                          * for source route?
9400                          */
9401                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9402                                 off += IP_ADDR_LEN;
9403                                 goto redo_srr;
9404                         }
9405 
9406                         if (dst == htonl(INADDR_LOOPBACK)) {
9407                                 ip1dbg(("ip_input_options: loopback addr in "
9408                                     "source route!\n"));
9409                                 goto bad_src_route;
9410                         }
9411                         /*
9412                          * For strict: verify that dst is directly
9413                          * reachable.
9414                          */
9415                         if (optval == IPOPT_SSRR) {
9416                                 ire = ire_ftable_lookup_v4(dst, 0, 0,
9417                                     IRE_INTERFACE, NULL, ALL_ZONES,
9418                                     ira->ira_tsl,
9419                                     MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9420                                     NULL);
9421                                 if (ire == NULL) {
9422                                         ip1dbg(("ip_input_options: SSRR not "
9423                                             "directly reachable: 0x%x\n",
9424                                             ntohl(dst)));
9425                                         goto bad_src_route;
9426                                 }
9427                                 ire_refrele(ire);
9428                         }
9429                         /*
9430                          * Defer update of the offset and the record route
9431                          * until the packet is forwarded.
9432                          */
9433                         break;
9434                 case IPOPT_RR:
9435                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9436                                 ip1dbg((
9437                                     "ip_input_options: bad option offset\n"));
9438                                 code = (char *)&opt[IPOPT_OLEN] -
9439                                     (char *)ipha;
9440                                 goto param_prob;
9441                         }
9442                         break;
9443                 case IPOPT_TS:
9444                         /*
9445                          * Verify that length >= 5 and that there is either
9446                          * room for another timestamp or that the overflow
9447                          * counter is not maxed out.
9448                          */
9449                         code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9450                         if (optlen < IPOPT_MINLEN_IT) {
9451                                 goto param_prob;
9452                         }
9453                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9454                                 ip1dbg((
9455                                     "ip_input_options: bad option offset\n"));
9456                                 code = (char *)&opt[IPOPT_OFFSET] -
9457                                     (char *)ipha;
9458                                 goto param_prob;
9459                         }
9460                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9461                         case IPOPT_TS_TSONLY:
9462                                 off = IPOPT_TS_TIMELEN;
9463                                 break;
9464                         case IPOPT_TS_TSANDADDR:
9465                         case IPOPT_TS_PRESPEC:
9466                         case IPOPT_TS_PRESPEC_RFC791:
9467                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9468                                 break;
9469                         default:
9470                                 code = (char *)&opt[IPOPT_POS_OV_FLG] -
9471                                     (char *)ipha;
9472                                 goto param_prob;
9473                         }
9474                         if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9475                             (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9476                                 /*
9477                                  * No room and the overflow counter is 15
9478                                  * already.
9479                                  */
9480                                 goto param_prob;
9481                         }
9482                         break;
9483                 }
9484         }
9485 
9486         if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9487                 return (dst);
9488         }
9489 
9490         ip1dbg(("ip_input_options: error processing IP options."));
9491         code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9492 
9493 param_prob:
9494         /* make sure we clear any indication of a hardware checksum */
9495         DB_CKSUMFLAGS(mp) = 0;
9496         ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9497         icmp_param_problem(mp, (uint8_t)code, ira);
9498         *errorp = -1;
9499         return (dst);
9500 
9501 bad_src_route:
9502         /* make sure we clear any indication of a hardware checksum */
9503         DB_CKSUMFLAGS(mp) = 0;
9504         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9505         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9506         *errorp = -1;
9507         return (dst);
9508 }
9509 
9510 /*
9511  * IP & ICMP info in >=14 msg's ...
9512  *  - ip fixed part (mib2_ip_t)
9513  *  - icmp fixed part (mib2_icmp_t)
9514  *  - ipAddrEntryTable (ip 20)          all IPv4 ipifs
9515  *  - ipRouteEntryTable (ip 21)         all IPv4 IREs
9516  *  - ipNetToMediaEntryTable (ip 22)    all IPv4 Neighbor Cache entries
9517  *  - ipRouteAttributeTable (ip 102)    labeled routes
9518  *  - ip multicast membership (ip_member_t)
9519  *  - ip multicast source filtering (ip_grpsrc_t)
9520  *  - igmp fixed part (struct igmpstat)
9521  *  - multicast routing stats (struct mrtstat)
9522  *  - multicast routing vifs (array of struct vifctl)
9523  *  - multicast routing routes (array of struct mfcctl)
9524  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9525  *                                      One per ill plus one generic
9526  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9527  *                                      One per ill plus one generic
9528  *  - ipv6RouteEntry                    all IPv6 IREs
9529  *  - ipv6RouteAttributeTable (ip6 102) labeled routes
9530  *  - ipv6NetToMediaEntry               all IPv6 Neighbor Cache entries
9531  *  - ipv6AddrEntry                     all IPv6 ipifs
9532  *  - ipv6 multicast membership (ipv6_member_t)
9533  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9534  *
9535  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9536  * already filled in by the caller.
9537  * If legacy_req is true then MIB structures needs to be truncated to their
9538  * legacy sizes before being returned.
9539  * Return value of 0 indicates that no messages were sent and caller
9540  * should free mpctl.
9541  */
9542 int
9543 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9544 {
9545         ip_stack_t *ipst;
9546         sctp_stack_t *sctps;
9547 
9548         if (q->q_next != NULL) {
9549                 ipst = ILLQ_TO_IPST(q);
9550         } else {
9551                 ipst = CONNQ_TO_IPST(q);
9552         }
9553         ASSERT(ipst != NULL);
9554         sctps = ipst->ips_netstack->netstack_sctp;
9555 
9556         if (mpctl == NULL || mpctl->b_cont == NULL) {
9557                 return (0);
9558         }
9559 
9560         /*
9561          * For the purposes of the (broken) packet shell use
9562          * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9563          * to make TCP and UDP appear first in the list of mib items.
9564          * TBD: We could expand this and use it in netstat so that
9565          * the kernel doesn't have to produce large tables (connections,
9566          * routes, etc) when netstat only wants the statistics or a particular
9567          * table.
9568          */
9569         if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9570                 if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9571                         return (1);
9572                 }
9573         }
9574 
9575         if (level != MIB2_TCP) {
9576                 if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9577                         return (1);
9578                 }
9579                 if (level == MIB2_UDP) {
9580                         goto done;
9581                 }
9582         }
9583 
9584         if (level != MIB2_UDP) {
9585                 if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9586                         return (1);
9587                 }
9588                 if (level == MIB2_TCP) {
9589                         goto done;
9590                 }
9591         }
9592 
9593         if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9594             ipst, legacy_req)) == NULL) {
9595                 return (1);
9596         }
9597 
9598         if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9599             legacy_req)) == NULL) {
9600                 return (1);
9601         }
9602 
9603         if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9604                 return (1);
9605         }
9606 
9607         if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9608                 return (1);
9609         }
9610 
9611         if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9612                 return (1);
9613         }
9614 
9615         if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9616                 return (1);
9617         }
9618 
9619         if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9620             legacy_req)) == NULL) {
9621                 return (1);
9622         }
9623 
9624         if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9625             legacy_req)) == NULL) {
9626                 return (1);
9627         }
9628 
9629         if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9630                 return (1);
9631         }
9632 
9633         if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9634                 return (1);
9635         }
9636 
9637         if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9638                 return (1);
9639         }
9640 
9641         if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9642                 return (1);
9643         }
9644 
9645         if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9646                 return (1);
9647         }
9648 
9649         if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9650                 return (1);
9651         }
9652 
9653         mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9654         if (mpctl == NULL)
9655                 return (1);
9656 
9657         mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9658         if (mpctl == NULL)
9659                 return (1);
9660 
9661         if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9662                 return (1);
9663         }
9664         if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9665                 return (1);
9666         }
9667 done:
9668         freemsg(mpctl);
9669         return (1);
9670 }
9671 
9672 /* Get global (legacy) IPv4 statistics */
9673 static mblk_t *
9674 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9675     ip_stack_t *ipst, boolean_t legacy_req)
9676 {
9677         mib2_ip_t               old_ip_mib;
9678         struct opthdr           *optp;
9679         mblk_t                  *mp2ctl;
9680         mib2_ipAddrEntry_t      mae;
9681 
9682         /*
9683          * make a copy of the original message
9684          */
9685         mp2ctl = copymsg(mpctl);
9686 
9687         /* fixed length IP structure... */
9688         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9689         optp->level = MIB2_IP;
9690         optp->name = 0;
9691         SET_MIB(old_ip_mib.ipForwarding,
9692             (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9693         SET_MIB(old_ip_mib.ipDefaultTTL,
9694             (uint32_t)ipst->ips_ip_def_ttl);
9695         SET_MIB(old_ip_mib.ipReasmTimeout,
9696             ipst->ips_ip_reassembly_timeout);
9697         SET_MIB(old_ip_mib.ipAddrEntrySize,
9698             (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9699             sizeof (mib2_ipAddrEntry_t));
9700         SET_MIB(old_ip_mib.ipRouteEntrySize,
9701             sizeof (mib2_ipRouteEntry_t));
9702         SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9703             sizeof (mib2_ipNetToMediaEntry_t));
9704         SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9705         SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9706         SET_MIB(old_ip_mib.ipRouteAttributeSize,
9707             sizeof (mib2_ipAttributeEntry_t));
9708         SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9709         SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9710 
9711         /*
9712          * Grab the statistics from the new IP MIB
9713          */
9714         SET_MIB(old_ip_mib.ipInReceives,
9715             (uint32_t)ipmib->ipIfStatsHCInReceives);
9716         SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9717         SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9718         SET_MIB(old_ip_mib.ipForwDatagrams,
9719             (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9720         SET_MIB(old_ip_mib.ipInUnknownProtos,
9721             ipmib->ipIfStatsInUnknownProtos);
9722         SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9723         SET_MIB(old_ip_mib.ipInDelivers,
9724             (uint32_t)ipmib->ipIfStatsHCInDelivers);
9725         SET_MIB(old_ip_mib.ipOutRequests,
9726             (uint32_t)ipmib->ipIfStatsHCOutRequests);
9727         SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9728         SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9729         SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9730         SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9731         SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9732         SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9733         SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9734         SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9735 
9736         /* ipRoutingDiscards is not being used */
9737         SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9738         SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9739         SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9740         SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9741         SET_MIB(old_ip_mib.ipReasmDuplicates,
9742             ipmib->ipIfStatsReasmDuplicates);
9743         SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9744         SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9745         SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9746         SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9747         SET_MIB(old_ip_mib.rawipInOverflows,
9748             ipmib->rawipIfStatsInOverflows);
9749 
9750         SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9751         SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9752         SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9753         SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9754         SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9755             ipmib->ipIfStatsOutSwitchIPVersion);
9756 
9757         if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9758             (int)sizeof (old_ip_mib))) {
9759                 ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9760                     (uint_t)sizeof (old_ip_mib)));
9761         }
9762 
9763         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9764         ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9765             (int)optp->level, (int)optp->name, (int)optp->len));
9766         qreply(q, mpctl);
9767         return (mp2ctl);
9768 }
9769 
9770 /* Per interface IPv4 statistics */
9771 static mblk_t *
9772 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9773     boolean_t legacy_req)
9774 {
9775         struct opthdr           *optp;
9776         mblk_t                  *mp2ctl;
9777         ill_t                   *ill;
9778         ill_walk_context_t      ctx;
9779         mblk_t                  *mp_tail = NULL;
9780         mib2_ipIfStatsEntry_t   global_ip_mib;
9781         mib2_ipAddrEntry_t      mae;
9782 
9783         /*
9784          * Make a copy of the original message
9785          */
9786         mp2ctl = copymsg(mpctl);
9787 
9788         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9789         optp->level = MIB2_IP;
9790         optp->name = MIB2_IP_TRAFFIC_STATS;
9791         /* Include "unknown interface" ip_mib */
9792         ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9793         ipst->ips_ip_mib.ipIfStatsIfIndex =
9794             MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9795         SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9796             (ipst->ips_ip_forwarding ? 1 : 2));
9797         SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9798             (uint32_t)ipst->ips_ip_def_ttl);
9799         SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9800             sizeof (mib2_ipIfStatsEntry_t));
9801         SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9802             sizeof (mib2_ipAddrEntry_t));
9803         SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9804             sizeof (mib2_ipRouteEntry_t));
9805         SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9806             sizeof (mib2_ipNetToMediaEntry_t));
9807         SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9808             sizeof (ip_member_t));
9809         SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9810             sizeof (ip_grpsrc_t));
9811 
9812         bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9813 
9814         if (legacy_req) {
9815                 SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9816                     LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9817         }
9818 
9819         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9820             (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9821                 ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9822                     "failed to allocate %u bytes\n",
9823                     (uint_t)sizeof (global_ip_mib)));
9824         }
9825 
9826         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9827         ill = ILL_START_WALK_V4(&ctx, ipst);
9828         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9829                 ill->ill_ip_mib->ipIfStatsIfIndex =
9830                     ill->ill_phyint->phyint_ifindex;
9831                 SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9832                     (ipst->ips_ip_forwarding ? 1 : 2));
9833                 SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9834                     (uint32_t)ipst->ips_ip_def_ttl);
9835 
9836                 ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9837                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9838                     (char *)ill->ill_ip_mib,
9839                     (int)sizeof (*ill->ill_ip_mib))) {
9840                         ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9841                             "failed to allocate %u bytes\n",
9842                             (uint_t)sizeof (*ill->ill_ip_mib)));
9843                 }
9844         }
9845         rw_exit(&ipst->ips_ill_g_lock);
9846 
9847         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9848         ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9849             "level %d, name %d, len %d\n",
9850             (int)optp->level, (int)optp->name, (int)optp->len));
9851         qreply(q, mpctl);
9852 
9853         if (mp2ctl == NULL)
9854                 return (NULL);
9855 
9856         return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9857             legacy_req));
9858 }
9859 
9860 /* Global IPv4 ICMP statistics */
9861 static mblk_t *
9862 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9863 {
9864         struct opthdr           *optp;
9865         mblk_t                  *mp2ctl;
9866 
9867         /*
9868          * Make a copy of the original message
9869          */
9870         mp2ctl = copymsg(mpctl);
9871 
9872         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9873         optp->level = MIB2_ICMP;
9874         optp->name = 0;
9875         if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9876             (int)sizeof (ipst->ips_icmp_mib))) {
9877                 ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9878                     (uint_t)sizeof (ipst->ips_icmp_mib)));
9879         }
9880         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9881         ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9882             (int)optp->level, (int)optp->name, (int)optp->len));
9883         qreply(q, mpctl);
9884         return (mp2ctl);
9885 }
9886 
9887 /* Global IPv4 IGMP statistics */
9888 static mblk_t *
9889 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9890 {
9891         struct opthdr           *optp;
9892         mblk_t                  *mp2ctl;
9893 
9894         /*
9895          * make a copy of the original message
9896          */
9897         mp2ctl = copymsg(mpctl);
9898 
9899         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9900         optp->level = EXPER_IGMP;
9901         optp->name = 0;
9902         if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9903             (int)sizeof (ipst->ips_igmpstat))) {
9904                 ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9905                     (uint_t)sizeof (ipst->ips_igmpstat)));
9906         }
9907         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9908         ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9909             (int)optp->level, (int)optp->name, (int)optp->len));
9910         qreply(q, mpctl);
9911         return (mp2ctl);
9912 }
9913 
9914 /* Global IPv4 Multicast Routing statistics */
9915 static mblk_t *
9916 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9917 {
9918         struct opthdr           *optp;
9919         mblk_t                  *mp2ctl;
9920 
9921         /*
9922          * make a copy of the original message
9923          */
9924         mp2ctl = copymsg(mpctl);
9925 
9926         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9927         optp->level = EXPER_DVMRP;
9928         optp->name = 0;
9929         if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9930                 ip0dbg(("ip_mroute_stats: failed\n"));
9931         }
9932         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9933         ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9934             (int)optp->level, (int)optp->name, (int)optp->len));
9935         qreply(q, mpctl);
9936         return (mp2ctl);
9937 }
9938 
9939 /* IPv4 address information */
9940 static mblk_t *
9941 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9942     boolean_t legacy_req)
9943 {
9944         struct opthdr           *optp;
9945         mblk_t                  *mp2ctl;
9946         mblk_t                  *mp_tail = NULL;
9947         ill_t                   *ill;
9948         ipif_t                  *ipif;
9949         uint_t                  bitval;
9950         mib2_ipAddrEntry_t      mae;
9951         size_t                  mae_size;
9952         zoneid_t                zoneid;
9953         ill_walk_context_t      ctx;
9954 
9955         /*
9956          * make a copy of the original message
9957          */
9958         mp2ctl = copymsg(mpctl);
9959 
9960         mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9961             sizeof (mib2_ipAddrEntry_t);
9962 
9963         /* ipAddrEntryTable */
9964 
9965         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9966         optp->level = MIB2_IP;
9967         optp->name = MIB2_IP_ADDR;
9968         zoneid = Q_TO_CONN(q)->conn_zoneid;
9969 
9970         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9971         ill = ILL_START_WALK_V4(&ctx, ipst);
9972         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9973                 for (ipif = ill->ill_ipif; ipif != NULL;
9974                     ipif = ipif->ipif_next) {
9975                         if (ipif->ipif_zoneid != zoneid &&
9976                             ipif->ipif_zoneid != ALL_ZONES)
9977                                 continue;
9978                         /* Sum of count from dead IRE_LO* and our current */
9979                         mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
9980                         if (ipif->ipif_ire_local != NULL) {
9981                                 mae.ipAdEntInfo.ae_ibcnt +=
9982                                     ipif->ipif_ire_local->ire_ib_pkt_count;
9983                         }
9984                         mae.ipAdEntInfo.ae_obcnt = 0;
9985                         mae.ipAdEntInfo.ae_focnt = 0;
9986 
9987                         ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
9988                             OCTET_LENGTH);
9989                         mae.ipAdEntIfIndex.o_length =
9990                             mi_strlen(mae.ipAdEntIfIndex.o_bytes);
9991                         mae.ipAdEntAddr = ipif->ipif_lcl_addr;
9992                         mae.ipAdEntNetMask = ipif->ipif_net_mask;
9993                         mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
9994                         mae.ipAdEntInfo.ae_subnet_len =
9995                             ip_mask_to_plen(ipif->ipif_net_mask);
9996                         mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
9997                         for (bitval = 1;
9998                             bitval &&
9999                             !(bitval & ipif->ipif_brd_addr);
10000                             bitval <<= 1)
10001                                 noop;
10002                         mae.ipAdEntBcastAddr = bitval;
10003                         mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10004                         mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10005                         mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
10006                         mae.ipAdEntInfo.ae_broadcast_addr =
10007                             ipif->ipif_brd_addr;
10008                         mae.ipAdEntInfo.ae_pp_dst_addr =
10009                             ipif->ipif_pp_dst_addr;
10010                         mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10011                             ill->ill_flags | ill->ill_phyint->phyint_flags;
10012                         mae.ipAdEntRetransmitTime =
10013                             ill->ill_reachable_retrans_time;
10014 
10015                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10016                             (char *)&mae, (int)mae_size)) {
10017                                 ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10018                                     "allocate %u bytes\n", (uint_t)mae_size));
10019                         }
10020                 }
10021         }
10022         rw_exit(&ipst->ips_ill_g_lock);
10023 
10024         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10025         ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10026             (int)optp->level, (int)optp->name, (int)optp->len));
10027         qreply(q, mpctl);
10028         return (mp2ctl);
10029 }
10030 
10031 /* IPv6 address information */
10032 static mblk_t *
10033 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10034     boolean_t legacy_req)
10035 {
10036         struct opthdr           *optp;
10037         mblk_t                  *mp2ctl;
10038         mblk_t                  *mp_tail = NULL;
10039         ill_t                   *ill;
10040         ipif_t                  *ipif;
10041         mib2_ipv6AddrEntry_t    mae6;
10042         size_t                  mae6_size;
10043         zoneid_t                zoneid;
10044         ill_walk_context_t      ctx;
10045 
10046         /*
10047          * make a copy of the original message
10048          */
10049         mp2ctl = copymsg(mpctl);
10050 
10051         mae6_size = (legacy_req) ?
10052             LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10053             sizeof (mib2_ipv6AddrEntry_t);
10054 
10055         /* ipv6AddrEntryTable */
10056 
10057         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10058         optp->level = MIB2_IP6;
10059         optp->name = MIB2_IP6_ADDR;
10060         zoneid = Q_TO_CONN(q)->conn_zoneid;
10061 
10062         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10063         ill = ILL_START_WALK_V6(&ctx, ipst);
10064         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10065                 for (ipif = ill->ill_ipif; ipif != NULL;
10066                     ipif = ipif->ipif_next) {
10067                         if (ipif->ipif_zoneid != zoneid &&
10068                             ipif->ipif_zoneid != ALL_ZONES)
10069                                 continue;
10070                         /* Sum of count from dead IRE_LO* and our current */
10071                         mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10072                         if (ipif->ipif_ire_local != NULL) {
10073                                 mae6.ipv6AddrInfo.ae_ibcnt +=
10074                                     ipif->ipif_ire_local->ire_ib_pkt_count;
10075                         }
10076                         mae6.ipv6AddrInfo.ae_obcnt = 0;
10077                         mae6.ipv6AddrInfo.ae_focnt = 0;
10078 
10079                         ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10080                             OCTET_LENGTH);
10081                         mae6.ipv6AddrIfIndex.o_length =
10082                             mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10083                         mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10084                         mae6.ipv6AddrPfxLength =
10085                             ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10086                         mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10087                         mae6.ipv6AddrInfo.ae_subnet_len =
10088                             mae6.ipv6AddrPfxLength;
10089                         mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10090 
10091                         /* Type: stateless(1), stateful(2), unknown(3) */
10092                         if (ipif->ipif_flags & IPIF_ADDRCONF)
10093                                 mae6.ipv6AddrType = 1;
10094                         else
10095                                 mae6.ipv6AddrType = 2;
10096                         /* Anycast: true(1), false(2) */
10097                         if (ipif->ipif_flags & IPIF_ANYCAST)
10098                                 mae6.ipv6AddrAnycastFlag = 1;
10099                         else
10100                                 mae6.ipv6AddrAnycastFlag = 2;
10101 
10102                         /*
10103                          * Address status: preferred(1), deprecated(2),
10104                          * invalid(3), inaccessible(4), unknown(5)
10105                          */
10106                         if (ipif->ipif_flags & IPIF_NOLOCAL)
10107                                 mae6.ipv6AddrStatus = 3;
10108                         else if (ipif->ipif_flags & IPIF_DEPRECATED)
10109                                 mae6.ipv6AddrStatus = 2;
10110                         else
10111                                 mae6.ipv6AddrStatus = 1;
10112                         mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10113                         mae6.ipv6AddrInfo.ae_metric  =
10114                             ipif->ipif_ill->ill_metric;
10115                         mae6.ipv6AddrInfo.ae_pp_dst_addr =
10116                             ipif->ipif_v6pp_dst_addr;
10117                         mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10118                             ill->ill_flags | ill->ill_phyint->phyint_flags;
10119                         mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10120                         mae6.ipv6AddrIdentifier = ill->ill_token;
10121                         mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10122                         mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10123                         mae6.ipv6AddrRetransmitTime =
10124                             ill->ill_reachable_retrans_time;
10125                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10126                             (char *)&mae6, (int)mae6_size)) {
10127                                 ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10128                                     "allocate %u bytes\n",
10129                                     (uint_t)mae6_size));
10130                         }
10131                 }
10132         }
10133         rw_exit(&ipst->ips_ill_g_lock);
10134 
10135         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10136         ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10137             (int)optp->level, (int)optp->name, (int)optp->len));
10138         qreply(q, mpctl);
10139         return (mp2ctl);
10140 }
10141 
10142 /* IPv4 multicast group membership. */
10143 static mblk_t *
10144 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10145 {
10146         struct opthdr           *optp;
10147         mblk_t                  *mp2ctl;
10148         ill_t                   *ill;
10149         ipif_t                  *ipif;
10150         ilm_t                   *ilm;
10151         ip_member_t             ipm;
10152         mblk_t                  *mp_tail = NULL;
10153         ill_walk_context_t      ctx;
10154         zoneid_t                zoneid;
10155 
10156         /*
10157          * make a copy of the original message
10158          */
10159         mp2ctl = copymsg(mpctl);
10160         zoneid = Q_TO_CONN(q)->conn_zoneid;
10161 
10162         /* ipGroupMember table */
10163         optp = (struct opthdr *)&mpctl->b_rptr[
10164             sizeof (struct T_optmgmt_ack)];
10165         optp->level = MIB2_IP;
10166         optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10167 
10168         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10169         ill = ILL_START_WALK_V4(&ctx, ipst);
10170         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10171                 /* Make sure the ill isn't going away. */
10172                 if (!ill_check_and_refhold(ill))
10173                         continue;
10174                 rw_exit(&ipst->ips_ill_g_lock);
10175                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10176                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10177                         if (ilm->ilm_zoneid != zoneid &&
10178                             ilm->ilm_zoneid != ALL_ZONES)
10179                                 continue;
10180 
10181                         /* Is there an ipif for ilm_ifaddr? */
10182                         for (ipif = ill->ill_ipif; ipif != NULL;
10183                             ipif = ipif->ipif_next) {
10184                                 if (!IPIF_IS_CONDEMNED(ipif) &&
10185                                     ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10186                                     ilm->ilm_ifaddr != INADDR_ANY)
10187                                         break;
10188                         }
10189                         if (ipif != NULL) {
10190                                 ipif_get_name(ipif,
10191                                     ipm.ipGroupMemberIfIndex.o_bytes,
10192                                     OCTET_LENGTH);
10193                         } else {
10194                                 ill_get_name(ill,
10195                                     ipm.ipGroupMemberIfIndex.o_bytes,
10196                                     OCTET_LENGTH);
10197                         }
10198                         ipm.ipGroupMemberIfIndex.o_length =
10199                             mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10200 
10201                         ipm.ipGroupMemberAddress = ilm->ilm_addr;
10202                         ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10203                         ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10204                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10205                             (char *)&ipm, (int)sizeof (ipm))) {
10206                                 ip1dbg(("ip_snmp_get_mib2_ip_group: "
10207                                     "failed to allocate %u bytes\n",
10208                                     (uint_t)sizeof (ipm)));
10209                         }
10210                 }
10211                 rw_exit(&ill->ill_mcast_lock);
10212                 ill_refrele(ill);
10213                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10214         }
10215         rw_exit(&ipst->ips_ill_g_lock);
10216         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10217         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10218             (int)optp->level, (int)optp->name, (int)optp->len));
10219         qreply(q, mpctl);
10220         return (mp2ctl);
10221 }
10222 
10223 /* IPv6 multicast group membership. */
10224 static mblk_t *
10225 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10226 {
10227         struct opthdr           *optp;
10228         mblk_t                  *mp2ctl;
10229         ill_t                   *ill;
10230         ilm_t                   *ilm;
10231         ipv6_member_t           ipm6;
10232         mblk_t                  *mp_tail = NULL;
10233         ill_walk_context_t      ctx;
10234         zoneid_t                zoneid;
10235 
10236         /*
10237          * make a copy of the original message
10238          */
10239         mp2ctl = copymsg(mpctl);
10240         zoneid = Q_TO_CONN(q)->conn_zoneid;
10241 
10242         /* ip6GroupMember table */
10243         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10244         optp->level = MIB2_IP6;
10245         optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10246 
10247         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10248         ill = ILL_START_WALK_V6(&ctx, ipst);
10249         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10250                 /* Make sure the ill isn't going away. */
10251                 if (!ill_check_and_refhold(ill))
10252                         continue;
10253                 rw_exit(&ipst->ips_ill_g_lock);
10254                 /*
10255                  * Normally we don't have any members on under IPMP interfaces.
10256                  * We report them as a debugging aid.
10257                  */
10258                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10259                 ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10260                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10261                         if (ilm->ilm_zoneid != zoneid &&
10262                             ilm->ilm_zoneid != ALL_ZONES)
10263                                 continue;       /* not this zone */
10264                         ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10265                         ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10266                         ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10267                         if (!snmp_append_data2(mpctl->b_cont,
10268                             &mp_tail,
10269                             (char *)&ipm6, (int)sizeof (ipm6))) {
10270                                 ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10271                                     "failed to allocate %u bytes\n",
10272                                     (uint_t)sizeof (ipm6)));
10273                         }
10274                 }
10275                 rw_exit(&ill->ill_mcast_lock);
10276                 ill_refrele(ill);
10277                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10278         }
10279         rw_exit(&ipst->ips_ill_g_lock);
10280 
10281         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10282         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10283             (int)optp->level, (int)optp->name, (int)optp->len));
10284         qreply(q, mpctl);
10285         return (mp2ctl);
10286 }
10287 
10288 /* IP multicast filtered sources */
10289 static mblk_t *
10290 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10291 {
10292         struct opthdr           *optp;
10293         mblk_t                  *mp2ctl;
10294         ill_t                   *ill;
10295         ipif_t                  *ipif;
10296         ilm_t                   *ilm;
10297         ip_grpsrc_t             ips;
10298         mblk_t                  *mp_tail = NULL;
10299         ill_walk_context_t      ctx;
10300         zoneid_t                zoneid;
10301         int                     i;
10302         slist_t                 *sl;
10303 
10304         /*
10305          * make a copy of the original message
10306          */
10307         mp2ctl = copymsg(mpctl);
10308         zoneid = Q_TO_CONN(q)->conn_zoneid;
10309 
10310         /* ipGroupSource table */
10311         optp = (struct opthdr *)&mpctl->b_rptr[
10312             sizeof (struct T_optmgmt_ack)];
10313         optp->level = MIB2_IP;
10314         optp->name = EXPER_IP_GROUP_SOURCES;
10315 
10316         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10317         ill = ILL_START_WALK_V4(&ctx, ipst);
10318         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10319                 /* Make sure the ill isn't going away. */
10320                 if (!ill_check_and_refhold(ill))
10321                         continue;
10322                 rw_exit(&ipst->ips_ill_g_lock);
10323                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10324                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10325                         sl = ilm->ilm_filter;
10326                         if (ilm->ilm_zoneid != zoneid &&
10327                             ilm->ilm_zoneid != ALL_ZONES)
10328                                 continue;
10329                         if (SLIST_IS_EMPTY(sl))
10330                                 continue;
10331 
10332                         /* Is there an ipif for ilm_ifaddr? */
10333                         for (ipif = ill->ill_ipif; ipif != NULL;
10334                             ipif = ipif->ipif_next) {
10335                                 if (!IPIF_IS_CONDEMNED(ipif) &&
10336                                     ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10337                                     ilm->ilm_ifaddr != INADDR_ANY)
10338                                         break;
10339                         }
10340                         if (ipif != NULL) {
10341                                 ipif_get_name(ipif,
10342                                     ips.ipGroupSourceIfIndex.o_bytes,
10343                                     OCTET_LENGTH);
10344                         } else {
10345                                 ill_get_name(ill,
10346                                     ips.ipGroupSourceIfIndex.o_bytes,
10347                                     OCTET_LENGTH);
10348                         }
10349                         ips.ipGroupSourceIfIndex.o_length =
10350                             mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10351 
10352                         ips.ipGroupSourceGroup = ilm->ilm_addr;
10353                         for (i = 0; i < sl->sl_numsrc; i++) {
10354                                 if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10355                                         continue;
10356                                 IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10357                                     ips.ipGroupSourceAddress);
10358                                 if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10359                                     (char *)&ips, (int)sizeof (ips)) == 0) {
10360                                         ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10361                                             " failed to allocate %u bytes\n",
10362                                             (uint_t)sizeof (ips)));
10363                                 }
10364                         }
10365                 }
10366                 rw_exit(&ill->ill_mcast_lock);
10367                 ill_refrele(ill);
10368                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10369         }
10370         rw_exit(&ipst->ips_ill_g_lock);
10371         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10372         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10373             (int)optp->level, (int)optp->name, (int)optp->len));
10374         qreply(q, mpctl);
10375         return (mp2ctl);
10376 }
10377 
10378 /* IPv6 multicast filtered sources. */
10379 static mblk_t *
10380 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10381 {
10382         struct opthdr           *optp;
10383         mblk_t                  *mp2ctl;
10384         ill_t                   *ill;
10385         ilm_t                   *ilm;
10386         ipv6_grpsrc_t           ips6;
10387         mblk_t                  *mp_tail = NULL;
10388         ill_walk_context_t      ctx;
10389         zoneid_t                zoneid;
10390         int                     i;
10391         slist_t                 *sl;
10392 
10393         /*
10394          * make a copy of the original message
10395          */
10396         mp2ctl = copymsg(mpctl);
10397         zoneid = Q_TO_CONN(q)->conn_zoneid;
10398 
10399         /* ip6GroupMember table */
10400         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10401         optp->level = MIB2_IP6;
10402         optp->name = EXPER_IP6_GROUP_SOURCES;
10403 
10404         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10405         ill = ILL_START_WALK_V6(&ctx, ipst);
10406         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10407                 /* Make sure the ill isn't going away. */
10408                 if (!ill_check_and_refhold(ill))
10409                         continue;
10410                 rw_exit(&ipst->ips_ill_g_lock);
10411                 /*
10412                  * Normally we don't have any members on under IPMP interfaces.
10413                  * We report them as a debugging aid.
10414                  */
10415                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10416                 ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10417                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10418                         sl = ilm->ilm_filter;
10419                         if (ilm->ilm_zoneid != zoneid &&
10420                             ilm->ilm_zoneid != ALL_ZONES)
10421                                 continue;
10422                         if (SLIST_IS_EMPTY(sl))
10423                                 continue;
10424                         ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10425                         for (i = 0; i < sl->sl_numsrc; i++) {
10426                                 ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10427                                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10428                                     (char *)&ips6, (int)sizeof (ips6))) {
10429                                         ip1dbg(("ip_snmp_get_mib2_ip6_"
10430                                             "group_src: failed to allocate "
10431                                             "%u bytes\n",
10432                                             (uint_t)sizeof (ips6)));
10433                                 }
10434                         }
10435                 }
10436                 rw_exit(&ill->ill_mcast_lock);
10437                 ill_refrele(ill);
10438                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10439         }
10440         rw_exit(&ipst->ips_ill_g_lock);
10441 
10442         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10443         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10444             (int)optp->level, (int)optp->name, (int)optp->len));
10445         qreply(q, mpctl);
10446         return (mp2ctl);
10447 }
10448 
10449 /* Multicast routing virtual interface table. */
10450 static mblk_t *
10451 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10452 {
10453         struct opthdr           *optp;
10454         mblk_t                  *mp2ctl;
10455 
10456         /*
10457          * make a copy of the original message
10458          */
10459         mp2ctl = copymsg(mpctl);
10460 
10461         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10462         optp->level = EXPER_DVMRP;
10463         optp->name = EXPER_DVMRP_VIF;
10464         if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10465                 ip0dbg(("ip_mroute_vif: failed\n"));
10466         }
10467         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10468         ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10469             (int)optp->level, (int)optp->name, (int)optp->len));
10470         qreply(q, mpctl);
10471         return (mp2ctl);
10472 }
10473 
10474 /* Multicast routing table. */
10475 static mblk_t *
10476 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10477 {
10478         struct opthdr           *optp;
10479         mblk_t                  *mp2ctl;
10480 
10481         /*
10482          * make a copy of the original message
10483          */
10484         mp2ctl = copymsg(mpctl);
10485 
10486         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10487         optp->level = EXPER_DVMRP;
10488         optp->name = EXPER_DVMRP_MRT;
10489         if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10490                 ip0dbg(("ip_mroute_mrt: failed\n"));
10491         }
10492         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10493         ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10494             (int)optp->level, (int)optp->name, (int)optp->len));
10495         qreply(q, mpctl);
10496         return (mp2ctl);
10497 }
10498 
10499 /*
10500  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10501  * in one IRE walk.
10502  */
10503 static mblk_t *
10504 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10505     ip_stack_t *ipst)
10506 {
10507         struct opthdr   *optp;
10508         mblk_t          *mp2ctl;        /* Returned */
10509         mblk_t          *mp3ctl;        /* nettomedia */
10510         mblk_t          *mp4ctl;        /* routeattrs */
10511         iproutedata_t   ird;
10512         zoneid_t        zoneid;
10513 
10514         /*
10515          * make copies of the original message
10516          *      - mp2ctl is returned unchanged to the caller for its use
10517          *      - mpctl is sent upstream as ipRouteEntryTable
10518          *      - mp3ctl is sent upstream as ipNetToMediaEntryTable
10519          *      - mp4ctl is sent upstream as ipRouteAttributeTable
10520          */
10521         mp2ctl = copymsg(mpctl);
10522         mp3ctl = copymsg(mpctl);
10523         mp4ctl = copymsg(mpctl);
10524         if (mp3ctl == NULL || mp4ctl == NULL) {
10525                 freemsg(mp4ctl);
10526                 freemsg(mp3ctl);
10527                 freemsg(mp2ctl);
10528                 freemsg(mpctl);
10529                 return (NULL);
10530         }
10531 
10532         bzero(&ird, sizeof (ird));
10533 
10534         ird.ird_route.lp_head = mpctl->b_cont;
10535         ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10536         ird.ird_attrs.lp_head = mp4ctl->b_cont;
10537         /*
10538          * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10539          * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10540          * intended a temporary solution until a proper MIB API is provided
10541          * that provides complete filtering/caller-opt-in.
10542          */
10543         if (level == EXPER_IP_AND_ALL_IRES)
10544                 ird.ird_flags |= IRD_REPORT_ALL;
10545 
10546         zoneid = Q_TO_CONN(q)->conn_zoneid;
10547         ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10548 
10549         /* ipRouteEntryTable in mpctl */
10550         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10551         optp->level = MIB2_IP;
10552         optp->name = MIB2_IP_ROUTE;
10553         optp->len = msgdsize(ird.ird_route.lp_head);
10554         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10555             (int)optp->level, (int)optp->name, (int)optp->len));
10556         qreply(q, mpctl);
10557 
10558         /* ipNetToMediaEntryTable in mp3ctl */
10559         ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10560 
10561         optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10562         optp->level = MIB2_IP;
10563         optp->name = MIB2_IP_MEDIA;
10564         optp->len = msgdsize(ird.ird_netmedia.lp_head);
10565         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10566             (int)optp->level, (int)optp->name, (int)optp->len));
10567         qreply(q, mp3ctl);
10568 
10569         /* ipRouteAttributeTable in mp4ctl */
10570         optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10571         optp->level = MIB2_IP;
10572         optp->name = EXPER_IP_RTATTR;
10573         optp->len = msgdsize(ird.ird_attrs.lp_head);
10574         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10575             (int)optp->level, (int)optp->name, (int)optp->len));
10576         if (optp->len == 0)
10577                 freemsg(mp4ctl);
10578         else
10579                 qreply(q, mp4ctl);
10580 
10581         return (mp2ctl);
10582 }
10583 
10584 /*
10585  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10586  * ipv6NetToMediaEntryTable in an NDP walk.
10587  */
10588 static mblk_t *
10589 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10590     ip_stack_t *ipst)
10591 {
10592         struct opthdr   *optp;
10593         mblk_t          *mp2ctl;        /* Returned */
10594         mblk_t          *mp3ctl;        /* nettomedia */
10595         mblk_t          *mp4ctl;        /* routeattrs */
10596         iproutedata_t   ird;
10597         zoneid_t        zoneid;
10598 
10599         /*
10600          * make copies of the original message
10601          *      - mp2ctl is returned unchanged to the caller for its use
10602          *      - mpctl is sent upstream as ipv6RouteEntryTable
10603          *      - mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10604          *      - mp4ctl is sent upstream as ipv6RouteAttributeTable
10605          */
10606         mp2ctl = copymsg(mpctl);
10607         mp3ctl = copymsg(mpctl);
10608         mp4ctl = copymsg(mpctl);
10609         if (mp3ctl == NULL || mp4ctl == NULL) {
10610                 freemsg(mp4ctl);
10611                 freemsg(mp3ctl);
10612                 freemsg(mp2ctl);
10613                 freemsg(mpctl);
10614                 return (NULL);
10615         }
10616 
10617         bzero(&ird, sizeof (ird));
10618 
10619         ird.ird_route.lp_head = mpctl->b_cont;
10620         ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10621         ird.ird_attrs.lp_head = mp4ctl->b_cont;
10622         /*
10623          * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10624          * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10625          * intended a temporary solution until a proper MIB API is provided
10626          * that provides complete filtering/caller-opt-in.
10627          */
10628         if (level == EXPER_IP_AND_ALL_IRES)
10629                 ird.ird_flags |= IRD_REPORT_ALL;
10630 
10631         zoneid = Q_TO_CONN(q)->conn_zoneid;
10632         ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10633 
10634         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10635         optp->level = MIB2_IP6;
10636         optp->name = MIB2_IP6_ROUTE;
10637         optp->len = msgdsize(ird.ird_route.lp_head);
10638         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10639             (int)optp->level, (int)optp->name, (int)optp->len));
10640         qreply(q, mpctl);
10641 
10642         /* ipv6NetToMediaEntryTable in mp3ctl */
10643         ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10644 
10645         optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10646         optp->level = MIB2_IP6;
10647         optp->name = MIB2_IP6_MEDIA;
10648         optp->len = msgdsize(ird.ird_netmedia.lp_head);
10649         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10650             (int)optp->level, (int)optp->name, (int)optp->len));
10651         qreply(q, mp3ctl);
10652 
10653         /* ipv6RouteAttributeTable in mp4ctl */
10654         optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10655         optp->level = MIB2_IP6;
10656         optp->name = EXPER_IP_RTATTR;
10657         optp->len = msgdsize(ird.ird_attrs.lp_head);
10658         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10659             (int)optp->level, (int)optp->name, (int)optp->len));
10660         if (optp->len == 0)
10661                 freemsg(mp4ctl);
10662         else
10663                 qreply(q, mp4ctl);
10664 
10665         return (mp2ctl);
10666 }
10667 
10668 /*
10669  * IPv6 mib: One per ill
10670  */
10671 static mblk_t *
10672 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10673     boolean_t legacy_req)
10674 {
10675         struct opthdr           *optp;
10676         mblk_t                  *mp2ctl;
10677         ill_t                   *ill;
10678         ill_walk_context_t      ctx;
10679         mblk_t                  *mp_tail = NULL;
10680         mib2_ipv6AddrEntry_t    mae6;
10681         mib2_ipIfStatsEntry_t   *ise;
10682         size_t                  ise_size, iae_size;
10683 
10684         /*
10685          * Make a copy of the original message
10686          */
10687         mp2ctl = copymsg(mpctl);
10688 
10689         /* fixed length IPv6 structure ... */
10690 
10691         if (legacy_req) {
10692                 ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10693                     mib2_ipIfStatsEntry_t);
10694                 iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10695         } else {
10696                 ise_size = sizeof (mib2_ipIfStatsEntry_t);
10697                 iae_size = sizeof (mib2_ipv6AddrEntry_t);
10698         }
10699 
10700         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10701         optp->level = MIB2_IP6;
10702         optp->name = 0;
10703         /* Include "unknown interface" ip6_mib */
10704         ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10705         ipst->ips_ip6_mib.ipIfStatsIfIndex =
10706             MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10707         SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10708             ipst->ips_ipv6_forwarding ? 1 : 2);
10709         SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10710             ipst->ips_ipv6_def_hops);
10711         SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10712             sizeof (mib2_ipIfStatsEntry_t));
10713         SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10714             sizeof (mib2_ipv6AddrEntry_t));
10715         SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10716             sizeof (mib2_ipv6RouteEntry_t));
10717         SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10718             sizeof (mib2_ipv6NetToMediaEntry_t));
10719         SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10720             sizeof (ipv6_member_t));
10721         SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10722             sizeof (ipv6_grpsrc_t));
10723 
10724         /*
10725          * Synchronize 64- and 32-bit counters
10726          */
10727         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10728             ipIfStatsHCInReceives);
10729         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10730             ipIfStatsHCInDelivers);
10731         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10732             ipIfStatsHCOutRequests);
10733         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10734             ipIfStatsHCOutForwDatagrams);
10735         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10736             ipIfStatsHCOutMcastPkts);
10737         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10738             ipIfStatsHCInMcastPkts);
10739 
10740         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10741             (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10742                 ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10743                     (uint_t)ise_size));
10744         } else if (legacy_req) {
10745                 /* Adjust the EntrySize fields for legacy requests. */
10746                 ise =
10747                     (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10748                 SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10749                 SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10750         }
10751 
10752         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10753         ill = ILL_START_WALK_V6(&ctx, ipst);
10754         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10755                 ill->ill_ip_mib->ipIfStatsIfIndex =
10756                     ill->ill_phyint->phyint_ifindex;
10757                 SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10758                     ipst->ips_ipv6_forwarding ? 1 : 2);
10759                 SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10760                     ill->ill_max_hops);
10761 
10762                 /*
10763                  * Synchronize 64- and 32-bit counters
10764                  */
10765                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10766                     ipIfStatsHCInReceives);
10767                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10768                     ipIfStatsHCInDelivers);
10769                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10770                     ipIfStatsHCOutRequests);
10771                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10772                     ipIfStatsHCOutForwDatagrams);
10773                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10774                     ipIfStatsHCOutMcastPkts);
10775                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10776                     ipIfStatsHCInMcastPkts);
10777 
10778                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10779                     (char *)ill->ill_ip_mib, (int)ise_size)) {
10780                         ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10781                         "%u bytes\n", (uint_t)ise_size));
10782                 } else if (legacy_req) {
10783                         /* Adjust the EntrySize fields for legacy requests. */
10784                         ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10785                             (int)ise_size);
10786                         SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10787                         SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10788                 }
10789         }
10790         rw_exit(&ipst->ips_ill_g_lock);
10791 
10792         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10793         ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10794             (int)optp->level, (int)optp->name, (int)optp->len));
10795         qreply(q, mpctl);
10796         return (mp2ctl);
10797 }
10798 
10799 /*
10800  * ICMPv6 mib: One per ill
10801  */
10802 static mblk_t *
10803 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10804 {
10805         struct opthdr           *optp;
10806         mblk_t                  *mp2ctl;
10807         ill_t                   *ill;
10808         ill_walk_context_t      ctx;
10809         mblk_t                  *mp_tail = NULL;
10810         /*
10811          * Make a copy of the original message
10812          */
10813         mp2ctl = copymsg(mpctl);
10814 
10815         /* fixed length ICMPv6 structure ... */
10816 
10817         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10818         optp->level = MIB2_ICMP6;
10819         optp->name = 0;
10820         /* Include "unknown interface" icmp6_mib */
10821         ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10822             MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10823         ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10824             sizeof (mib2_ipv6IfIcmpEntry_t);
10825         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10826             (char *)&ipst->ips_icmp6_mib,
10827             (int)sizeof (ipst->ips_icmp6_mib))) {
10828                 ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10829                     (uint_t)sizeof (ipst->ips_icmp6_mib)));
10830         }
10831 
10832         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10833         ill = ILL_START_WALK_V6(&ctx, ipst);
10834         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10835                 ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10836                     ill->ill_phyint->phyint_ifindex;
10837                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10838                     (char *)ill->ill_icmp6_mib,
10839                     (int)sizeof (*ill->ill_icmp6_mib))) {
10840                         ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10841                             "%u bytes\n",
10842                             (uint_t)sizeof (*ill->ill_icmp6_mib)));
10843                 }
10844         }
10845         rw_exit(&ipst->ips_ill_g_lock);
10846 
10847         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10848         ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10849             (int)optp->level, (int)optp->name, (int)optp->len));
10850         qreply(q, mpctl);
10851         return (mp2ctl);
10852 }
10853 
10854 /*
10855  * ire_walk routine to create both ipRouteEntryTable and
10856  * ipRouteAttributeTable in one IRE walk
10857  */
10858 static void
10859 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10860 {
10861         ill_t                           *ill;
10862         mib2_ipRouteEntry_t             *re;
10863         mib2_ipAttributeEntry_t         iaes;
10864         tsol_ire_gw_secattr_t           *attrp;
10865         tsol_gc_t                       *gc = NULL;
10866         tsol_gcgrp_t                    *gcgrp = NULL;
10867         ip_stack_t                      *ipst = ire->ire_ipst;
10868 
10869         ASSERT(ire->ire_ipversion == IPV4_VERSION);
10870 
10871         if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10872                 if (ire->ire_testhidden)
10873                         return;
10874                 if (ire->ire_type & IRE_IF_CLONE)
10875                         return;
10876         }
10877 
10878         if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10879                 return;
10880 
10881         if ((attrp = ire->ire_gw_secattr) != NULL) {
10882                 mutex_enter(&attrp->igsa_lock);
10883                 if ((gc = attrp->igsa_gc) != NULL) {
10884                         gcgrp = gc->gc_grp;
10885                         ASSERT(gcgrp != NULL);
10886                         rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10887                 }
10888                 mutex_exit(&attrp->igsa_lock);
10889         }
10890         /*
10891          * Return all IRE types for route table... let caller pick and choose
10892          */
10893         re->ipRouteDest = ire->ire_addr;
10894         ill = ire->ire_ill;
10895         re->ipRouteIfIndex.o_length = 0;
10896         if (ill != NULL) {
10897                 ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10898                 re->ipRouteIfIndex.o_length =
10899                     mi_strlen(re->ipRouteIfIndex.o_bytes);
10900         }
10901         re->ipRouteMetric1 = -1;
10902         re->ipRouteMetric2 = -1;
10903         re->ipRouteMetric3 = -1;
10904         re->ipRouteMetric4 = -1;
10905 
10906         re->ipRouteNextHop = ire->ire_gateway_addr;
10907         /* indirect(4), direct(3), or invalid(2) */
10908         if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10909                 re->ipRouteType = 2;
10910         else if (ire->ire_type & IRE_ONLINK)
10911                 re->ipRouteType = 3;
10912         else
10913                 re->ipRouteType = 4;
10914 
10915         re->ipRouteProto = -1;
10916         re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10917         re->ipRouteMask = ire->ire_mask;
10918         re->ipRouteMetric5 = -1;
10919         re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10920         if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10921                 re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10922 
10923         re->ipRouteInfo.re_frag_flag = 0;
10924         re->ipRouteInfo.re_rtt               = 0;
10925         re->ipRouteInfo.re_src_addr  = 0;
10926         re->ipRouteInfo.re_ref               = ire->ire_refcnt;
10927         re->ipRouteInfo.re_obpkt     = ire->ire_ob_pkt_count;
10928         re->ipRouteInfo.re_ibpkt     = ire->ire_ib_pkt_count;
10929         re->ipRouteInfo.re_flags     = ire->ire_flags;
10930 
10931         /* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10932         if (ire->ire_type & IRE_INTERFACE) {
10933                 ire_t *child;
10934 
10935                 rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10936                 child = ire->ire_dep_children;
10937                 while (child != NULL) {
10938                         re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10939                         re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10940                         child = child->ire_dep_sib_next;
10941                 }
10942                 rw_exit(&ipst->ips_ire_dep_lock);
10943         }
10944 
10945         if (ire->ire_flags & RTF_DYNAMIC) {
10946                 re->ipRouteInfo.re_ire_type  = IRE_HOST_REDIRECT;
10947         } else {
10948                 re->ipRouteInfo.re_ire_type  = ire->ire_type;
10949         }
10950 
10951         if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10952             (char *)re, (int)sizeof (*re))) {
10953                 ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10954                     (uint_t)sizeof (*re)));
10955         }
10956 
10957         if (gc != NULL) {
10958                 iaes.iae_routeidx = ird->ird_idx;
10959                 iaes.iae_doi = gc->gc_db->gcdb_doi;
10960                 iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10961 
10962                 if (!snmp_append_data2(ird->ird_attrs.lp_head,
10963                     &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10964                         ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
10965                             "bytes\n", (uint_t)sizeof (iaes)));
10966                 }
10967         }
10968 
10969         /* bump route index for next pass */
10970         ird->ird_idx++;
10971 
10972         kmem_free(re, sizeof (*re));
10973         if (gcgrp != NULL)
10974                 rw_exit(&gcgrp->gcgrp_rwlock);
10975 }
10976 
10977 /*
10978  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
10979  */
10980 static void
10981 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
10982 {
10983         ill_t                           *ill;
10984         mib2_ipv6RouteEntry_t           *re;
10985         mib2_ipAttributeEntry_t         iaes;
10986         tsol_ire_gw_secattr_t           *attrp;
10987         tsol_gc_t                       *gc = NULL;
10988         tsol_gcgrp_t                    *gcgrp = NULL;
10989         ip_stack_t                      *ipst = ire->ire_ipst;
10990 
10991         ASSERT(ire->ire_ipversion == IPV6_VERSION);
10992 
10993         if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10994                 if (ire->ire_testhidden)
10995                         return;
10996                 if (ire->ire_type & IRE_IF_CLONE)
10997                         return;
10998         }
10999 
11000         if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11001                 return;
11002 
11003         if ((attrp = ire->ire_gw_secattr) != NULL) {
11004                 mutex_enter(&attrp->igsa_lock);
11005                 if ((gc = attrp->igsa_gc) != NULL) {
11006                         gcgrp = gc->gc_grp;
11007                         ASSERT(gcgrp != NULL);
11008                         rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11009                 }
11010                 mutex_exit(&attrp->igsa_lock);
11011         }
11012         /*
11013          * Return all IRE types for route table... let caller pick and choose
11014          */
11015         re->ipv6RouteDest = ire->ire_addr_v6;
11016         re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11017         re->ipv6RouteIndex = 0;      /* Unique when multiple with same dest/plen */
11018         re->ipv6RouteIfIndex.o_length = 0;
11019         ill = ire->ire_ill;
11020         if (ill != NULL) {
11021                 ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11022                 re->ipv6RouteIfIndex.o_length =
11023                     mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11024         }
11025 
11026         ASSERT(!(ire->ire_type & IRE_BROADCAST));
11027 
11028         mutex_enter(&ire->ire_lock);
11029         re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11030         mutex_exit(&ire->ire_lock);
11031 
11032         /* remote(4), local(3), or discard(2) */
11033         if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11034                 re->ipv6RouteType = 2;
11035         else if (ire->ire_type & IRE_ONLINK)
11036                 re->ipv6RouteType = 3;
11037         else
11038                 re->ipv6RouteType = 4;
11039 
11040         re->ipv6RouteProtocol        = -1;
11041         re->ipv6RoutePolicy  = 0;
11042         re->ipv6RouteAge     = gethrestime_sec() - ire->ire_create_time;
11043         re->ipv6RouteNextHopRDI      = 0;
11044         re->ipv6RouteWeight  = 0;
11045         re->ipv6RouteMetric  = 0;
11046         re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11047         if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11048                 re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11049 
11050         re->ipv6RouteInfo.re_frag_flag       = 0;
11051         re->ipv6RouteInfo.re_rtt     = 0;
11052         re->ipv6RouteInfo.re_src_addr        = ipv6_all_zeros;
11053         re->ipv6RouteInfo.re_obpkt   = ire->ire_ob_pkt_count;
11054         re->ipv6RouteInfo.re_ibpkt   = ire->ire_ib_pkt_count;
11055         re->ipv6RouteInfo.re_ref     = ire->ire_refcnt;
11056         re->ipv6RouteInfo.re_flags   = ire->ire_flags;
11057 
11058         /* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11059         if (ire->ire_type & IRE_INTERFACE) {
11060                 ire_t *child;
11061 
11062                 rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11063                 child = ire->ire_dep_children;
11064                 while (child != NULL) {
11065                         re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11066                         re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11067                         child = child->ire_dep_sib_next;
11068                 }
11069                 rw_exit(&ipst->ips_ire_dep_lock);
11070         }
11071         if (ire->ire_flags & RTF_DYNAMIC) {
11072                 re->ipv6RouteInfo.re_ire_type        = IRE_HOST_REDIRECT;
11073         } else {
11074                 re->ipv6RouteInfo.re_ire_type        = ire->ire_type;
11075         }
11076 
11077         if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11078             (char *)re, (int)sizeof (*re))) {
11079                 ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11080                     (uint_t)sizeof (*re)));
11081         }
11082 
11083         if (gc != NULL) {
11084                 iaes.iae_routeidx = ird->ird_idx;
11085                 iaes.iae_doi = gc->gc_db->gcdb_doi;
11086                 iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11087 
11088                 if (!snmp_append_data2(ird->ird_attrs.lp_head,
11089                     &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11090                         ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11091                             "bytes\n", (uint_t)sizeof (iaes)));
11092                 }
11093         }
11094 
11095         /* bump route index for next pass */
11096         ird->ird_idx++;
11097 
11098         kmem_free(re, sizeof (*re));
11099         if (gcgrp != NULL)
11100                 rw_exit(&gcgrp->gcgrp_rwlock);
11101 }
11102 
11103 /*
11104  * ncec_walk routine to create ipv6NetToMediaEntryTable
11105  */
11106 static void
11107 ip_snmp_get2_v6_media(ncec_t *ncec, void *ptr)
11108 {
11109         iproutedata_t *ird              = ptr;
11110         ill_t                           *ill;
11111         mib2_ipv6NetToMediaEntry_t      ntme;
11112 
11113         ill = ncec->ncec_ill;
11114         /* skip arpce entries, and loopback ncec entries */
11115         if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11116                 return;
11117         /*
11118          * Neighbor cache entry attached to IRE with on-link
11119          * destination.
11120          * We report all IPMP groups on ncec_ill which is normally the upper.
11121          */
11122         ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11123         ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11124         ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11125         if (ncec->ncec_lladdr != NULL) {
11126                 bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11127                     ntme.ipv6NetToMediaPhysAddress.o_length);
11128         }
11129         /*
11130          * Note: Returns ND_* states. Should be:
11131          * reachable(1), stale(2), delay(3), probe(4),
11132          * invalid(5), unknown(6)
11133          */
11134         ntme.ipv6NetToMediaState = ncec->ncec_state;
11135         ntme.ipv6NetToMediaLastUpdated = 0;
11136 
11137         /* other(1), dynamic(2), static(3), local(4) */
11138         if (NCE_MYADDR(ncec)) {
11139                 ntme.ipv6NetToMediaType = 4;
11140         } else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11141                 ntme.ipv6NetToMediaType = 1; /* proxy */
11142         } else if (ncec->ncec_flags & NCE_F_STATIC) {
11143                 ntme.ipv6NetToMediaType = 3;
11144         } else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11145                 ntme.ipv6NetToMediaType = 1;
11146         } else {
11147                 ntme.ipv6NetToMediaType = 2;
11148         }
11149 
11150         if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11151             &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11152                 ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11153                     (uint_t)sizeof (ntme)));
11154         }
11155 }
11156 
11157 int
11158 nce2ace(ncec_t *ncec)
11159 {
11160         int flags = 0;
11161 
11162         if (NCE_ISREACHABLE(ncec))
11163                 flags |= ACE_F_RESOLVED;
11164         if (ncec->ncec_flags & NCE_F_AUTHORITY)
11165                 flags |= ACE_F_AUTHORITY;
11166         if (ncec->ncec_flags & NCE_F_PUBLISH)
11167                 flags |= ACE_F_PUBLISH;
11168         if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11169                 flags |= ACE_F_PERMANENT;
11170         if (NCE_MYADDR(ncec))
11171                 flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11172         if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11173                 flags |= ACE_F_UNVERIFIED;
11174         if (ncec->ncec_flags & NCE_F_AUTHORITY)
11175                 flags |= ACE_F_AUTHORITY;
11176         if (ncec->ncec_flags & NCE_F_DELAYED)
11177                 flags |= ACE_F_DELAYED;
11178         return (flags);
11179 }
11180 
11181 /*
11182  * ncec_walk routine to create ipNetToMediaEntryTable
11183  */
11184 static void
11185 ip_snmp_get2_v4_media(ncec_t *ncec, void *ptr)
11186 {
11187         iproutedata_t *ird              = ptr;
11188         ill_t                           *ill;
11189         mib2_ipNetToMediaEntry_t        ntme;
11190         const char                      *name = "unknown";
11191         ipaddr_t                        ncec_addr;
11192 
11193         ill = ncec->ncec_ill;
11194         if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11195             ill->ill_net_type == IRE_LOOPBACK)
11196                 return;
11197 
11198         /* We report all IPMP groups on ncec_ill which is normally the upper. */
11199         name = ill->ill_name;
11200         /* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11201         if (NCE_MYADDR(ncec)) {
11202                 ntme.ipNetToMediaType = 4;
11203         } else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11204                 ntme.ipNetToMediaType = 1;
11205         } else {
11206                 ntme.ipNetToMediaType = 3;
11207         }
11208         ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11209         bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11210             ntme.ipNetToMediaIfIndex.o_length);
11211 
11212         IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11213         bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11214 
11215         ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11216         ncec_addr = INADDR_BROADCAST;
11217         bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11218             sizeof (ncec_addr));
11219         /*
11220          * map all the flags to the ACE counterpart.
11221          */
11222         ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11223 
11224         ntme.ipNetToMediaPhysAddress.o_length =
11225             MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11226 
11227         if (!NCE_ISREACHABLE(ncec))
11228                 ntme.ipNetToMediaPhysAddress.o_length = 0;
11229         else {
11230                 if (ncec->ncec_lladdr != NULL) {
11231                         bcopy(ncec->ncec_lladdr,
11232                             ntme.ipNetToMediaPhysAddress.o_bytes,
11233                             ntme.ipNetToMediaPhysAddress.o_length);
11234                 }
11235         }
11236 
11237         if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11238             &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11239                 ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11240                     (uint_t)sizeof (ntme)));
11241         }
11242 }
11243 
11244 /*
11245  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11246  */
11247 /* ARGSUSED */
11248 int
11249 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11250 {
11251         switch (level) {
11252         case MIB2_IP:
11253         case MIB2_ICMP:
11254                 switch (name) {
11255                 default:
11256                         break;
11257                 }
11258                 return (1);
11259         default:
11260                 return (1);
11261         }
11262 }
11263 
11264 /*
11265  * When there exists both a 64- and 32-bit counter of a particular type
11266  * (i.e., InReceives), only the 64-bit counters are added.
11267  */
11268 void
11269 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11270 {
11271         UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11272         UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11273         UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11274         UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11275         UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11276         UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11277         UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11278         UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11279         UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11280         UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11281         UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11282         UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11283         UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11284         UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11285         UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11286         UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11287         UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11288         UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11289         UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11290         UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11291         UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11292         UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11293             o2->ipIfStatsInWrongIPVersion);
11294         UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11295             o2->ipIfStatsInWrongIPVersion);
11296         UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11297             o2->ipIfStatsOutSwitchIPVersion);
11298         UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11299         UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11300         UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11301             o2->ipIfStatsHCInForwDatagrams);
11302         UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11303         UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11304         UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11305             o2->ipIfStatsHCOutForwDatagrams);
11306         UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11307         UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11308         UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11309         UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11310         UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11311         UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11312         UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11313             o2->ipIfStatsHCOutMcastOctets);
11314         UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11315         UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11316         UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11317         UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11318         UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11319         UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11320         UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11321 }
11322 
11323 void
11324 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11325 {
11326         UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11327         UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11328         UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11329         UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11330         UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11331         UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11332         UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11333         UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11334         UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11335         UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11336             o2->ipv6IfIcmpInRouterSolicits);
11337         UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11338             o2->ipv6IfIcmpInRouterAdvertisements);
11339         UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11340             o2->ipv6IfIcmpInNeighborSolicits);
11341         UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11342             o2->ipv6IfIcmpInNeighborAdvertisements);
11343         UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11344         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11345             o2->ipv6IfIcmpInGroupMembQueries);
11346         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11347             o2->ipv6IfIcmpInGroupMembResponses);
11348         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11349             o2->ipv6IfIcmpInGroupMembReductions);
11350         UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11351         UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11352         UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11353             o2->ipv6IfIcmpOutDestUnreachs);
11354         UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11355             o2->ipv6IfIcmpOutAdminProhibs);
11356         UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11357         UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11358             o2->ipv6IfIcmpOutParmProblems);
11359         UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11360         UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11361         UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11362         UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11363             o2->ipv6IfIcmpOutRouterSolicits);
11364         UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11365             o2->ipv6IfIcmpOutRouterAdvertisements);
11366         UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11367             o2->ipv6IfIcmpOutNeighborSolicits);
11368         UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11369             o2->ipv6IfIcmpOutNeighborAdvertisements);
11370         UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11371         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11372             o2->ipv6IfIcmpOutGroupMembQueries);
11373         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11374             o2->ipv6IfIcmpOutGroupMembResponses);
11375         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11376             o2->ipv6IfIcmpOutGroupMembReductions);
11377         UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11378         UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11379         UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11380             o2->ipv6IfIcmpInBadNeighborAdvertisements);
11381         UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11382             o2->ipv6IfIcmpInBadNeighborSolicitations);
11383         UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11384         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11385             o2->ipv6IfIcmpInGroupMembTotal);
11386         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11387             o2->ipv6IfIcmpInGroupMembBadQueries);
11388         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11389             o2->ipv6IfIcmpInGroupMembBadReports);
11390         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11391             o2->ipv6IfIcmpInGroupMembOurReports);
11392 }
11393 
11394 /*
11395  * Called before the options are updated to check if this packet will
11396  * be source routed from here.
11397  * This routine assumes that the options are well formed i.e. that they
11398  * have already been checked.
11399  */
11400 boolean_t
11401 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11402 {
11403         ipoptp_t        opts;
11404         uchar_t         *opt;
11405         uint8_t         optval;
11406         uint8_t         optlen;
11407         ipaddr_t        dst;
11408 
11409         if (IS_SIMPLE_IPH(ipha)) {
11410                 ip2dbg(("not source routed\n"));
11411                 return (B_FALSE);
11412         }
11413         dst = ipha->ipha_dst;
11414         for (optval = ipoptp_first(&opts, ipha);
11415             optval != IPOPT_EOL;
11416             optval = ipoptp_next(&opts)) {
11417                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11418                 opt = opts.ipoptp_cur;
11419                 optlen = opts.ipoptp_len;
11420                 ip2dbg(("ip_source_routed: opt %d, len %d\n",
11421                     optval, optlen));
11422                 switch (optval) {
11423                         uint32_t off;
11424                 case IPOPT_SSRR:
11425                 case IPOPT_LSRR:
11426                         /*
11427                          * If dst is one of our addresses and there are some
11428                          * entries left in the source route return (true).
11429                          */
11430                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11431                                 ip2dbg(("ip_source_routed: not next"
11432                                     " source route 0x%x\n",
11433                                     ntohl(dst)));
11434                                 return (B_FALSE);
11435                         }
11436                         off = opt[IPOPT_OFFSET];
11437                         off--;
11438                         if (optlen < IP_ADDR_LEN ||
11439                             off > optlen - IP_ADDR_LEN) {
11440                                 /* End of source route */
11441                                 ip1dbg(("ip_source_routed: end of SR\n"));
11442                                 return (B_FALSE);
11443                         }
11444                         return (B_TRUE);
11445                 }
11446         }
11447         ip2dbg(("not source routed\n"));
11448         return (B_FALSE);
11449 }
11450 
11451 /*
11452  * ip_unbind is called by the transports to remove a conn from
11453  * the fanout table.
11454  */
11455 void
11456 ip_unbind(conn_t *connp)
11457 {
11458 
11459         ASSERT(!MUTEX_HELD(&connp->conn_lock));
11460 
11461         if (is_system_labeled() && connp->conn_anon_port) {
11462                 (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11463                     connp->conn_mlp_type, connp->conn_proto,
11464                     ntohs(connp->conn_lport), B_FALSE);
11465                 connp->conn_anon_port = 0;
11466         }
11467         connp->conn_mlp_type = mlptSingle;
11468 
11469         ipcl_hash_remove(connp);
11470 }
11471 
11472 /*
11473  * Used for deciding the MSS size for the upper layer. Thus
11474  * we need to check the outbound policy values in the conn.
11475  */
11476 int
11477 conn_ipsec_length(conn_t *connp)
11478 {
11479         ipsec_latch_t *ipl;
11480 
11481         ipl = connp->conn_latch;
11482         if (ipl == NULL)
11483                 return (0);
11484 
11485         if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11486                 return (0);
11487 
11488         return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11489 }
11490 
11491 /*
11492  * Returns an estimate of the IPsec headers size. This is used if
11493  * we don't want to call into IPsec to get the exact size.
11494  */
11495 int
11496 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11497 {
11498         ipsec_action_t *a;
11499 
11500         if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11501                 return (0);
11502 
11503         a = ixa->ixa_ipsec_action;
11504         if (a == NULL) {
11505                 ASSERT(ixa->ixa_ipsec_policy != NULL);
11506                 a = ixa->ixa_ipsec_policy->ipsp_act;
11507         }
11508         ASSERT(a != NULL);
11509 
11510         return (a->ipa_ovhd);
11511 }
11512 
11513 /*
11514  * If there are any source route options, return the true final
11515  * destination. Otherwise, return the destination.
11516  */
11517 ipaddr_t
11518 ip_get_dst(ipha_t *ipha)
11519 {
11520         ipoptp_t        opts;
11521         uchar_t         *opt;
11522         uint8_t         optval;
11523         uint8_t         optlen;
11524         ipaddr_t        dst;
11525         uint32_t off;
11526 
11527         dst = ipha->ipha_dst;
11528 
11529         if (IS_SIMPLE_IPH(ipha))
11530                 return (dst);
11531 
11532         for (optval = ipoptp_first(&opts, ipha);
11533             optval != IPOPT_EOL;
11534             optval = ipoptp_next(&opts)) {
11535                 opt = opts.ipoptp_cur;
11536                 optlen = opts.ipoptp_len;
11537                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11538                 switch (optval) {
11539                 case IPOPT_SSRR:
11540                 case IPOPT_LSRR:
11541                         off = opt[IPOPT_OFFSET];
11542                         /*
11543                          * If one of the conditions is true, it means
11544                          * end of options and dst already has the right
11545                          * value.
11546                          */
11547                         if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11548                                 off = optlen - IP_ADDR_LEN;
11549                                 bcopy(&opt[off], &dst, IP_ADDR_LEN);
11550                         }
11551                         return (dst);
11552                 default:
11553                         break;
11554                 }
11555         }
11556 
11557         return (dst);
11558 }
11559 
11560 /*
11561  * Outbound IP fragmentation routine.
11562  * Assumes the caller has checked whether or not fragmentation should
11563  * be allowed. Here we copy the DF bit from the header to all the generated
11564  * fragments.
11565  */
11566 int
11567 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11568     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11569     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11570 {
11571         int             i1;
11572         int             hdr_len;
11573         mblk_t          *hdr_mp;
11574         ipha_t          *ipha;
11575         int             ip_data_end;
11576         int             len;
11577         mblk_t          *mp = mp_orig;
11578         int             offset;
11579         ill_t           *ill = nce->nce_ill;
11580         ip_stack_t      *ipst = ill->ill_ipst;
11581         mblk_t          *carve_mp;
11582         uint32_t        frag_flag;
11583         uint_t          priority = mp->b_band;
11584         int             error = 0;
11585 
11586         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11587 
11588         if (pkt_len != msgdsize(mp)) {
11589                 ip0dbg(("Packet length mismatch: %d, %ld\n",
11590                     pkt_len, msgdsize(mp)));
11591                 freemsg(mp);
11592                 return (EINVAL);
11593         }
11594 
11595         if (max_frag == 0) {
11596                 ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11597                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11598                 ip_drop_output("FragFails: zero max_frag", mp, ill);
11599                 freemsg(mp);
11600                 return (EINVAL);
11601         }
11602 
11603         ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11604         ipha = (ipha_t *)mp->b_rptr;
11605         ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11606         frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11607 
11608         /*
11609          * Establish the starting offset.  May not be zero if we are fragging
11610          * a fragment that is being forwarded.
11611          */
11612         offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11613 
11614         /* TODO why is this test needed? */
11615         if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11616                 /* TODO: notify ulp somehow */
11617                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11618                 ip_drop_output("FragFails: bad starting offset", mp, ill);
11619                 freemsg(mp);
11620                 return (EINVAL);
11621         }
11622 
11623         hdr_len = IPH_HDR_LENGTH(ipha);
11624         ipha->ipha_hdr_checksum = 0;
11625 
11626         /*
11627          * Establish the number of bytes maximum per frag, after putting
11628          * in the header.
11629          */
11630         len = (max_frag - hdr_len) & ~7;
11631 
11632         /* Get a copy of the header for the trailing frags */
11633         hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11634             mp);
11635         if (hdr_mp == NULL) {
11636                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11637                 ip_drop_output("FragFails: no hdr_mp", mp, ill);
11638                 freemsg(mp);
11639                 return (ENOBUFS);
11640         }
11641 
11642         /* Store the starting offset, with the MoreFrags flag. */
11643         i1 = offset | IPH_MF | frag_flag;
11644         ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11645 
11646         /* Establish the ending byte offset, based on the starting offset. */
11647         offset <<= 3;
11648         ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11649 
11650         /* Store the length of the first fragment in the IP header. */
11651         i1 = len + hdr_len;
11652         ASSERT(i1 <= IP_MAXPACKET);
11653         ipha->ipha_length = htons((uint16_t)i1);
11654 
11655         /*
11656          * Compute the IP header checksum for the first frag.  We have to
11657          * watch out that we stop at the end of the header.
11658          */
11659         ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11660 
11661         /*
11662          * Now carve off the first frag.  Note that this will include the
11663          * original IP header.
11664          */
11665         if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11666                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11667                 ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11668                 freeb(hdr_mp);
11669                 freemsg(mp_orig);
11670                 return (ENOBUFS);
11671         }
11672 
11673         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11674 
11675         error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11676             ixa_cookie);
11677         if (error != 0 && error != EWOULDBLOCK) {
11678                 /* No point in sending the other fragments */
11679                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11680                 ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11681                 freeb(hdr_mp);
11682                 freemsg(mp_orig);
11683                 return (error);
11684         }
11685 
11686         /* No need to redo state machine in loop */
11687         ixaflags &= ~IXAF_REACH_CONF;
11688 
11689         /* Advance the offset to the second frag starting point. */
11690         offset += len;
11691         /*
11692          * Update hdr_len from the copied header - there might be less options
11693          * in the later fragments.
11694          */
11695         hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11696         /* Loop until done. */
11697         for (;;) {
11698                 uint16_t        offset_and_flags;
11699                 uint16_t        ip_len;
11700 
11701                 if (ip_data_end - offset > len) {
11702                         /*
11703                          * Carve off the appropriate amount from the original
11704                          * datagram.
11705                          */
11706                         if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11707                                 mp = NULL;
11708                                 break;
11709                         }
11710                         /*
11711                          * More frags after this one.  Get another copy
11712                          * of the header.
11713                          */
11714                         if (carve_mp->b_datap->db_ref == 1 &&
11715                             hdr_mp->b_wptr - hdr_mp->b_rptr <
11716                             carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11717                                 /* Inline IP header */
11718                                 carve_mp->b_rptr -= hdr_mp->b_wptr -
11719                                     hdr_mp->b_rptr;
11720                                 bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11721                                     hdr_mp->b_wptr - hdr_mp->b_rptr);
11722                                 mp = carve_mp;
11723                         } else {
11724                                 if (!(mp = copyb(hdr_mp))) {
11725                                         freemsg(carve_mp);
11726                                         break;
11727                                 }
11728                                 /* Get priority marking, if any. */
11729                                 mp->b_band = priority;
11730                                 mp->b_cont = carve_mp;
11731                         }
11732                         ipha = (ipha_t *)mp->b_rptr;
11733                         offset_and_flags = IPH_MF;
11734                 } else {
11735                         /*
11736                          * Last frag.  Consume the header. Set len to
11737                          * the length of this last piece.
11738                          */
11739                         len = ip_data_end - offset;
11740 
11741                         /*
11742                          * Carve off the appropriate amount from the original
11743                          * datagram.
11744                          */
11745                         if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11746                                 mp = NULL;
11747                                 break;
11748                         }
11749                         if (carve_mp->b_datap->db_ref == 1 &&
11750                             hdr_mp->b_wptr - hdr_mp->b_rptr <
11751                             carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11752                                 /* Inline IP header */
11753                                 carve_mp->b_rptr -= hdr_mp->b_wptr -
11754                                     hdr_mp->b_rptr;
11755                                 bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11756                                     hdr_mp->b_wptr - hdr_mp->b_rptr);
11757                                 mp = carve_mp;
11758                                 freeb(hdr_mp);
11759                                 hdr_mp = mp;
11760                         } else {
11761                                 mp = hdr_mp;
11762                                 /* Get priority marking, if any. */
11763                                 mp->b_band = priority;
11764                                 mp->b_cont = carve_mp;
11765                         }
11766                         ipha = (ipha_t *)mp->b_rptr;
11767                         /* A frag of a frag might have IPH_MF non-zero */
11768                         offset_and_flags =
11769                             ntohs(ipha->ipha_fragment_offset_and_flags) &
11770                             IPH_MF;
11771                 }
11772                 offset_and_flags |= (uint16_t)(offset >> 3);
11773                 offset_and_flags |= (uint16_t)frag_flag;
11774                 /* Store the offset and flags in the IP header. */
11775                 ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11776 
11777                 /* Store the length in the IP header. */
11778                 ip_len = (uint16_t)(len + hdr_len);
11779                 ipha->ipha_length = htons(ip_len);
11780 
11781                 /*
11782                  * Set the IP header checksum.  Note that mp is just
11783                  * the header, so this is easy to pass to ip_csum.
11784                  */
11785                 ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11786 
11787                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11788 
11789                 error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11790                     nolzid, ixa_cookie);
11791                 /* All done if we just consumed the hdr_mp. */
11792                 if (mp == hdr_mp) {
11793                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11794                         return (error);
11795                 }
11796                 if (error != 0 && error != EWOULDBLOCK) {
11797                         DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11798                             mblk_t *, hdr_mp);
11799                         /* No point in sending the other fragments */
11800                         break;
11801                 }
11802 
11803                 /* Otherwise, advance and loop. */
11804                 offset += len;
11805         }
11806         /* Clean up following allocation failure. */
11807         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11808         ip_drop_output("FragFails: loop ended", NULL, ill);
11809         if (mp != hdr_mp)
11810                 freeb(hdr_mp);
11811         if (mp != mp_orig)
11812                 freemsg(mp_orig);
11813         return (error);
11814 }
11815 
11816 /*
11817  * Copy the header plus those options which have the copy bit set
11818  */
11819 static mblk_t *
11820 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11821     mblk_t *src)
11822 {
11823         mblk_t  *mp;
11824         uchar_t *up;
11825 
11826         /*
11827          * Quick check if we need to look for options without the copy bit
11828          * set
11829          */
11830         mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11831         if (!mp)
11832                 return (mp);
11833         mp->b_rptr += ipst->ips_ip_wroff_extra;
11834         if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11835                 bcopy(rptr, mp->b_rptr, hdr_len);
11836                 mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11837                 return (mp);
11838         }
11839         up  = mp->b_rptr;
11840         bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11841         up += IP_SIMPLE_HDR_LENGTH;
11842         rptr += IP_SIMPLE_HDR_LENGTH;
11843         hdr_len -= IP_SIMPLE_HDR_LENGTH;
11844         while (hdr_len > 0) {
11845                 uint32_t optval;
11846                 uint32_t optlen;
11847 
11848                 optval = *rptr;
11849                 if (optval == IPOPT_EOL)
11850                         break;
11851                 if (optval == IPOPT_NOP)
11852                         optlen = 1;
11853                 else
11854                         optlen = rptr[1];
11855                 if (optval & IPOPT_COPY) {
11856                         bcopy(rptr, up, optlen);
11857                         up += optlen;
11858                 }
11859                 rptr += optlen;
11860                 hdr_len -= optlen;
11861         }
11862         /*
11863          * Make sure that we drop an even number of words by filling
11864          * with EOL to the next word boundary.
11865          */
11866         for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11867             hdr_len & 0x3; hdr_len++)
11868                 *up++ = IPOPT_EOL;
11869         mp->b_wptr = up;
11870         /* Update header length */
11871         mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11872         return (mp);
11873 }
11874 
11875 /*
11876  * Update any source route, record route, or timestamp options when
11877  * sending a packet back to ourselves.
11878  * Check that we are at end of strict source route.
11879  * The options have been sanity checked by ip_output_options().
11880  */
11881 void
11882 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11883 {
11884         ipoptp_t        opts;
11885         uchar_t         *opt;
11886         uint8_t         optval;
11887         uint8_t         optlen;
11888         ipaddr_t        dst;
11889         uint32_t        ts;
11890         timestruc_t     now;
11891 
11892         for (optval = ipoptp_first(&opts, ipha);
11893             optval != IPOPT_EOL;
11894             optval = ipoptp_next(&opts)) {
11895                 opt = opts.ipoptp_cur;
11896                 optlen = opts.ipoptp_len;
11897                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11898                 switch (optval) {
11899                         uint32_t off;
11900                 case IPOPT_SSRR:
11901                 case IPOPT_LSRR:
11902                         off = opt[IPOPT_OFFSET];
11903                         off--;
11904                         if (optlen < IP_ADDR_LEN ||
11905                             off > optlen - IP_ADDR_LEN) {
11906                                 /* End of source route */
11907                                 break;
11908                         }
11909                         /*
11910                          * This will only happen if two consecutive entries
11911                          * in the source route contains our address or if
11912                          * it is a packet with a loose source route which
11913                          * reaches us before consuming the whole source route
11914                          */
11915 
11916                         if (optval == IPOPT_SSRR) {
11917                                 return;
11918                         }
11919                         /*
11920                          * Hack: instead of dropping the packet truncate the
11921                          * source route to what has been used by filling the
11922                          * rest with IPOPT_NOP.
11923                          */
11924                         opt[IPOPT_OLEN] = (uint8_t)off;
11925                         while (off < optlen) {
11926                                 opt[off++] = IPOPT_NOP;
11927                         }
11928                         break;
11929                 case IPOPT_RR:
11930                         off = opt[IPOPT_OFFSET];
11931                         off--;
11932                         if (optlen < IP_ADDR_LEN ||
11933                             off > optlen - IP_ADDR_LEN) {
11934                                 /* No more room - ignore */
11935                                 ip1dbg((
11936                                     "ip_output_local_options: end of RR\n"));
11937                                 break;
11938                         }
11939                         dst = htonl(INADDR_LOOPBACK);
11940                         bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11941                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11942                         break;
11943                 case IPOPT_TS:
11944                         /* Insert timestamp if there is romm */
11945                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11946                         case IPOPT_TS_TSONLY:
11947                                 off = IPOPT_TS_TIMELEN;
11948                                 break;
11949                         case IPOPT_TS_PRESPEC:
11950                         case IPOPT_TS_PRESPEC_RFC791:
11951                                 /* Verify that the address matched */
11952                                 off = opt[IPOPT_OFFSET] - 1;
11953                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11954                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11955                                         /* Not for us */
11956                                         break;
11957                                 }
11958                                 /* FALLTHROUGH */
11959                         case IPOPT_TS_TSANDADDR:
11960                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11961                                 break;
11962                         default:
11963                                 /*
11964                                  * ip_*put_options should have already
11965                                  * dropped this packet.
11966                                  */
11967                                 cmn_err(CE_PANIC, "ip_output_local_options: "
11968                                     "unknown IT - bug in ip_output_options?\n");
11969                         }
11970                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
11971                                 /* Increase overflow counter */
11972                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
11973                                 opt[IPOPT_POS_OV_FLG] = (uint8_t)
11974                                     (opt[IPOPT_POS_OV_FLG] & 0x0F) |
11975                                     (off << 4);
11976                                 break;
11977                         }
11978                         off = opt[IPOPT_OFFSET] - 1;
11979                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11980                         case IPOPT_TS_PRESPEC:
11981                         case IPOPT_TS_PRESPEC_RFC791:
11982                         case IPOPT_TS_TSANDADDR:
11983                                 dst = htonl(INADDR_LOOPBACK);
11984                                 bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11985                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11986                                 /* FALLTHROUGH */
11987                         case IPOPT_TS_TSONLY:
11988                                 off = opt[IPOPT_OFFSET] - 1;
11989                                 /* Compute # of milliseconds since midnight */
11990                                 gethrestime(&now);
11991                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
11992                                     NSEC2MSEC(now.tv_nsec);
11993                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
11994                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
11995                                 break;
11996                         }
11997                         break;
11998                 }
11999         }
12000 }
12001 
12002 /*
12003  * Prepend an M_DATA fastpath header, and if none present prepend a
12004  * DL_UNITDATA_REQ. Frees the mblk on failure.
12005  *
12006  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12007  * If there is a change to them, the nce will be deleted (condemned) and
12008  * a new nce_t will be created when packets are sent. Thus we need no locks
12009  * to access those fields.
12010  *
12011  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12012  * we place b_band in dl_priority.dl_max.
12013  */
12014 static mblk_t *
12015 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12016 {
12017         uint_t  hlen;
12018         mblk_t *mp1;
12019         uint_t  priority;
12020         uchar_t *rptr;
12021 
12022         rptr = mp->b_rptr;
12023 
12024         ASSERT(DB_TYPE(mp) == M_DATA);
12025         priority = mp->b_band;
12026 
12027         ASSERT(nce != NULL);
12028         if ((mp1 = nce->nce_fp_mp) != NULL) {
12029                 hlen = MBLKL(mp1);
12030                 /*
12031                  * Check if we have enough room to prepend fastpath
12032                  * header
12033                  */
12034                 if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12035                         rptr -= hlen;
12036                         bcopy(mp1->b_rptr, rptr, hlen);
12037                         /*
12038                          * Set the b_rptr to the start of the link layer
12039                          * header
12040                          */
12041                         mp->b_rptr = rptr;
12042                         return (mp);
12043                 }
12044                 mp1 = copyb(mp1);
12045                 if (mp1 == NULL) {
12046                         ill_t *ill = nce->nce_ill;
12047 
12048                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12049                         ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12050                         freemsg(mp);
12051                         return (NULL);
12052                 }
12053                 mp1->b_band = priority;
12054                 mp1->b_cont = mp;
12055                 DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12056                 DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12057                 DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12058                 DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12059                 DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12060                 DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12061                 /*
12062                  * XXX disable ICK_VALID and compute checksum
12063                  * here; can happen if nce_fp_mp changes and
12064                  * it can't be copied now due to insufficient
12065                  * space. (unlikely, fp mp can change, but it
12066                  * does not increase in length)
12067                  */
12068                 return (mp1);
12069         }
12070         mp1 = copyb(nce->nce_dlur_mp);
12071 
12072         if (mp1 == NULL) {
12073                 ill_t *ill = nce->nce_ill;
12074 
12075                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12076                 ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12077                 freemsg(mp);
12078                 return (NULL);
12079         }
12080         mp1->b_cont = mp;
12081         if (priority != 0) {
12082                 mp1->b_band = priority;
12083                 ((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12084                     priority;
12085         }
12086         return (mp1);
12087 }
12088 
12089 /*
12090  * Finish the outbound IPsec processing. This function is called from
12091  * ipsec_out_process() if the IPsec packet was processed
12092  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12093  * asynchronously.
12094  *
12095  * This is common to IPv4 and IPv6.
12096  */
12097 int
12098 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12099 {
12100         iaflags_t       ixaflags = ixa->ixa_flags;
12101         uint_t          pktlen;
12102 
12103 
12104         /* AH/ESP don't update ixa_pktlen when they modify the packet */
12105         if (ixaflags & IXAF_IS_IPV4) {
12106                 ipha_t          *ipha = (ipha_t *)mp->b_rptr;
12107 
12108                 ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12109                 pktlen = ntohs(ipha->ipha_length);
12110         } else {
12111                 ip6_t           *ip6h = (ip6_t *)mp->b_rptr;
12112 
12113                 ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12114                 pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12115         }
12116 
12117         /*
12118          * We release any hard reference on the SAs here to make
12119          * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12120          * on the SAs.
12121          * If in the future we want the hard latching of the SAs in the
12122          * ip_xmit_attr_t then we should remove this.
12123          */
12124         if (ixa->ixa_ipsec_esp_sa != NULL) {
12125                 IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12126                 ixa->ixa_ipsec_esp_sa = NULL;
12127         }
12128         if (ixa->ixa_ipsec_ah_sa != NULL) {
12129                 IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12130                 ixa->ixa_ipsec_ah_sa = NULL;
12131         }
12132 
12133         /* Do we need to fragment? */
12134         if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12135             pktlen > ixa->ixa_fragsize) {
12136                 if (ixaflags & IXAF_IS_IPV4) {
12137                         ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12138                         /*
12139                          * We check for the DF case in ipsec_out_process
12140                          * hence this only handles the non-DF case.
12141                          */
12142                         return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12143                             pktlen, ixa->ixa_fragsize,
12144                             ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12145                             ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12146                             &ixa->ixa_cookie));
12147                 } else {
12148                         mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12149                         if (mp == NULL) {
12150                                 /* MIB and ip_drop_output already done */
12151                                 return (ENOMEM);
12152                         }
12153                         pktlen += sizeof (ip6_frag_t);
12154                         if (pktlen > ixa->ixa_fragsize) {
12155                                 return (ip_fragment_v6(mp, ixa->ixa_nce,
12156                                     ixa->ixa_flags, pktlen,
12157                                     ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12158                                     ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12159                                     ixa->ixa_postfragfn, &ixa->ixa_cookie));
12160                         }
12161                 }
12162         }
12163         return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12164             pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12165             ixa->ixa_no_loop_zoneid, NULL));
12166 }
12167 
12168 /*
12169  * Finish the inbound IPsec processing. This function is called from
12170  * ipsec_out_process() if the IPsec packet was processed
12171  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12172  * asynchronously.
12173  *
12174  * This is common to IPv4 and IPv6.
12175  */
12176 void
12177 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12178 {
12179         iaflags_t       iraflags = ira->ira_flags;
12180 
12181         /* Length might have changed */
12182         if (iraflags & IRAF_IS_IPV4) {
12183                 ipha_t          *ipha = (ipha_t *)mp->b_rptr;
12184 
12185                 ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12186                 ira->ira_pktlen = ntohs(ipha->ipha_length);
12187                 ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12188                 ira->ira_protocol = ipha->ipha_protocol;
12189 
12190                 ip_fanout_v4(mp, ipha, ira);
12191         } else {
12192                 ip6_t           *ip6h = (ip6_t *)mp->b_rptr;
12193                 uint8_t         *nexthdrp;
12194 
12195                 ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12196                 ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12197                 if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12198                     &nexthdrp)) {
12199                         /* Malformed packet */
12200                         BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12201                         ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12202                         freemsg(mp);
12203                         return;
12204                 }
12205                 ira->ira_protocol = *nexthdrp;
12206                 ip_fanout_v6(mp, ip6h, ira);
12207         }
12208 }
12209 
12210 /*
12211  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12212  *
12213  * If this function returns B_TRUE, the requested SA's have been filled
12214  * into the ixa_ipsec_*_sa pointers.
12215  *
12216  * If the function returns B_FALSE, the packet has been "consumed", most
12217  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12218  *
12219  * The SA references created by the protocol-specific "select"
12220  * function will be released in ip_output_post_ipsec.
12221  */
12222 static boolean_t
12223 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12224 {
12225         boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12226         ipsec_policy_t *pp;
12227         ipsec_action_t *ap;
12228 
12229         ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12230         ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12231             (ixa->ixa_ipsec_action != NULL));
12232 
12233         ap = ixa->ixa_ipsec_action;
12234         if (ap == NULL) {
12235                 pp = ixa->ixa_ipsec_policy;
12236                 ASSERT(pp != NULL);
12237                 ap = pp->ipsp_act;
12238                 ASSERT(ap != NULL);
12239         }
12240 
12241         /*
12242          * We have an action.  now, let's select SA's.
12243          * A side effect of setting ixa_ipsec_*_sa is that it will
12244          * be cached in the conn_t.
12245          */
12246         if (ap->ipa_want_esp) {
12247                 if (ixa->ixa_ipsec_esp_sa == NULL) {
12248                         need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12249                             IPPROTO_ESP);
12250                 }
12251                 ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12252         }
12253 
12254         if (ap->ipa_want_ah) {
12255                 if (ixa->ixa_ipsec_ah_sa == NULL) {
12256                         need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12257                             IPPROTO_AH);
12258                 }
12259                 ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12260                 /*
12261                  * The ESP and AH processing order needs to be preserved
12262                  * when both protocols are required (ESP should be applied
12263                  * before AH for an outbound packet). Force an ESP ACQUIRE
12264                  * when both ESP and AH are required, and an AH ACQUIRE
12265                  * is needed.
12266                  */
12267                 if (ap->ipa_want_esp && need_ah_acquire)
12268                         need_esp_acquire = B_TRUE;
12269         }
12270 
12271         /*
12272          * Send an ACQUIRE (extended, regular, or both) if we need one.
12273          * Release SAs that got referenced, but will not be used until we
12274          * acquire _all_ of the SAs we need.
12275          */
12276         if (need_ah_acquire || need_esp_acquire) {
12277                 if (ixa->ixa_ipsec_ah_sa != NULL) {
12278                         IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12279                         ixa->ixa_ipsec_ah_sa = NULL;
12280                 }
12281                 if (ixa->ixa_ipsec_esp_sa != NULL) {
12282                         IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12283                         ixa->ixa_ipsec_esp_sa = NULL;
12284                 }
12285 
12286                 sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12287                 return (B_FALSE);
12288         }
12289 
12290         return (B_TRUE);
12291 }
12292 
12293 /*
12294  * Handle IPsec output processing.
12295  * This function is only entered once for a given packet.
12296  * We try to do things synchronously, but if we need to have user-level
12297  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12298  * will be completed
12299  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12300  *  - when asynchronous ESP is done it will do AH
12301  *
12302  * In all cases we come back in ip_output_post_ipsec() to fragment and
12303  * send out the packet.
12304  */
12305 int
12306 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12307 {
12308         ill_t           *ill = ixa->ixa_nce->nce_ill;
12309         ip_stack_t      *ipst = ixa->ixa_ipst;
12310         ipsec_stack_t   *ipss;
12311         ipsec_policy_t  *pp;
12312         ipsec_action_t  *ap;
12313 
12314         ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12315 
12316         ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12317             (ixa->ixa_ipsec_action != NULL));
12318 
12319         ipss = ipst->ips_netstack->netstack_ipsec;
12320         if (!ipsec_loaded(ipss)) {
12321                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12322                 ip_drop_packet(mp, B_TRUE, ill,
12323                     DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12324                     &ipss->ipsec_dropper);
12325                 return (ENOTSUP);
12326         }
12327 
12328         ap = ixa->ixa_ipsec_action;
12329         if (ap == NULL) {
12330                 pp = ixa->ixa_ipsec_policy;
12331                 ASSERT(pp != NULL);
12332                 ap = pp->ipsp_act;
12333                 ASSERT(ap != NULL);
12334         }
12335 
12336         /* Handle explicit drop action and bypass. */
12337         switch (ap->ipa_act.ipa_type) {
12338         case IPSEC_ACT_DISCARD:
12339         case IPSEC_ACT_REJECT:
12340                 ip_drop_packet(mp, B_FALSE, ill,
12341                     DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12342                 return (EHOSTUNREACH);  /* IPsec policy failure */
12343         case IPSEC_ACT_BYPASS:
12344                 return (ip_output_post_ipsec(mp, ixa));
12345         }
12346 
12347         /*
12348          * The order of processing is first insert a IP header if needed.
12349          * Then insert the ESP header and then the AH header.
12350          */
12351         if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12352                 /*
12353                  * First get the outer IP header before sending
12354                  * it to ESP.
12355                  */
12356                 ipha_t *oipha, *iipha;
12357                 mblk_t *outer_mp, *inner_mp;
12358 
12359                 if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12360                         (void) mi_strlog(ill->ill_rq, 0,
12361                             SL_ERROR|SL_TRACE|SL_CONSOLE,
12362                             "ipsec_out_process: "
12363                             "Self-Encapsulation failed: Out of memory\n");
12364                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12365                         ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12366                         freemsg(mp);
12367                         return (ENOBUFS);
12368                 }
12369                 inner_mp = mp;
12370                 ASSERT(inner_mp->b_datap->db_type == M_DATA);
12371                 oipha = (ipha_t *)outer_mp->b_rptr;
12372                 iipha = (ipha_t *)inner_mp->b_rptr;
12373                 *oipha = *iipha;
12374                 outer_mp->b_wptr += sizeof (ipha_t);
12375                 oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12376                     sizeof (ipha_t));
12377                 oipha->ipha_protocol = IPPROTO_ENCAP;
12378                 oipha->ipha_version_and_hdr_length =
12379                     IP_SIMPLE_HDR_VERSION;
12380                 oipha->ipha_hdr_checksum = 0;
12381                 oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12382                 outer_mp->b_cont = inner_mp;
12383                 mp = outer_mp;
12384 
12385                 ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12386         }
12387 
12388         /* If we need to wait for a SA then we can't return any errno */
12389         if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12390             (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12391             !ipsec_out_select_sa(mp, ixa))
12392                 return (0);
12393 
12394         /*
12395          * By now, we know what SA's to use.  Toss over to ESP & AH
12396          * to do the heavy lifting.
12397          */
12398         if (ap->ipa_want_esp) {
12399                 ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12400 
12401                 mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12402                 if (mp == NULL) {
12403                         /*
12404                          * Either it failed or is pending. In the former case
12405                          * ipIfStatsInDiscards was increased.
12406                          */
12407                         return (0);
12408                 }
12409         }
12410 
12411         if (ap->ipa_want_ah) {
12412                 ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12413 
12414                 mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12415                 if (mp == NULL) {
12416                         /*
12417                          * Either it failed or is pending. In the former case
12418                          * ipIfStatsInDiscards was increased.
12419                          */
12420                         return (0);
12421                 }
12422         }
12423         /*
12424          * We are done with IPsec processing. Send it over
12425          * the wire.
12426          */
12427         return (ip_output_post_ipsec(mp, ixa));
12428 }
12429 
12430 /*
12431  * ioctls that go through a down/up sequence may need to wait for the down
12432  * to complete. This involves waiting for the ire and ipif refcnts to go down
12433  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12434  */
12435 /* ARGSUSED */
12436 void
12437 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12438 {
12439         struct iocblk *iocp;
12440         mblk_t *mp1;
12441         ip_ioctl_cmd_t *ipip;
12442         int err;
12443         sin_t   *sin;
12444         struct lifreq *lifr;
12445         struct ifreq *ifr;
12446 
12447         iocp = (struct iocblk *)mp->b_rptr;
12448         ASSERT(ipsq != NULL);
12449         /* Existence of mp1 verified in ip_wput_nondata */
12450         mp1 = mp->b_cont->b_cont;
12451         ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12452         if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12453                 /*
12454                  * Special case where ipx_current_ipif is not set:
12455                  * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12456                  * We are here as were not able to complete the operation in
12457                  * ipif_set_values because we could not become exclusive on
12458                  * the new ipsq.
12459                  */
12460                 ill_t *ill = q->q_ptr;
12461                 ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12462         }
12463         ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12464 
12465         if (ipip->ipi_cmd_type == IF_CMD) {
12466                 /* This a old style SIOC[GS]IF* command */
12467                 ifr = (struct ifreq *)mp1->b_rptr;
12468                 sin = (sin_t *)&ifr->ifr_addr;
12469         } else if (ipip->ipi_cmd_type == LIF_CMD) {
12470                 /* This a new style SIOC[GS]LIF* command */
12471                 lifr = (struct lifreq *)mp1->b_rptr;
12472                 sin = (sin_t *)&lifr->lifr_addr;
12473         } else {
12474                 sin = NULL;
12475         }
12476 
12477         err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12478             q, mp, ipip, mp1->b_rptr);
12479 
12480         DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12481             int, ipip->ipi_cmd,
12482             ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12483             ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12484 
12485         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12486 }
12487 
12488 /*
12489  * ioctl processing
12490  *
12491  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12492  * the ioctl command in the ioctl tables, determines the copyin data size
12493  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12494  *
12495  * ioctl processing then continues when the M_IOCDATA makes its way down to
12496  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12497  * associated 'conn' is refheld till the end of the ioctl and the general
12498  * ioctl processing function ip_process_ioctl() is called to extract the
12499  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12500  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12501  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12502  * is used to extract the ioctl's arguments.
12503  *
12504  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12505  * so goes thru the serialization primitive ipsq_try_enter. Then the
12506  * appropriate function to handle the ioctl is called based on the entry in
12507  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12508  * which also refreleases the 'conn' that was refheld at the start of the
12509  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12510  *
12511  * Many exclusive ioctls go thru an internal down up sequence as part of
12512  * the operation. For example an attempt to change the IP address of an
12513  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12514  * does all the cleanup such as deleting all ires that use this address.
12515  * Then we need to wait till all references to the interface go away.
12516  */
12517 void
12518 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12519 {
12520         struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12521         ip_ioctl_cmd_t *ipip = arg;
12522         ip_extract_func_t *extract_funcp;
12523         ill_t *ill;
12524         cmd_info_t ci;
12525         int err;
12526         boolean_t entered_ipsq = B_FALSE;
12527 
12528         ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12529 
12530         if (ipip == NULL)
12531                 ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12532 
12533         /*
12534          * SIOCLIFADDIF needs to go thru a special path since the
12535          * ill may not exist yet. This happens in the case of lo0
12536          * which is created using this ioctl.
12537          */
12538         if (ipip->ipi_cmd == SIOCLIFADDIF) {
12539                 err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12540                 DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12541                     int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12542                 ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12543                 return;
12544         }
12545 
12546         ci.ci_ipif = NULL;
12547         switch (ipip->ipi_cmd_type) {
12548         case MISC_CMD:
12549         case MSFILT_CMD:
12550                 /*
12551                  * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12552                  */
12553                 if (ipip->ipi_cmd == IF_UNITSEL) {
12554                         /* ioctl comes down the ill */
12555                         ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12556                         ipif_refhold(ci.ci_ipif);
12557                 }
12558                 err = 0;
12559                 ci.ci_sin = NULL;
12560                 ci.ci_sin6 = NULL;
12561                 ci.ci_lifr = NULL;
12562                 extract_funcp = NULL;
12563                 break;
12564 
12565         case IF_CMD:
12566         case LIF_CMD:
12567                 extract_funcp = ip_extract_lifreq;
12568                 break;
12569 
12570         case ARP_CMD:
12571         case XARP_CMD:
12572                 extract_funcp = ip_extract_arpreq;
12573                 break;
12574 
12575         default:
12576                 ASSERT(0);
12577         }
12578 
12579         if (extract_funcp != NULL) {
12580                 err = (*extract_funcp)(q, mp, ipip, &ci);
12581                 if (err != 0) {
12582                         DTRACE_PROBE4(ipif__ioctl,
12583                             char *, "ip_process_ioctl finish err",
12584                             int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12585                         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12586                         return;
12587                 }
12588 
12589                 /*
12590                  * All of the extraction functions return a refheld ipif.
12591                  */
12592                 ASSERT(ci.ci_ipif != NULL);
12593         }
12594 
12595         if (!(ipip->ipi_flags & IPI_WR)) {
12596                 /*
12597                  * A return value of EINPROGRESS means the ioctl is
12598                  * either queued and waiting for some reason or has
12599                  * already completed.
12600                  */
12601                 err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12602                     ci.ci_lifr);
12603                 if (ci.ci_ipif != NULL) {
12604                         DTRACE_PROBE4(ipif__ioctl,
12605                             char *, "ip_process_ioctl finish RD",
12606                             int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12607                             ipif_t *, ci.ci_ipif);
12608                         ipif_refrele(ci.ci_ipif);
12609                 } else {
12610                         DTRACE_PROBE4(ipif__ioctl,
12611                             char *, "ip_process_ioctl finish RD",
12612                             int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12613                 }
12614                 ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12615                 return;
12616         }
12617 
12618         ASSERT(ci.ci_ipif != NULL);
12619 
12620         /*
12621          * If ipsq is non-NULL, we are already being called exclusively
12622          */
12623         ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12624         if (ipsq == NULL) {
12625                 ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12626                     NEW_OP, B_TRUE);
12627                 if (ipsq == NULL) {
12628                         ipif_refrele(ci.ci_ipif);
12629                         return;
12630                 }
12631                 entered_ipsq = B_TRUE;
12632         }
12633         /*
12634          * Release the ipif so that ipif_down and friends that wait for
12635          * references to go away are not misled about the current ipif_refcnt
12636          * values. We are writer so we can access the ipif even after releasing
12637          * the ipif.
12638          */
12639         ipif_refrele(ci.ci_ipif);
12640 
12641         ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12642 
12643         /*
12644          * We need to cache the ill_t that we're going to use as the argument
12645          * to the ipif-ioctl DTrace probe (below) because the ci_ipif can be
12646          * blown away by calling ipi_func.
12647          */
12648         ill = ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill;
12649 
12650         /*
12651          * A return value of EINPROGRESS means the ioctl is
12652          * either queued and waiting for some reason or has
12653          * already completed.
12654          */
12655         err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12656 
12657         DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12658             int, ipip->ipi_cmd, ill_t *, ill, ipif_t *, ci.ci_ipif);
12659         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12660 
12661         if (entered_ipsq)
12662                 ipsq_exit(ipsq);
12663 }
12664 
12665 /*
12666  * Complete the ioctl. Typically ioctls use the mi package and need to
12667  * do mi_copyout/mi_copy_done.
12668  */
12669 void
12670 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12671 {
12672         conn_t  *connp = NULL;
12673 
12674         if (err == EINPROGRESS)
12675                 return;
12676 
12677         if (CONN_Q(q)) {
12678                 connp = Q_TO_CONN(q);
12679                 ASSERT(connp->conn_ref >= 2);
12680         }
12681 
12682         switch (mode) {
12683         case COPYOUT:
12684                 if (err == 0)
12685                         mi_copyout(q, mp);
12686                 else
12687                         mi_copy_done(q, mp, err);
12688                 break;
12689 
12690         case NO_COPYOUT:
12691                 mi_copy_done(q, mp, err);
12692                 break;
12693 
12694         default:
12695                 ASSERT(mode == CONN_CLOSE);     /* aborted through CONN_CLOSE */
12696                 break;
12697         }
12698 
12699         /*
12700          * The conn refhold and ioctlref placed on the conn at the start of the
12701          * ioctl are released here.
12702          */
12703         if (connp != NULL) {
12704                 CONN_DEC_IOCTLREF(connp);
12705                 CONN_OPER_PENDING_DONE(connp);
12706         }
12707 
12708         if (ipsq != NULL)
12709                 ipsq_current_finish(ipsq);
12710 }
12711 
12712 /* Handles all non data messages */
12713 int
12714 ip_wput_nondata(queue_t *q, mblk_t *mp)
12715 {
12716         mblk_t          *mp1;
12717         struct iocblk   *iocp;
12718         ip_ioctl_cmd_t  *ipip;
12719         conn_t          *connp;
12720         cred_t          *cr;
12721         char            *proto_str;
12722 
12723         if (CONN_Q(q))
12724                 connp = Q_TO_CONN(q);
12725         else
12726                 connp = NULL;
12727 
12728         switch (DB_TYPE(mp)) {
12729         case M_IOCTL:
12730                 /*
12731                  * IOCTL processing begins in ip_sioctl_copyin_setup which
12732                  * will arrange to copy in associated control structures.
12733                  */
12734                 ip_sioctl_copyin_setup(q, mp);
12735                 return (0);
12736         case M_IOCDATA:
12737                 /*
12738                  * Ensure that this is associated with one of our trans-
12739                  * parent ioctls.  If it's not ours, discard it if we're
12740                  * running as a driver, or pass it on if we're a module.
12741                  */
12742                 iocp = (struct iocblk *)mp->b_rptr;
12743                 ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12744                 if (ipip == NULL) {
12745                         if (q->q_next == NULL) {
12746                                 goto nak;
12747                         } else {
12748                                 putnext(q, mp);
12749                         }
12750                         return (0);
12751                 }
12752                 if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12753                         /*
12754                          * The ioctl is one we recognise, but is not consumed
12755                          * by IP as a module and we are a module, so we drop
12756                          */
12757                         goto nak;
12758                 }
12759 
12760                 /* IOCTL continuation following copyin or copyout. */
12761                 if (mi_copy_state(q, mp, NULL) == -1) {
12762                         /*
12763                          * The copy operation failed.  mi_copy_state already
12764                          * cleaned up, so we're out of here.
12765                          */
12766                         return (0);
12767                 }
12768                 /*
12769                  * If we just completed a copy in, we become writer and
12770                  * continue processing in ip_sioctl_copyin_done.  If it
12771                  * was a copy out, we call mi_copyout again.  If there is
12772                  * nothing more to copy out, it will complete the IOCTL.
12773                  */
12774                 if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12775                         if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12776                                 mi_copy_done(q, mp, EPROTO);
12777                                 return (0);
12778                         }
12779                         /*
12780                          * Check for cases that need more copying.  A return
12781                          * value of 0 means a second copyin has been started,
12782                          * so we return; a return value of 1 means no more
12783                          * copying is needed, so we continue.
12784                          */
12785                         if (ipip->ipi_cmd_type == MSFILT_CMD &&
12786                             MI_COPY_COUNT(mp) == 1) {
12787                                 if (ip_copyin_msfilter(q, mp) == 0)
12788                                         return (0);
12789                         }
12790                         /*
12791                          * Refhold the conn, till the ioctl completes. This is
12792                          * needed in case the ioctl ends up in the pending mp
12793                          * list. Every mp in the ipx_pending_mp list must have
12794                          * a refhold on the conn to resume processing. The
12795                          * refhold is released when the ioctl completes
12796                          * (whether normally or abnormally). An ioctlref is also
12797                          * placed on the conn to prevent TCP from removing the
12798                          * queue needed to send the ioctl reply back.
12799                          * In all cases ip_ioctl_finish is called to finish
12800                          * the ioctl and release the refholds.
12801                          */
12802                         if (connp != NULL) {
12803                                 /* This is not a reentry */
12804                                 CONN_INC_REF(connp);
12805                                 CONN_INC_IOCTLREF(connp);
12806                         } else {
12807                                 if (!(ipip->ipi_flags & IPI_MODOK)) {
12808                                         mi_copy_done(q, mp, EINVAL);
12809                                         return (0);
12810                                 }
12811                         }
12812 
12813                         ip_process_ioctl(NULL, q, mp, ipip);
12814 
12815                 } else {
12816                         mi_copyout(q, mp);
12817                 }
12818                 return (0);
12819 
12820         case M_IOCNAK:
12821                 /*
12822                  * The only way we could get here is if a resolver didn't like
12823                  * an IOCTL we sent it.  This shouldn't happen.
12824                  */
12825                 (void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12826                     "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12827                     ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12828                 freemsg(mp);
12829                 return (0);
12830         case M_IOCACK:
12831                 /* /dev/ip shouldn't see this */
12832                 goto nak;
12833         case M_FLUSH:
12834                 if (*mp->b_rptr & FLUSHW)
12835                         flushq(q, FLUSHALL);
12836                 if (q->q_next) {
12837                         putnext(q, mp);
12838                         return (0);
12839                 }
12840                 if (*mp->b_rptr & FLUSHR) {
12841                         *mp->b_rptr &= ~FLUSHW;
12842                         qreply(q, mp);
12843                         return (0);
12844                 }
12845                 freemsg(mp);
12846                 return (0);
12847         case M_CTL:
12848                 break;
12849         case M_PROTO:
12850         case M_PCPROTO:
12851                 /*
12852                  * The only PROTO messages we expect are SNMP-related.
12853                  */
12854                 switch (((union T_primitives *)mp->b_rptr)->type) {
12855                 case T_SVR4_OPTMGMT_REQ:
12856                         ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12857                             "flags %x\n",
12858                             ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12859 
12860                         if (connp == NULL) {
12861                                 proto_str = "T_SVR4_OPTMGMT_REQ";
12862                                 goto protonak;
12863                         }
12864 
12865                         /*
12866                          * All Solaris components should pass a db_credp
12867                          * for this TPI message, hence we ASSERT.
12868                          * But in case there is some other M_PROTO that looks
12869                          * like a TPI message sent by some other kernel
12870                          * component, we check and return an error.
12871                          */
12872                         cr = msg_getcred(mp, NULL);
12873                         ASSERT(cr != NULL);
12874                         if (cr == NULL) {
12875                                 mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12876                                 if (mp != NULL)
12877                                         qreply(q, mp);
12878                                 return (0);
12879                         }
12880 
12881                         if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12882                                 proto_str = "Bad SNMPCOM request?";
12883                                 goto protonak;
12884                         }
12885                         return (0);
12886                 default:
12887                         ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12888                             (int)*(uint_t *)mp->b_rptr));
12889                         freemsg(mp);
12890                         return (0);
12891                 }
12892         default:
12893                 break;
12894         }
12895         if (q->q_next) {
12896                 putnext(q, mp);
12897         } else
12898                 freemsg(mp);
12899         return (0);
12900 
12901 nak:
12902         iocp->ioc_error = EINVAL;
12903         mp->b_datap->db_type = M_IOCNAK;
12904         iocp->ioc_count = 0;
12905         qreply(q, mp);
12906         return (0);
12907 
12908 protonak:
12909         cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12910         if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12911                 qreply(q, mp);
12912         return (0);
12913 }
12914 
12915 /*
12916  * Process IP options in an outbound packet.  Verify that the nexthop in a
12917  * strict source route is onlink.
12918  * Returns non-zero if something fails in which case an ICMP error has been
12919  * sent and mp freed.
12920  *
12921  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12922  */
12923 int
12924 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12925 {
12926         ipoptp_t        opts;
12927         uchar_t         *opt;
12928         uint8_t         optval;
12929         uint8_t         optlen;
12930         ipaddr_t        dst;
12931         intptr_t        code = 0;
12932         ire_t           *ire;
12933         ip_stack_t      *ipst = ixa->ixa_ipst;
12934         ip_recv_attr_t  iras;
12935 
12936         ip2dbg(("ip_output_options\n"));
12937 
12938         dst = ipha->ipha_dst;
12939         for (optval = ipoptp_first(&opts, ipha);
12940             optval != IPOPT_EOL;
12941             optval = ipoptp_next(&opts)) {
12942                 opt = opts.ipoptp_cur;
12943                 optlen = opts.ipoptp_len;
12944                 ip2dbg(("ip_output_options: opt %d, len %d\n",
12945                     optval, optlen));
12946                 switch (optval) {
12947                         uint32_t off;
12948                 case IPOPT_SSRR:
12949                 case IPOPT_LSRR:
12950                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12951                                 ip1dbg((
12952                                     "ip_output_options: bad option offset\n"));
12953                                 code = (char *)&opt[IPOPT_OLEN] -
12954                                     (char *)ipha;
12955                                 goto param_prob;
12956                         }
12957                         off = opt[IPOPT_OFFSET];
12958                         ip1dbg(("ip_output_options: next hop 0x%x\n",
12959                             ntohl(dst)));
12960                         /*
12961                          * For strict: verify that dst is directly
12962                          * reachable.
12963                          */
12964                         if (optval == IPOPT_SSRR) {
12965                                 ire = ire_ftable_lookup_v4(dst, 0, 0,
12966                                     IRE_INTERFACE, NULL, ALL_ZONES,
12967                                     ixa->ixa_tsl,
12968                                     MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12969                                     NULL);
12970                                 if (ire == NULL) {
12971                                         ip1dbg(("ip_output_options: SSRR not"
12972                                             " directly reachable: 0x%x\n",
12973                                             ntohl(dst)));
12974                                         goto bad_src_route;
12975                                 }
12976                                 ire_refrele(ire);
12977                         }
12978                         break;
12979                 case IPOPT_RR:
12980                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12981                                 ip1dbg((
12982                                     "ip_output_options: bad option offset\n"));
12983                                 code = (char *)&opt[IPOPT_OLEN] -
12984                                     (char *)ipha;
12985                                 goto param_prob;
12986                         }
12987                         break;
12988                 case IPOPT_TS:
12989                         /*
12990                          * Verify that length >=5 and that there is either
12991                          * room for another timestamp or that the overflow
12992                          * counter is not maxed out.
12993                          */
12994                         code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
12995                         if (optlen < IPOPT_MINLEN_IT) {
12996                                 goto param_prob;
12997                         }
12998                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12999                                 ip1dbg((
13000                                     "ip_output_options: bad option offset\n"));
13001                                 code = (char *)&opt[IPOPT_OFFSET] -
13002                                     (char *)ipha;
13003                                 goto param_prob;
13004                         }
13005                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13006                         case IPOPT_TS_TSONLY:
13007                                 off = IPOPT_TS_TIMELEN;
13008                                 break;
13009                         case IPOPT_TS_TSANDADDR:
13010                         case IPOPT_TS_PRESPEC:
13011                         case IPOPT_TS_PRESPEC_RFC791:
13012                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13013                                 break;
13014                         default:
13015                                 code = (char *)&opt[IPOPT_POS_OV_FLG] -
13016                                     (char *)ipha;
13017                                 goto param_prob;
13018                         }
13019                         if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13020                             (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13021                                 /*
13022                                  * No room and the overflow counter is 15
13023                                  * already.
13024                                  */
13025                                 goto param_prob;
13026                         }
13027                         break;
13028                 }
13029         }
13030 
13031         if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13032                 return (0);
13033 
13034         ip1dbg(("ip_output_options: error processing IP options."));
13035         code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13036 
13037 param_prob:
13038         bzero(&iras, sizeof (iras));
13039         iras.ira_ill = iras.ira_rill = ill;
13040         iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13041         iras.ira_rifindex = iras.ira_ruifindex;
13042         iras.ira_flags = IRAF_IS_IPV4;
13043 
13044         ip_drop_output("ip_output_options", mp, ill);
13045         icmp_param_problem(mp, (uint8_t)code, &iras);
13046         ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13047         return (-1);
13048 
13049 bad_src_route:
13050         bzero(&iras, sizeof (iras));
13051         iras.ira_ill = iras.ira_rill = ill;
13052         iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13053         iras.ira_rifindex = iras.ira_ruifindex;
13054         iras.ira_flags = IRAF_IS_IPV4;
13055 
13056         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13057         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13058         ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13059         return (-1);
13060 }
13061 
13062 /*
13063  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13064  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13065  * thru /etc/system.
13066  */
13067 #define CONN_MAXDRAINCNT        64
13068 
13069 static void
13070 conn_drain_init(ip_stack_t *ipst)
13071 {
13072         int i, j;
13073         idl_tx_list_t *itl_tx;
13074 
13075         ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13076 
13077         if ((ipst->ips_conn_drain_list_cnt == 0) ||
13078             (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13079                 /*
13080                  * Default value of the number of drainers is the
13081                  * number of cpus, subject to maximum of 8 drainers.
13082                  */
13083                 if (boot_max_ncpus != -1)
13084                         ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13085                 else
13086                         ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13087         }
13088 
13089         ipst->ips_idl_tx_list =
13090             kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13091         for (i = 0; i < TX_FANOUT_SIZE; i++) {
13092                 itl_tx =  &ipst->ips_idl_tx_list[i];
13093                 itl_tx->txl_drain_list =
13094                     kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13095                     sizeof (idl_t), KM_SLEEP);
13096                 mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13097                 for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13098                         mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13099                             MUTEX_DEFAULT, NULL);
13100                         itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13101                 }
13102         }
13103 }
13104 
13105 static void
13106 conn_drain_fini(ip_stack_t *ipst)
13107 {
13108         int i;
13109         idl_tx_list_t *itl_tx;
13110 
13111         for (i = 0; i < TX_FANOUT_SIZE; i++) {
13112                 itl_tx =  &ipst->ips_idl_tx_list[i];
13113                 kmem_free(itl_tx->txl_drain_list,
13114                     ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13115         }
13116         kmem_free(ipst->ips_idl_tx_list,
13117             TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13118         ipst->ips_idl_tx_list = NULL;
13119 }
13120 
13121 /*
13122  * Flow control has blocked us from proceeding.  Insert the given conn in one
13123  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13124  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13125  * will call conn_walk_drain().  See the flow control notes at the top of this
13126  * file for more details.
13127  */
13128 void
13129 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13130 {
13131         idl_t   *idl = tx_list->txl_drain_list;
13132         uint_t  index;
13133         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
13134 
13135         mutex_enter(&connp->conn_lock);
13136         if (connp->conn_state_flags & CONN_CLOSING) {
13137                 /*
13138                  * The conn is closing as a result of which CONN_CLOSING
13139                  * is set. Return.
13140                  */
13141                 mutex_exit(&connp->conn_lock);
13142                 return;
13143         } else if (connp->conn_idl == NULL) {
13144                 /*
13145                  * Assign the next drain list round robin. We dont' use
13146                  * a lock, and thus it may not be strictly round robin.
13147                  * Atomicity of load/stores is enough to make sure that
13148                  * conn_drain_list_index is always within bounds.
13149                  */
13150                 index = tx_list->txl_drain_index;
13151                 ASSERT(index < ipst->ips_conn_drain_list_cnt);
13152                 connp->conn_idl = &tx_list->txl_drain_list[index];
13153                 index++;
13154                 if (index == ipst->ips_conn_drain_list_cnt)
13155                         index = 0;
13156                 tx_list->txl_drain_index = index;
13157         } else {
13158                 ASSERT(connp->conn_idl->idl_itl == tx_list);
13159         }
13160         mutex_exit(&connp->conn_lock);
13161 
13162         idl = connp->conn_idl;
13163         mutex_enter(&idl->idl_lock);
13164         if ((connp->conn_drain_prev != NULL) ||
13165             (connp->conn_state_flags & CONN_CLOSING)) {
13166                 /*
13167                  * The conn is either already in the drain list or closing.
13168                  * (We needed to check for CONN_CLOSING again since close can
13169                  * sneak in between dropping conn_lock and acquiring idl_lock.)
13170                  */
13171                 mutex_exit(&idl->idl_lock);
13172                 return;
13173         }
13174 
13175         /*
13176          * The conn is not in the drain list. Insert it at the
13177          * tail of the drain list. The drain list is circular
13178          * and doubly linked. idl_conn points to the 1st element
13179          * in the list.
13180          */
13181         if (idl->idl_conn == NULL) {
13182                 idl->idl_conn = connp;
13183                 connp->conn_drain_next = connp;
13184                 connp->conn_drain_prev = connp;
13185         } else {
13186                 conn_t *head = idl->idl_conn;
13187 
13188                 connp->conn_drain_next = head;
13189                 connp->conn_drain_prev = head->conn_drain_prev;
13190                 head->conn_drain_prev->conn_drain_next = connp;
13191                 head->conn_drain_prev = connp;
13192         }
13193         /*
13194          * For non streams based sockets assert flow control.
13195          */
13196         conn_setqfull(connp, NULL);
13197         mutex_exit(&idl->idl_lock);
13198 }
13199 
13200 static void
13201 conn_drain_remove(conn_t *connp)
13202 {
13203         idl_t *idl = connp->conn_idl;
13204 
13205         if (idl != NULL) {
13206                 /*
13207                  * Remove ourself from the drain list.
13208                  */
13209                 if (connp->conn_drain_next == connp) {
13210                         /* Singleton in the list */
13211                         ASSERT(connp->conn_drain_prev == connp);
13212                         idl->idl_conn = NULL;
13213                 } else {
13214                         connp->conn_drain_prev->conn_drain_next =
13215                             connp->conn_drain_next;
13216                         connp->conn_drain_next->conn_drain_prev =
13217                             connp->conn_drain_prev;
13218                         if (idl->idl_conn == connp)
13219                                 idl->idl_conn = connp->conn_drain_next;
13220                 }
13221 
13222                 /*
13223                  * NOTE: because conn_idl is associated with a specific drain
13224                  * list which in turn is tied to the index the TX ring
13225                  * (txl_cookie) hashes to, and because the TX ring can change
13226                  * over the lifetime of the conn_t, we must clear conn_idl so
13227                  * a subsequent conn_drain_insert() will set conn_idl again
13228                  * based on the latest txl_cookie.
13229                  */
13230                 connp->conn_idl = NULL;
13231         }
13232         connp->conn_drain_next = NULL;
13233         connp->conn_drain_prev = NULL;
13234 
13235         conn_clrqfull(connp, NULL);
13236         /*
13237          * For streams based sockets open up flow control.
13238          */
13239         if (!IPCL_IS_NONSTR(connp))
13240                 enableok(connp->conn_wq);
13241 }
13242 
13243 /*
13244  * This conn is closing, and we are called from ip_close. OR
13245  * this conn is draining because flow-control on the ill has been relieved.
13246  *
13247  * We must also need to remove conn's on this idl from the list, and also
13248  * inform the sockfs upcalls about the change in flow-control.
13249  */
13250 static void
13251 conn_drain(conn_t *connp, boolean_t closing)
13252 {
13253         idl_t *idl;
13254         conn_t *next_connp;
13255 
13256         /*
13257          * connp->conn_idl is stable at this point, and no lock is needed
13258          * to check it. If we are called from ip_close, close has already
13259          * set CONN_CLOSING, thus freezing the value of conn_idl, and
13260          * called us only because conn_idl is non-null. If we are called thru
13261          * service, conn_idl could be null, but it cannot change because
13262          * service is single-threaded per queue, and there cannot be another
13263          * instance of service trying to call conn_drain_insert on this conn
13264          * now.
13265          */
13266         ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13267 
13268         /*
13269          * If the conn doesn't exist or is not on a drain list, bail.
13270          */
13271         if (connp == NULL || connp->conn_idl == NULL ||
13272             connp->conn_drain_prev == NULL) {
13273                 return;
13274         }
13275 
13276         idl = connp->conn_idl;
13277         ASSERT(MUTEX_HELD(&idl->idl_lock));
13278 
13279         if (!closing) {
13280                 next_connp = connp->conn_drain_next;
13281                 while (next_connp != connp) {
13282                         conn_t *delconnp = next_connp;
13283 
13284                         next_connp = next_connp->conn_drain_next;
13285                         conn_drain_remove(delconnp);
13286                 }
13287                 ASSERT(connp->conn_drain_next == idl->idl_conn);
13288         }
13289         conn_drain_remove(connp);
13290 }
13291 
13292 /*
13293  * Write service routine. Shared perimeter entry point.
13294  * The device queue's messages has fallen below the low water mark and STREAMS
13295  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13296  * each waiting conn.
13297  */
13298 int
13299 ip_wsrv(queue_t *q)
13300 {
13301         ill_t   *ill;
13302 
13303         ill = (ill_t *)q->q_ptr;
13304         if (ill->ill_state_flags == 0) {
13305                 ip_stack_t *ipst = ill->ill_ipst;
13306 
13307                 /*
13308                  * The device flow control has opened up.
13309                  * Walk through conn drain lists and qenable the
13310                  * first conn in each list. This makes sense only
13311                  * if the stream is fully plumbed and setup.
13312                  * Hence the ill_state_flags check above.
13313                  */
13314                 ip1dbg(("ip_wsrv: walking\n"));
13315                 conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13316                 enableok(ill->ill_wq);
13317         }
13318         return (0);
13319 }
13320 
13321 /*
13322  * Callback to disable flow control in IP.
13323  *
13324  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13325  * is enabled.
13326  *
13327  * When MAC_TX() is not able to send any more packets, dld sets its queue
13328  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13329  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13330  * function and wakes up corresponding mac worker threads, which in turn
13331  * calls this callback function, and disables flow control.
13332  */
13333 void
13334 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13335 {
13336         ill_t *ill = (ill_t *)arg;
13337         ip_stack_t *ipst = ill->ill_ipst;
13338         idl_tx_list_t *idl_txl;
13339 
13340         idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13341         mutex_enter(&idl_txl->txl_lock);
13342         /* add code to to set a flag to indicate idl_txl is enabled */
13343         conn_walk_drain(ipst, idl_txl);
13344         mutex_exit(&idl_txl->txl_lock);
13345 }
13346 
13347 /*
13348  * Flow control has been relieved and STREAMS has backenabled us; drain
13349  * all the conn lists on `tx_list'.
13350  */
13351 static void
13352 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13353 {
13354         int i;
13355         idl_t *idl;
13356 
13357         IP_STAT(ipst, ip_conn_walk_drain);
13358 
13359         for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13360                 idl = &tx_list->txl_drain_list[i];
13361                 mutex_enter(&idl->idl_lock);
13362                 conn_drain(idl->idl_conn, B_FALSE);
13363                 mutex_exit(&idl->idl_lock);
13364         }
13365 }
13366 
13367 /*
13368  * Determine if the ill and multicast aspects of that packets
13369  * "matches" the conn.
13370  */
13371 boolean_t
13372 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13373 {
13374         ill_t           *ill = ira->ira_rill;
13375         zoneid_t        zoneid = ira->ira_zoneid;
13376         uint_t          in_ifindex;
13377         ipaddr_t        dst, src;
13378 
13379         dst = ipha->ipha_dst;
13380         src = ipha->ipha_src;
13381 
13382         /*
13383          * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13384          * unicast, broadcast and multicast reception to
13385          * conn_incoming_ifindex.
13386          * conn_wantpacket is called for unicast, broadcast and
13387          * multicast packets.
13388          */
13389         in_ifindex = connp->conn_incoming_ifindex;
13390 
13391         /* mpathd can bind to the under IPMP interface, which we allow */
13392         if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13393                 if (!IS_UNDER_IPMP(ill))
13394                         return (B_FALSE);
13395 
13396                 if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13397                         return (B_FALSE);
13398         }
13399 
13400         if (!IPCL_ZONE_MATCH(connp, zoneid))
13401                 return (B_FALSE);
13402 
13403         if (!(ira->ira_flags & IRAF_MULTICAST))
13404                 return (B_TRUE);
13405 
13406         if (connp->conn_multi_router) {
13407                 /* multicast packet and multicast router socket: send up */
13408                 return (B_TRUE);
13409         }
13410 
13411         if (ipha->ipha_protocol == IPPROTO_PIM ||
13412             ipha->ipha_protocol == IPPROTO_RSVP)
13413                 return (B_TRUE);
13414 
13415         return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13416 }
13417 
13418 void
13419 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13420 {
13421         if (IPCL_IS_NONSTR(connp)) {
13422                 (*connp->conn_upcalls->su_txq_full)
13423                     (connp->conn_upper_handle, B_TRUE);
13424                 if (flow_stopped != NULL)
13425                         *flow_stopped = B_TRUE;
13426         } else {
13427                 queue_t *q = connp->conn_wq;
13428 
13429                 ASSERT(q != NULL);
13430                 if (!(q->q_flag & QFULL)) {
13431                         mutex_enter(QLOCK(q));
13432                         if (!(q->q_flag & QFULL)) {
13433                                 /* still need to set QFULL */
13434                                 q->q_flag |= QFULL;
13435                                 /* set flow_stopped to true under QLOCK */
13436                                 if (flow_stopped != NULL)
13437                                         *flow_stopped = B_TRUE;
13438                                 mutex_exit(QLOCK(q));
13439                         } else {
13440                                 /* flow_stopped is left unchanged */
13441                                 mutex_exit(QLOCK(q));
13442                         }
13443                 }
13444         }
13445 }
13446 
13447 void
13448 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13449 {
13450         if (IPCL_IS_NONSTR(connp)) {
13451                 (*connp->conn_upcalls->su_txq_full)
13452                     (connp->conn_upper_handle, B_FALSE);
13453                 if (flow_stopped != NULL)
13454                         *flow_stopped = B_FALSE;
13455         } else {
13456                 queue_t *q = connp->conn_wq;
13457 
13458                 ASSERT(q != NULL);
13459                 if (q->q_flag & QFULL) {
13460                         mutex_enter(QLOCK(q));
13461                         if (q->q_flag & QFULL) {
13462                                 q->q_flag &= ~QFULL;
13463                                 /* set flow_stopped to false under QLOCK */
13464                                 if (flow_stopped != NULL)
13465                                         *flow_stopped = B_FALSE;
13466                                 mutex_exit(QLOCK(q));
13467                                 if (q->q_flag & QWANTW)
13468                                         qbackenable(q, 0);
13469                         } else {
13470                                 /* flow_stopped is left unchanged */
13471                                 mutex_exit(QLOCK(q));
13472                         }
13473                 }
13474         }
13475 
13476         mutex_enter(&connp->conn_lock);
13477         connp->conn_blocked = B_FALSE;
13478         mutex_exit(&connp->conn_lock);
13479 }
13480 
13481 /*
13482  * Return the length in bytes of the IPv4 headers (base header, label, and
13483  * other IP options) that will be needed based on the
13484  * ip_pkt_t structure passed by the caller.
13485  *
13486  * The returned length does not include the length of the upper level
13487  * protocol (ULP) header.
13488  * The caller needs to check that the length doesn't exceed the max for IPv4.
13489  */
13490 int
13491 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13492 {
13493         int len;
13494 
13495         len = IP_SIMPLE_HDR_LENGTH;
13496         if (ipp->ipp_fields & IPPF_LABEL_V4) {
13497                 ASSERT(ipp->ipp_label_len_v4 != 0);
13498                 /* We need to round up here */
13499                 len += (ipp->ipp_label_len_v4 + 3) & ~3;
13500         }
13501 
13502         if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13503                 ASSERT(ipp->ipp_ipv4_options_len != 0);
13504                 ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13505                 len += ipp->ipp_ipv4_options_len;
13506         }
13507         return (len);
13508 }
13509 
13510 /*
13511  * All-purpose routine to build an IPv4 header with options based
13512  * on the abstract ip_pkt_t.
13513  *
13514  * The caller has to set the source and destination address as well as
13515  * ipha_length. The caller has to massage any source route and compensate
13516  * for the ULP pseudo-header checksum due to the source route.
13517  */
13518 void
13519 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13520     uint8_t protocol)
13521 {
13522         ipha_t  *ipha = (ipha_t *)buf;
13523         uint8_t *cp;
13524 
13525         /* Initialize IPv4 header */
13526         ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13527         ipha->ipha_length = 0;       /* Caller will set later */
13528         ipha->ipha_ident = 0;
13529         ipha->ipha_fragment_offset_and_flags = 0;
13530         ipha->ipha_ttl = ipp->ipp_unicast_hops;
13531         ipha->ipha_protocol = protocol;
13532         ipha->ipha_hdr_checksum = 0;
13533 
13534         if ((ipp->ipp_fields & IPPF_ADDR) &&
13535             IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13536                 ipha->ipha_src = ipp->ipp_addr_v4;
13537 
13538         cp = (uint8_t *)&ipha[1];
13539         if (ipp->ipp_fields & IPPF_LABEL_V4) {
13540                 ASSERT(ipp->ipp_label_len_v4 != 0);
13541                 bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13542                 cp += ipp->ipp_label_len_v4;
13543                 /* We need to round up here */
13544                 while ((uintptr_t)cp & 0x3) {
13545                         *cp++ = IPOPT_NOP;
13546                 }
13547         }
13548 
13549         if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13550                 ASSERT(ipp->ipp_ipv4_options_len != 0);
13551                 ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13552                 bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13553                 cp += ipp->ipp_ipv4_options_len;
13554         }
13555         ipha->ipha_version_and_hdr_length =
13556             (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13557 
13558         ASSERT((int)(cp - buf) == buf_len);
13559 }
13560 
13561 /* Allocate the private structure */
13562 static int
13563 ip_priv_alloc(void **bufp)
13564 {
13565         void    *buf;
13566 
13567         if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13568                 return (ENOMEM);
13569 
13570         *bufp = buf;
13571         return (0);
13572 }
13573 
13574 /* Function to delete the private structure */
13575 void
13576 ip_priv_free(void *buf)
13577 {
13578         ASSERT(buf != NULL);
13579         kmem_free(buf, sizeof (ip_priv_t));
13580 }
13581 
13582 /*
13583  * The entry point for IPPF processing.
13584  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13585  * routine just returns.
13586  *
13587  * When called, ip_process generates an ipp_packet_t structure
13588  * which holds the state information for this packet and invokes the
13589  * the classifier (via ipp_packet_process). The classification, depending on
13590  * configured filters, results in a list of actions for this packet. Invoking
13591  * an action may cause the packet to be dropped, in which case we return NULL.
13592  * proc indicates the callout position for
13593  * this packet and ill is the interface this packet arrived on or will leave
13594  * on (inbound and outbound resp.).
13595  *
13596  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13597  * on the ill corrsponding to the destination IP address.
13598  */
13599 mblk_t *
13600 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13601 {
13602         ip_priv_t       *priv;
13603         ipp_action_id_t aid;
13604         int             rc = 0;
13605         ipp_packet_t    *pp;
13606 
13607         /* If the classifier is not loaded, return  */
13608         if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13609                 return (mp);
13610         }
13611 
13612         ASSERT(mp != NULL);
13613 
13614         /* Allocate the packet structure */
13615         rc = ipp_packet_alloc(&pp, "ip", aid);
13616         if (rc != 0)
13617                 goto drop;
13618 
13619         /* Allocate the private structure */
13620         rc = ip_priv_alloc((void **)&priv);
13621         if (rc != 0) {
13622                 ipp_packet_free(pp);
13623                 goto drop;
13624         }
13625         priv->proc = proc;
13626         priv->ill_index = ill_get_upper_ifindex(rill);
13627 
13628         ipp_packet_set_private(pp, priv, ip_priv_free);
13629         ipp_packet_set_data(pp, mp);
13630 
13631         /* Invoke the classifier */
13632         rc = ipp_packet_process(&pp);
13633         if (pp != NULL) {
13634                 mp = ipp_packet_get_data(pp);
13635                 ipp_packet_free(pp);
13636                 if (rc != 0)
13637                         goto drop;
13638                 return (mp);
13639         } else {
13640                 /* No mp to trace in ip_drop_input/ip_drop_output  */
13641                 mp = NULL;
13642         }
13643 drop:
13644         if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13645                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13646                 ip_drop_input("ip_process", mp, ill);
13647         } else {
13648                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13649                 ip_drop_output("ip_process", mp, ill);
13650         }
13651         freemsg(mp);
13652         return (NULL);
13653 }
13654 
13655 /*
13656  * Propagate a multicast group membership operation (add/drop) on
13657  * all the interfaces crossed by the related multirt routes.
13658  * The call is considered successful if the operation succeeds
13659  * on at least one interface.
13660  *
13661  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13662  * multicast addresses with the ire argument being the first one.
13663  * We walk the bucket to find all the of those.
13664  *
13665  * Common to IPv4 and IPv6.
13666  */
13667 static int
13668 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13669     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13670     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13671     mcast_record_t fmode, const in6_addr_t *v6src)
13672 {
13673         ire_t           *ire_gw;
13674         irb_t           *irb;
13675         int             ifindex;
13676         int             error = 0;
13677         int             result;
13678         ip_stack_t      *ipst = ire->ire_ipst;
13679         ipaddr_t        group;
13680         boolean_t       isv6;
13681         int             match_flags;
13682 
13683         if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13684                 IN6_V4MAPPED_TO_IPADDR(v6group, group);
13685                 isv6 = B_FALSE;
13686         } else {
13687                 isv6 = B_TRUE;
13688         }
13689 
13690         irb = ire->ire_bucket;
13691         ASSERT(irb != NULL);
13692 
13693         result = 0;
13694         irb_refhold(irb);
13695         for (; ire != NULL; ire = ire->ire_next) {
13696                 if ((ire->ire_flags & RTF_MULTIRT) == 0)
13697                         continue;
13698 
13699                 /* We handle -ifp routes by matching on the ill if set */
13700                 match_flags = MATCH_IRE_TYPE;
13701                 if (ire->ire_ill != NULL)
13702                         match_flags |= MATCH_IRE_ILL;
13703 
13704                 if (isv6) {
13705                         if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13706                                 continue;
13707 
13708                         ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13709                             0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13710                             match_flags, 0, ipst, NULL);
13711                 } else {
13712                         if (ire->ire_addr != group)
13713                                 continue;
13714 
13715                         ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13716                             0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13717                             match_flags, 0, ipst, NULL);
13718                 }
13719                 /* No interface route exists for the gateway; skip this ire. */
13720                 if (ire_gw == NULL)
13721                         continue;
13722                 if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13723                         ire_refrele(ire_gw);
13724                         continue;
13725                 }
13726                 ASSERT(ire_gw->ire_ill != NULL);     /* IRE_INTERFACE */
13727                 ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13728 
13729                 /*
13730                  * The operation is considered a success if
13731                  * it succeeds at least once on any one interface.
13732                  */
13733                 error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13734                     fmode, v6src);
13735                 if (error == 0)
13736                         result = CGTP_MCAST_SUCCESS;
13737 
13738                 ire_refrele(ire_gw);
13739         }
13740         irb_refrele(irb);
13741         /*
13742          * Consider the call as successful if we succeeded on at least
13743          * one interface. Otherwise, return the last encountered error.
13744          */
13745         return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13746 }
13747 
13748 /*
13749  * Return the expected CGTP hooks version number.
13750  */
13751 int
13752 ip_cgtp_filter_supported(void)
13753 {
13754         return (ip_cgtp_filter_rev);
13755 }
13756 
13757 /*
13758  * CGTP hooks can be registered by invoking this function.
13759  * Checks that the version number matches.
13760  */
13761 int
13762 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13763 {
13764         netstack_t *ns;
13765         ip_stack_t *ipst;
13766 
13767         if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13768                 return (ENOTSUP);
13769 
13770         ns = netstack_find_by_stackid(stackid);
13771         if (ns == NULL)
13772                 return (EINVAL);
13773         ipst = ns->netstack_ip;
13774         ASSERT(ipst != NULL);
13775 
13776         if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13777                 netstack_rele(ns);
13778                 return (EALREADY);
13779         }
13780 
13781         ipst->ips_ip_cgtp_filter_ops = ops;
13782 
13783         ill_set_inputfn_all(ipst);
13784 
13785         netstack_rele(ns);
13786         return (0);
13787 }
13788 
13789 /*
13790  * CGTP hooks can be unregistered by invoking this function.
13791  * Returns ENXIO if there was no registration.
13792  * Returns EBUSY if the ndd variable has not been turned off.
13793  */
13794 int
13795 ip_cgtp_filter_unregister(netstackid_t stackid)
13796 {
13797         netstack_t *ns;
13798         ip_stack_t *ipst;
13799 
13800         ns = netstack_find_by_stackid(stackid);
13801         if (ns == NULL)
13802                 return (EINVAL);
13803         ipst = ns->netstack_ip;
13804         ASSERT(ipst != NULL);
13805 
13806         if (ipst->ips_ip_cgtp_filter) {
13807                 netstack_rele(ns);
13808                 return (EBUSY);
13809         }
13810 
13811         if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13812                 netstack_rele(ns);
13813                 return (ENXIO);
13814         }
13815         ipst->ips_ip_cgtp_filter_ops = NULL;
13816 
13817         ill_set_inputfn_all(ipst);
13818 
13819         netstack_rele(ns);
13820         return (0);
13821 }
13822 
13823 /*
13824  * Check whether there is a CGTP filter registration.
13825  * Returns non-zero if there is a registration, otherwise returns zero.
13826  * Note: returns zero if bad stackid.
13827  */
13828 int
13829 ip_cgtp_filter_is_registered(netstackid_t stackid)
13830 {
13831         netstack_t *ns;
13832         ip_stack_t *ipst;
13833         int ret;
13834 
13835         ns = netstack_find_by_stackid(stackid);
13836         if (ns == NULL)
13837                 return (0);
13838         ipst = ns->netstack_ip;
13839         ASSERT(ipst != NULL);
13840 
13841         if (ipst->ips_ip_cgtp_filter_ops != NULL)
13842                 ret = 1;
13843         else
13844                 ret = 0;
13845 
13846         netstack_rele(ns);
13847         return (ret);
13848 }
13849 
13850 static int
13851 ip_squeue_switch(int val)
13852 {
13853         int rval;
13854 
13855         switch (val) {
13856         case IP_SQUEUE_ENTER_NODRAIN:
13857                 rval = SQ_NODRAIN;
13858                 break;
13859         case IP_SQUEUE_ENTER:
13860                 rval = SQ_PROCESS;
13861                 break;
13862         case IP_SQUEUE_FILL:
13863         default:
13864                 rval = SQ_FILL;
13865                 break;
13866         }
13867         return (rval);
13868 }
13869 
13870 static void *
13871 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13872 {
13873         kstat_t *ksp;
13874 
13875         ip_stat_t template = {
13876                 { "ip_udp_fannorm",             KSTAT_DATA_UINT64 },
13877                 { "ip_udp_fanmb",               KSTAT_DATA_UINT64 },
13878                 { "ip_recv_pullup",             KSTAT_DATA_UINT64 },
13879                 { "ip_db_ref",                  KSTAT_DATA_UINT64 },
13880                 { "ip_notaligned",              KSTAT_DATA_UINT64 },
13881                 { "ip_multimblk",               KSTAT_DATA_UINT64 },
13882                 { "ip_opt",                     KSTAT_DATA_UINT64 },
13883                 { "ipsec_proto_ahesp",          KSTAT_DATA_UINT64 },
13884                 { "ip_conn_flputbq",            KSTAT_DATA_UINT64 },
13885                 { "ip_conn_walk_drain",         KSTAT_DATA_UINT64 },
13886                 { "ip_out_sw_cksum",            KSTAT_DATA_UINT64 },
13887                 { "ip_out_sw_cksum_bytes",      KSTAT_DATA_UINT64 },
13888                 { "ip_in_sw_cksum",             KSTAT_DATA_UINT64 },
13889                 { "ip_ire_reclaim_calls",       KSTAT_DATA_UINT64 },
13890                 { "ip_ire_reclaim_deleted",     KSTAT_DATA_UINT64 },
13891                 { "ip_nce_reclaim_calls",       KSTAT_DATA_UINT64 },
13892                 { "ip_nce_reclaim_deleted",     KSTAT_DATA_UINT64 },
13893                 { "ip_nce_mcast_reclaim_calls", KSTAT_DATA_UINT64 },
13894                 { "ip_nce_mcast_reclaim_deleted",       KSTAT_DATA_UINT64 },
13895                 { "ip_nce_mcast_reclaim_tqfail",        KSTAT_DATA_UINT64 },
13896                 { "ip_dce_reclaim_calls",       KSTAT_DATA_UINT64 },
13897                 { "ip_dce_reclaim_deleted",     KSTAT_DATA_UINT64 },
13898                 { "ip_tcp_in_full_hw_cksum_err",        KSTAT_DATA_UINT64 },
13899                 { "ip_tcp_in_part_hw_cksum_err",        KSTAT_DATA_UINT64 },
13900                 { "ip_tcp_in_sw_cksum_err",             KSTAT_DATA_UINT64 },
13901                 { "ip_udp_in_full_hw_cksum_err",        KSTAT_DATA_UINT64 },
13902                 { "ip_udp_in_part_hw_cksum_err",        KSTAT_DATA_UINT64 },
13903                 { "ip_udp_in_sw_cksum_err",     KSTAT_DATA_UINT64 },
13904                 { "conn_in_recvdstaddr",        KSTAT_DATA_UINT64 },
13905                 { "conn_in_recvopts",           KSTAT_DATA_UINT64 },
13906                 { "conn_in_recvif",             KSTAT_DATA_UINT64 },
13907                 { "conn_in_recvslla",           KSTAT_DATA_UINT64 },
13908                 { "conn_in_recvucred",          KSTAT_DATA_UINT64 },
13909                 { "conn_in_recvttl",            KSTAT_DATA_UINT64 },
13910                 { "conn_in_recvhopopts",        KSTAT_DATA_UINT64 },
13911                 { "conn_in_recvhoplimit",       KSTAT_DATA_UINT64 },
13912                 { "conn_in_recvdstopts",        KSTAT_DATA_UINT64 },
13913                 { "conn_in_recvrthdrdstopts",   KSTAT_DATA_UINT64 },
13914                 { "conn_in_recvrthdr",          KSTAT_DATA_UINT64 },
13915                 { "conn_in_recvpktinfo",        KSTAT_DATA_UINT64 },
13916                 { "conn_in_recvtclass",         KSTAT_DATA_UINT64 },
13917                 { "conn_in_timestamp",          KSTAT_DATA_UINT64 },
13918         };
13919 
13920         ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13921             KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13922             KSTAT_FLAG_VIRTUAL, stackid);
13923 
13924         if (ksp == NULL)
13925                 return (NULL);
13926 
13927         bcopy(&template, ip_statisticsp, sizeof (template));
13928         ksp->ks_data = (void *)ip_statisticsp;
13929         ksp->ks_private = (void *)(uintptr_t)stackid;
13930 
13931         kstat_install(ksp);
13932         return (ksp);
13933 }
13934 
13935 static void
13936 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13937 {
13938         if (ksp != NULL) {
13939                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13940                 kstat_delete_netstack(ksp, stackid);
13941         }
13942 }
13943 
13944 static void *
13945 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13946 {
13947         kstat_t *ksp;
13948 
13949         ip_named_kstat_t template = {
13950                 { "forwarding",         KSTAT_DATA_UINT32, 0 },
13951                 { "defaultTTL",         KSTAT_DATA_UINT32, 0 },
13952                 { "inReceives",         KSTAT_DATA_UINT64, 0 },
13953                 { "inHdrErrors",        KSTAT_DATA_UINT32, 0 },
13954                 { "inAddrErrors",       KSTAT_DATA_UINT32, 0 },
13955                 { "forwDatagrams",      KSTAT_DATA_UINT64, 0 },
13956                 { "inUnknownProtos",    KSTAT_DATA_UINT32, 0 },
13957                 { "inDiscards",         KSTAT_DATA_UINT32, 0 },
13958                 { "inDelivers",         KSTAT_DATA_UINT64, 0 },
13959                 { "outRequests",        KSTAT_DATA_UINT64, 0 },
13960                 { "outDiscards",        KSTAT_DATA_UINT32, 0 },
13961                 { "outNoRoutes",        KSTAT_DATA_UINT32, 0 },
13962                 { "reasmTimeout",       KSTAT_DATA_UINT32, 0 },
13963                 { "reasmReqds",         KSTAT_DATA_UINT32, 0 },
13964                 { "reasmOKs",           KSTAT_DATA_UINT32, 0 },
13965                 { "reasmFails",         KSTAT_DATA_UINT32, 0 },
13966                 { "fragOKs",            KSTAT_DATA_UINT32, 0 },
13967                 { "fragFails",          KSTAT_DATA_UINT32, 0 },
13968                 { "fragCreates",        KSTAT_DATA_UINT32, 0 },
13969                 { "addrEntrySize",      KSTAT_DATA_INT32, 0 },
13970                 { "routeEntrySize",     KSTAT_DATA_INT32, 0 },
13971                 { "netToMediaEntrySize",        KSTAT_DATA_INT32, 0 },
13972                 { "routingDiscards",    KSTAT_DATA_UINT32, 0 },
13973                 { "inErrs",             KSTAT_DATA_UINT32, 0 },
13974                 { "noPorts",            KSTAT_DATA_UINT32, 0 },
13975                 { "inCksumErrs",        KSTAT_DATA_UINT32, 0 },
13976                 { "reasmDuplicates",    KSTAT_DATA_UINT32, 0 },
13977                 { "reasmPartDups",      KSTAT_DATA_UINT32, 0 },
13978                 { "forwProhibits",      KSTAT_DATA_UINT32, 0 },
13979                 { "udpInCksumErrs",     KSTAT_DATA_UINT32, 0 },
13980                 { "udpInOverflows",     KSTAT_DATA_UINT32, 0 },
13981                 { "rawipInOverflows",   KSTAT_DATA_UINT32, 0 },
13982                 { "ipsecInSucceeded",   KSTAT_DATA_UINT32, 0 },
13983                 { "ipsecInFailed",      KSTAT_DATA_INT32, 0 },
13984                 { "memberEntrySize",    KSTAT_DATA_INT32, 0 },
13985                 { "inIPv6",             KSTAT_DATA_UINT32, 0 },
13986                 { "outIPv6",            KSTAT_DATA_UINT32, 0 },
13987                 { "outSwitchIPv6",      KSTAT_DATA_UINT32, 0 },
13988         };
13989 
13990         ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
13991             NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
13992         if (ksp == NULL || ksp->ks_data == NULL)
13993                 return (NULL);
13994 
13995         template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
13996         template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
13997         template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
13998         template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
13999         template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14000 
14001         template.netToMediaEntrySize.value.i32 =
14002             sizeof (mib2_ipNetToMediaEntry_t);
14003 
14004         template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14005 
14006         bcopy(&template, ksp->ks_data, sizeof (template));
14007         ksp->ks_update = ip_kstat_update;
14008         ksp->ks_private = (void *)(uintptr_t)stackid;
14009 
14010         kstat_install(ksp);
14011         return (ksp);
14012 }
14013 
14014 static void
14015 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14016 {
14017         if (ksp != NULL) {
14018                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14019                 kstat_delete_netstack(ksp, stackid);
14020         }
14021 }
14022 
14023 static int
14024 ip_kstat_update(kstat_t *kp, int rw)
14025 {
14026         ip_named_kstat_t *ipkp;
14027         mib2_ipIfStatsEntry_t ipmib;
14028         ill_walk_context_t ctx;
14029         ill_t *ill;
14030         netstackid_t    stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14031         netstack_t      *ns;
14032         ip_stack_t      *ipst;
14033 
14034         if (kp->ks_data == NULL)
14035                 return (EIO);
14036 
14037         if (rw == KSTAT_WRITE)
14038                 return (EACCES);
14039 
14040         ns = netstack_find_by_stackid(stackid);
14041         if (ns == NULL)
14042                 return (-1);
14043         ipst = ns->netstack_ip;
14044         if (ipst == NULL) {
14045                 netstack_rele(ns);
14046                 return (-1);
14047         }
14048         ipkp = (ip_named_kstat_t *)kp->ks_data;
14049 
14050         bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14051         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14052         ill = ILL_START_WALK_V4(&ctx, ipst);
14053         for (; ill != NULL; ill = ill_next(&ctx, ill))
14054                 ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14055         rw_exit(&ipst->ips_ill_g_lock);
14056 
14057         ipkp->forwarding.value.ui32 =                ipmib.ipIfStatsForwarding;
14058         ipkp->defaultTTL.value.ui32 =                ipmib.ipIfStatsDefaultTTL;
14059         ipkp->inReceives.value.ui64 =                ipmib.ipIfStatsHCInReceives;
14060         ipkp->inHdrErrors.value.ui32 =               ipmib.ipIfStatsInHdrErrors;
14061         ipkp->inAddrErrors.value.ui32 =              ipmib.ipIfStatsInAddrErrors;
14062         ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14063         ipkp->inUnknownProtos.value.ui32 =   ipmib.ipIfStatsInUnknownProtos;
14064         ipkp->inDiscards.value.ui32 =                ipmib.ipIfStatsInDiscards;
14065         ipkp->inDelivers.value.ui64 =                ipmib.ipIfStatsHCInDelivers;
14066         ipkp->outRequests.value.ui64 =               ipmib.ipIfStatsHCOutRequests;
14067         ipkp->outDiscards.value.ui32 =               ipmib.ipIfStatsOutDiscards;
14068         ipkp->outNoRoutes.value.ui32 =               ipmib.ipIfStatsOutNoRoutes;
14069         ipkp->reasmTimeout.value.ui32 =              ipst->ips_ip_reassembly_timeout;
14070         ipkp->reasmReqds.value.ui32 =                ipmib.ipIfStatsReasmReqds;
14071         ipkp->reasmOKs.value.ui32 =          ipmib.ipIfStatsReasmOKs;
14072         ipkp->reasmFails.value.ui32 =                ipmib.ipIfStatsReasmFails;
14073         ipkp->fragOKs.value.ui32 =           ipmib.ipIfStatsOutFragOKs;
14074         ipkp->fragFails.value.ui32 =         ipmib.ipIfStatsOutFragFails;
14075         ipkp->fragCreates.value.ui32 =               ipmib.ipIfStatsOutFragCreates;
14076 
14077         ipkp->routingDiscards.value.ui32 =   0;
14078         ipkp->inErrs.value.ui32 =            ipmib.tcpIfStatsInErrs;
14079         ipkp->noPorts.value.ui32 =           ipmib.udpIfStatsNoPorts;
14080         ipkp->inCksumErrs.value.ui32 =               ipmib.ipIfStatsInCksumErrs;
14081         ipkp->reasmDuplicates.value.ui32 =   ipmib.ipIfStatsReasmDuplicates;
14082         ipkp->reasmPartDups.value.ui32 =     ipmib.ipIfStatsReasmPartDups;
14083         ipkp->forwProhibits.value.ui32 =     ipmib.ipIfStatsForwProhibits;
14084         ipkp->udpInCksumErrs.value.ui32 =    ipmib.udpIfStatsInCksumErrs;
14085         ipkp->udpInOverflows.value.ui32 =    ipmib.udpIfStatsInOverflows;
14086         ipkp->rawipInOverflows.value.ui32 =  ipmib.rawipIfStatsInOverflows;
14087         ipkp->ipsecInSucceeded.value.ui32 =  ipmib.ipsecIfStatsInSucceeded;
14088         ipkp->ipsecInFailed.value.i32 =              ipmib.ipsecIfStatsInFailed;
14089 
14090         ipkp->inIPv6.value.ui32 =    ipmib.ipIfStatsInWrongIPVersion;
14091         ipkp->outIPv6.value.ui32 =   ipmib.ipIfStatsOutWrongIPVersion;
14092         ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14093 
14094         netstack_rele(ns);
14095 
14096         return (0);
14097 }
14098 
14099 static void *
14100 icmp_kstat_init(netstackid_t stackid)
14101 {
14102         kstat_t *ksp;
14103 
14104         icmp_named_kstat_t template = {
14105                 { "inMsgs",             KSTAT_DATA_UINT32 },
14106                 { "inErrors",           KSTAT_DATA_UINT32 },
14107                 { "inDestUnreachs",     KSTAT_DATA_UINT32 },
14108                 { "inTimeExcds",        KSTAT_DATA_UINT32 },
14109                 { "inParmProbs",        KSTAT_DATA_UINT32 },
14110                 { "inSrcQuenchs",       KSTAT_DATA_UINT32 },
14111                 { "inRedirects",        KSTAT_DATA_UINT32 },
14112                 { "inEchos",            KSTAT_DATA_UINT32 },
14113                 { "inEchoReps",         KSTAT_DATA_UINT32 },
14114                 { "inTimestamps",       KSTAT_DATA_UINT32 },
14115                 { "inTimestampReps",    KSTAT_DATA_UINT32 },
14116                 { "inAddrMasks",        KSTAT_DATA_UINT32 },
14117                 { "inAddrMaskReps",     KSTAT_DATA_UINT32 },
14118                 { "outMsgs",            KSTAT_DATA_UINT32 },
14119                 { "outErrors",          KSTAT_DATA_UINT32 },
14120                 { "outDestUnreachs",    KSTAT_DATA_UINT32 },
14121                 { "outTimeExcds",       KSTAT_DATA_UINT32 },
14122                 { "outParmProbs",       KSTAT_DATA_UINT32 },
14123                 { "outSrcQuenchs",      KSTAT_DATA_UINT32 },
14124                 { "outRedirects",       KSTAT_DATA_UINT32 },
14125                 { "outEchos",           KSTAT_DATA_UINT32 },
14126                 { "outEchoReps",        KSTAT_DATA_UINT32 },
14127                 { "outTimestamps",      KSTAT_DATA_UINT32 },
14128                 { "outTimestampReps",   KSTAT_DATA_UINT32 },
14129                 { "outAddrMasks",       KSTAT_DATA_UINT32 },
14130                 { "outAddrMaskReps",    KSTAT_DATA_UINT32 },
14131                 { "inChksumErrs",       KSTAT_DATA_UINT32 },
14132                 { "inUnknowns",         KSTAT_DATA_UINT32 },
14133                 { "inFragNeeded",       KSTAT_DATA_UINT32 },
14134                 { "outFragNeeded",      KSTAT_DATA_UINT32 },
14135                 { "outDrops",           KSTAT_DATA_UINT32 },
14136                 { "inOverFlows",        KSTAT_DATA_UINT32 },
14137                 { "inBadRedirects",     KSTAT_DATA_UINT32 },
14138         };
14139 
14140         ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14141             NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14142         if (ksp == NULL || ksp->ks_data == NULL)
14143                 return (NULL);
14144 
14145         bcopy(&template, ksp->ks_data, sizeof (template));
14146 
14147         ksp->ks_update = icmp_kstat_update;
14148         ksp->ks_private = (void *)(uintptr_t)stackid;
14149 
14150         kstat_install(ksp);
14151         return (ksp);
14152 }
14153 
14154 static void
14155 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14156 {
14157         if (ksp != NULL) {
14158                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14159                 kstat_delete_netstack(ksp, stackid);
14160         }
14161 }
14162 
14163 static int
14164 icmp_kstat_update(kstat_t *kp, int rw)
14165 {
14166         icmp_named_kstat_t *icmpkp;
14167         netstackid_t    stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14168         netstack_t      *ns;
14169         ip_stack_t      *ipst;
14170 
14171         if (kp->ks_data == NULL)
14172                 return (EIO);
14173 
14174         if (rw == KSTAT_WRITE)
14175                 return (EACCES);
14176 
14177         ns = netstack_find_by_stackid(stackid);
14178         if (ns == NULL)
14179                 return (-1);
14180         ipst = ns->netstack_ip;
14181         if (ipst == NULL) {
14182                 netstack_rele(ns);
14183                 return (-1);
14184         }
14185         icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14186 
14187         icmpkp->inMsgs.value.ui32 =      ipst->ips_icmp_mib.icmpInMsgs;
14188         icmpkp->inErrors.value.ui32 =            ipst->ips_icmp_mib.icmpInErrors;
14189         icmpkp->inDestUnreachs.value.ui32 =
14190             ipst->ips_icmp_mib.icmpInDestUnreachs;
14191         icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14192         icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14193         icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14194         icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14195         icmpkp->inEchos.value.ui32 =     ipst->ips_icmp_mib.icmpInEchos;
14196         icmpkp->inEchoReps.value.ui32 =          ipst->ips_icmp_mib.icmpInEchoReps;
14197         icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14198         icmpkp->inTimestampReps.value.ui32 =
14199             ipst->ips_icmp_mib.icmpInTimestampReps;
14200         icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14201         icmpkp->inAddrMaskReps.value.ui32 =
14202             ipst->ips_icmp_mib.icmpInAddrMaskReps;
14203         icmpkp->outMsgs.value.ui32 =     ipst->ips_icmp_mib.icmpOutMsgs;
14204         icmpkp->outErrors.value.ui32 =           ipst->ips_icmp_mib.icmpOutErrors;
14205         icmpkp->outDestUnreachs.value.ui32 =
14206             ipst->ips_icmp_mib.icmpOutDestUnreachs;
14207         icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14208         icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14209         icmpkp->outSrcQuenchs.value.ui32 =
14210             ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14211         icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14212         icmpkp->outEchos.value.ui32 =            ipst->ips_icmp_mib.icmpOutEchos;
14213         icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14214         icmpkp->outTimestamps.value.ui32 =
14215             ipst->ips_icmp_mib.icmpOutTimestamps;
14216         icmpkp->outTimestampReps.value.ui32 =
14217             ipst->ips_icmp_mib.icmpOutTimestampReps;
14218         icmpkp->outAddrMasks.value.ui32 =
14219             ipst->ips_icmp_mib.icmpOutAddrMasks;
14220         icmpkp->outAddrMaskReps.value.ui32 =
14221             ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14222         icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14223         icmpkp->inUnknowns.value.ui32 =          ipst->ips_icmp_mib.icmpInUnknowns;
14224         icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14225         icmpkp->outFragNeeded.value.ui32 =
14226             ipst->ips_icmp_mib.icmpOutFragNeeded;
14227         icmpkp->outDrops.value.ui32 =            ipst->ips_icmp_mib.icmpOutDrops;
14228         icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14229         icmpkp->inBadRedirects.value.ui32 =
14230             ipst->ips_icmp_mib.icmpInBadRedirects;
14231 
14232         netstack_rele(ns);
14233         return (0);
14234 }
14235 
14236 /*
14237  * This is the fanout function for raw socket opened for SCTP.  Note
14238  * that it is called after SCTP checks that there is no socket which
14239  * wants a packet.  Then before SCTP handles this out of the blue packet,
14240  * this function is called to see if there is any raw socket for SCTP.
14241  * If there is and it is bound to the correct address, the packet will
14242  * be sent to that socket.  Note that only one raw socket can be bound to
14243  * a port.  This is assured in ipcl_sctp_hash_insert();
14244  */
14245 void
14246 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14247     ip_recv_attr_t *ira)
14248 {
14249         conn_t          *connp;
14250         queue_t         *rq;
14251         boolean_t       secure;
14252         ill_t           *ill = ira->ira_ill;
14253         ip_stack_t      *ipst = ill->ill_ipst;
14254         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
14255         sctp_stack_t    *sctps = ipst->ips_netstack->netstack_sctp;
14256         iaflags_t       iraflags = ira->ira_flags;
14257         ill_t           *rill = ira->ira_rill;
14258 
14259         secure = iraflags & IRAF_IPSEC_SECURE;
14260 
14261         connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14262             ira, ipst);
14263         if (connp == NULL) {
14264                 /*
14265                  * Although raw sctp is not summed, OOB chunks must be.
14266                  * Drop the packet here if the sctp checksum failed.
14267                  */
14268                 if (iraflags & IRAF_SCTP_CSUM_ERR) {
14269                         SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14270                         freemsg(mp);
14271                         return;
14272                 }
14273                 ira->ira_ill = ira->ira_rill = NULL;
14274                 sctp_ootb_input(mp, ira, ipst);
14275                 ira->ira_ill = ill;
14276                 ira->ira_rill = rill;
14277                 return;
14278         }
14279         rq = connp->conn_rq;
14280         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14281                 CONN_DEC_REF(connp);
14282                 BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14283                 freemsg(mp);
14284                 return;
14285         }
14286         if (((iraflags & IRAF_IS_IPV4) ?
14287             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14288             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14289             secure) {
14290                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
14291                     ip6h, ira);
14292                 if (mp == NULL) {
14293                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14294                         /* Note that mp is NULL */
14295                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
14296                         CONN_DEC_REF(connp);
14297                         return;
14298                 }
14299         }
14300 
14301         if (iraflags & IRAF_ICMP_ERROR) {
14302                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
14303         } else {
14304                 ill_t *rill = ira->ira_rill;
14305 
14306                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14307                 /* This is the SOCK_RAW, IPPROTO_SCTP case. */
14308                 ira->ira_ill = ira->ira_rill = NULL;
14309                 (connp->conn_recv)(connp, mp, NULL, ira);
14310                 ira->ira_ill = ill;
14311                 ira->ira_rill = rill;
14312         }
14313         CONN_DEC_REF(connp);
14314 }
14315 
14316 /*
14317  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14318  * header before the ip payload.
14319  */
14320 static void
14321 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14322 {
14323         int len = (mp->b_wptr - mp->b_rptr);
14324         mblk_t *ip_mp;
14325 
14326         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14327         if (is_fp_mp || len != fp_mp_len) {
14328                 if (len > fp_mp_len) {
14329                         /*
14330                          * fastpath header and ip header in the first mblk
14331                          */
14332                         mp->b_rptr += fp_mp_len;
14333                 } else {
14334                         /*
14335                          * ip_xmit_attach_llhdr had to prepend an mblk to
14336                          * attach the fastpath header before ip header.
14337                          */
14338                         ip_mp = mp->b_cont;
14339                         freeb(mp);
14340                         mp = ip_mp;
14341                         mp->b_rptr += (fp_mp_len - len);
14342                 }
14343         } else {
14344                 ip_mp = mp->b_cont;
14345                 freeb(mp);
14346                 mp = ip_mp;
14347         }
14348         ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14349         freemsg(mp);
14350 }
14351 
14352 /*
14353  * Normal post fragmentation function.
14354  *
14355  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14356  * using the same state machine.
14357  *
14358  * We return an error on failure. In particular we return EWOULDBLOCK
14359  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14360  * (currently by canputnext failure resulting in backenabling from GLD.)
14361  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14362  * indication that they can flow control until ip_wsrv() tells then to restart.
14363  *
14364  * If the nce passed by caller is incomplete, this function
14365  * queues the packet and if necessary, sends ARP request and bails.
14366  * If the Neighbor Cache passed is fully resolved, we simply prepend
14367  * the link-layer header to the packet, do ipsec hw acceleration
14368  * work if necessary, and send the packet out on the wire.
14369  */
14370 /* ARGSUSED6 */
14371 int
14372 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14373     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14374 {
14375         queue_t         *wq;
14376         ill_t           *ill = nce->nce_ill;
14377         ip_stack_t      *ipst = ill->ill_ipst;
14378         uint64_t        delta;
14379         boolean_t       isv6 = ill->ill_isv6;
14380         boolean_t       fp_mp;
14381         ncec_t          *ncec = nce->nce_common;
14382         int64_t         now = LBOLT_FASTPATH64;
14383         boolean_t       is_probe;
14384 
14385         DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14386 
14387         ASSERT(mp != NULL);
14388         ASSERT(mp->b_datap->db_type == M_DATA);
14389         ASSERT(pkt_len == msgdsize(mp));
14390 
14391         /*
14392          * If we have already been here and are coming back after ARP/ND.
14393          * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14394          * in that case since they have seen the packet when it came here
14395          * the first time.
14396          */
14397         if (ixaflags & IXAF_NO_TRACE)
14398                 goto sendit;
14399 
14400         if (ixaflags & IXAF_IS_IPV4) {
14401                 ipha_t *ipha = (ipha_t *)mp->b_rptr;
14402 
14403                 ASSERT(!isv6);
14404                 ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14405                 if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14406                     !(ixaflags & IXAF_NO_PFHOOK)) {
14407                         int     error;
14408 
14409                         FW_HOOKS(ipst->ips_ip4_physical_out_event,
14410                             ipst->ips_ipv4firewall_physical_out,
14411                             NULL, ill, ipha, mp, mp, 0, ipst, error);
14412                         DTRACE_PROBE1(ip4__physical__out__end,
14413                             mblk_t *, mp);
14414                         if (mp == NULL)
14415                                 return (error);
14416 
14417                         /* The length could have changed */
14418                         pkt_len = msgdsize(mp);
14419                 }
14420                 if (ipst->ips_ip4_observe.he_interested) {
14421                         /*
14422                          * Note that for TX the zoneid is the sending
14423                          * zone, whether or not MLP is in play.
14424                          * Since the szone argument is the IP zoneid (i.e.,
14425                          * zero for exclusive-IP zones) and ipobs wants
14426                          * the system zoneid, we map it here.
14427                          */
14428                         szone = IP_REAL_ZONEID(szone, ipst);
14429 
14430                         /*
14431                          * On the outbound path the destination zone will be
14432                          * unknown as we're sending this packet out on the
14433                          * wire.
14434                          */
14435                         ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14436                             ill, ipst);
14437                 }
14438                 DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14439                     void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14440                     ipha_t *, ipha, ip6_t *, NULL, int, 0);
14441         } else {
14442                 ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14443 
14444                 ASSERT(isv6);
14445                 ASSERT(pkt_len ==
14446                     ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14447                 if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14448                     !(ixaflags & IXAF_NO_PFHOOK)) {
14449                         int     error;
14450 
14451                         FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14452                             ipst->ips_ipv6firewall_physical_out,
14453                             NULL, ill, ip6h, mp, mp, 0, ipst, error);
14454                         DTRACE_PROBE1(ip6__physical__out__end,
14455                             mblk_t *, mp);
14456                         if (mp == NULL)
14457                                 return (error);
14458 
14459                         /* The length could have changed */
14460                         pkt_len = msgdsize(mp);
14461                 }
14462                 if (ipst->ips_ip6_observe.he_interested) {
14463                         /* See above */
14464                         szone = IP_REAL_ZONEID(szone, ipst);
14465 
14466                         ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14467                             ill, ipst);
14468                 }
14469                 DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14470                     void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14471                     ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14472         }
14473 
14474 sendit:
14475         /*
14476          * We check the state without a lock because the state can never
14477          * move "backwards" to initial or incomplete.
14478          */
14479         switch (ncec->ncec_state) {
14480         case ND_REACHABLE:
14481         case ND_STALE:
14482         case ND_DELAY:
14483         case ND_PROBE:
14484                 mp = ip_xmit_attach_llhdr(mp, nce);
14485                 if (mp == NULL) {
14486                         /*
14487                          * ip_xmit_attach_llhdr has increased
14488                          * ipIfStatsOutDiscards and called ip_drop_output()
14489                          */
14490                         return (ENOBUFS);
14491                 }
14492                 /*
14493                  * check if nce_fastpath completed and we tagged on a
14494                  * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14495                  */
14496                 fp_mp = (mp->b_datap->db_type == M_DATA);
14497 
14498                 if (fp_mp &&
14499                     (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14500                         ill_dld_direct_t *idd;
14501 
14502                         idd = &ill->ill_dld_capab->idc_direct;
14503                         /*
14504                          * Send the packet directly to DLD, where it
14505                          * may be queued depending on the availability
14506                          * of transmit resources at the media layer.
14507                          * Return value should be taken into
14508                          * account and flow control the TCP.
14509                          */
14510                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14511                         UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14512                             pkt_len);
14513 
14514                         if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14515                                 (void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14516                                     (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14517                         } else {
14518                                 uintptr_t cookie;
14519 
14520                                 if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14521                                     mp, (uintptr_t)xmit_hint, 0)) != 0) {
14522                                         if (ixacookie != NULL)
14523                                                 *ixacookie = cookie;
14524                                         return (EWOULDBLOCK);
14525                                 }
14526                         }
14527                 } else {
14528                         wq = ill->ill_wq;
14529 
14530                         if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14531                             !canputnext(wq)) {
14532                                 if (ixacookie != NULL)
14533                                         *ixacookie = 0;
14534                                 ip_xmit_flowctl_drop(ill, mp, fp_mp,
14535                                     nce->nce_fp_mp != NULL ?
14536                                     MBLKL(nce->nce_fp_mp) : 0);
14537                                 return (EWOULDBLOCK);
14538                         }
14539                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14540                         UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14541                             pkt_len);
14542                         putnext(wq, mp);
14543                 }
14544 
14545                 /*
14546                  * The rest of this function implements Neighbor Unreachability
14547                  * detection. Determine if the ncec is eligible for NUD.
14548                  */
14549                 if (ncec->ncec_flags & NCE_F_NONUD)
14550                         return (0);
14551 
14552                 ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14553 
14554                 /*
14555                  * Check for upper layer advice
14556                  */
14557                 if (ixaflags & IXAF_REACH_CONF) {
14558                         timeout_id_t tid;
14559 
14560                         /*
14561                          * It should be o.k. to check the state without
14562                          * a lock here, at most we lose an advice.
14563                          */
14564                         ncec->ncec_last = TICK_TO_MSEC(now);
14565                         if (ncec->ncec_state != ND_REACHABLE) {
14566                                 mutex_enter(&ncec->ncec_lock);
14567                                 ncec->ncec_state = ND_REACHABLE;
14568                                 tid = ncec->ncec_timeout_id;
14569                                 ncec->ncec_timeout_id = 0;
14570                                 mutex_exit(&ncec->ncec_lock);
14571                                 (void) untimeout(tid);
14572                                 if (ip_debug > 2) {
14573                                         /* ip1dbg */
14574                                         pr_addr_dbg("ip_xmit: state"
14575                                             " for %s changed to"
14576                                             " REACHABLE\n", AF_INET6,
14577                                             &ncec->ncec_addr);
14578                                 }
14579                         }
14580                         return (0);
14581                 }
14582 
14583                 delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14584                 ip1dbg(("ip_xmit: delta = %" PRId64
14585                     " ill_reachable_time = %d \n", delta,
14586                     ill->ill_reachable_time));
14587                 if (delta > (uint64_t)ill->ill_reachable_time) {
14588                         mutex_enter(&ncec->ncec_lock);
14589                         switch (ncec->ncec_state) {
14590                         case ND_REACHABLE:
14591                                 ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14592                                 /* FALLTHROUGH */
14593                         case ND_STALE:
14594                                 /*
14595                                  * ND_REACHABLE is identical to
14596                                  * ND_STALE in this specific case. If
14597                                  * reachable time has expired for this
14598                                  * neighbor (delta is greater than
14599                                  * reachable time), conceptually, the
14600                                  * neighbor cache is no longer in
14601                                  * REACHABLE state, but already in
14602                                  * STALE state.  So the correct
14603                                  * transition here is to ND_DELAY.
14604                                  */
14605                                 ncec->ncec_state = ND_DELAY;
14606                                 mutex_exit(&ncec->ncec_lock);
14607                                 nce_restart_timer(ncec,
14608                                     ipst->ips_delay_first_probe_time);
14609                                 if (ip_debug > 3) {
14610                                         /* ip2dbg */
14611                                         pr_addr_dbg("ip_xmit: state"
14612                                             " for %s changed to"
14613                                             " DELAY\n", AF_INET6,
14614                                             &ncec->ncec_addr);
14615                                 }
14616                                 break;
14617                         case ND_DELAY:
14618                         case ND_PROBE:
14619                                 mutex_exit(&ncec->ncec_lock);
14620                                 /* Timers have already started */
14621                                 break;
14622                         case ND_UNREACHABLE:
14623                                 /*
14624                                  * nce_timer has detected that this ncec
14625                                  * is unreachable and initiated deleting
14626                                  * this ncec.
14627                                  * This is a harmless race where we found the
14628                                  * ncec before it was deleted and have
14629                                  * just sent out a packet using this
14630                                  * unreachable ncec.
14631                                  */
14632                                 mutex_exit(&ncec->ncec_lock);
14633                                 break;
14634                         default:
14635                                 ASSERT(0);
14636                                 mutex_exit(&ncec->ncec_lock);
14637                         }
14638                 }
14639                 return (0);
14640 
14641         case ND_INCOMPLETE:
14642                 /*
14643                  * the state could have changed since we didn't hold the lock.
14644                  * Re-verify state under lock.
14645                  */
14646                 is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14647                 mutex_enter(&ncec->ncec_lock);
14648                 if (NCE_ISREACHABLE(ncec)) {
14649                         mutex_exit(&ncec->ncec_lock);
14650                         goto sendit;
14651                 }
14652                 /* queue the packet */
14653                 nce_queue_mp(ncec, mp, is_probe);
14654                 mutex_exit(&ncec->ncec_lock);
14655                 DTRACE_PROBE2(ip__xmit__incomplete,
14656                     (ncec_t *), ncec, (mblk_t *), mp);
14657                 return (0);
14658 
14659         case ND_INITIAL:
14660                 /*
14661                  * State could have changed since we didn't hold the lock, so
14662                  * re-verify state.
14663                  */
14664                 is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14665                 mutex_enter(&ncec->ncec_lock);
14666                 if (NCE_ISREACHABLE(ncec))  {
14667                         mutex_exit(&ncec->ncec_lock);
14668                         goto sendit;
14669                 }
14670                 nce_queue_mp(ncec, mp, is_probe);
14671                 if (ncec->ncec_state == ND_INITIAL) {
14672                         ncec->ncec_state = ND_INCOMPLETE;
14673                         mutex_exit(&ncec->ncec_lock);
14674                         /*
14675                          * figure out the source we want to use
14676                          * and resolve it.
14677                          */
14678                         ip_ndp_resolve(ncec);
14679                 } else  {
14680                         mutex_exit(&ncec->ncec_lock);
14681                 }
14682                 return (0);
14683 
14684         case ND_UNREACHABLE:
14685                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14686                 ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14687                     mp, ill);
14688                 freemsg(mp);
14689                 return (0);
14690 
14691         default:
14692                 ASSERT(0);
14693                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14694                 ip_drop_output("ipIfStatsOutDiscards - ND_other",
14695                     mp, ill);
14696                 freemsg(mp);
14697                 return (ENETUNREACH);
14698         }
14699 }
14700 
14701 /*
14702  * Return B_TRUE if the buffers differ in length or content.
14703  * This is used for comparing extension header buffers.
14704  * Note that an extension header would be declared different
14705  * even if all that changed was the next header value in that header i.e.
14706  * what really changed is the next extension header.
14707  */
14708 boolean_t
14709 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14710     uint_t blen)
14711 {
14712         if (!b_valid)
14713                 blen = 0;
14714 
14715         if (alen != blen)
14716                 return (B_TRUE);
14717         if (alen == 0)
14718                 return (B_FALSE);       /* Both zero length */
14719         return (bcmp(abuf, bbuf, alen));
14720 }
14721 
14722 /*
14723  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14724  * Return B_FALSE if memory allocation fails - don't change any state!
14725  */
14726 boolean_t
14727 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14728     const void *src, uint_t srclen)
14729 {
14730         void *dst;
14731 
14732         if (!src_valid)
14733                 srclen = 0;
14734 
14735         ASSERT(*dstlenp == 0);
14736         if (src != NULL && srclen != 0) {
14737                 dst = mi_alloc(srclen, BPRI_MED);
14738                 if (dst == NULL)
14739                         return (B_FALSE);
14740         } else {
14741                 dst = NULL;
14742         }
14743         if (*dstp != NULL)
14744                 mi_free(*dstp);
14745         *dstp = dst;
14746         *dstlenp = dst == NULL ? 0 : srclen;
14747         return (B_TRUE);
14748 }
14749 
14750 /*
14751  * Replace what is in *dst, *dstlen with the source.
14752  * Assumes ip_allocbuf has already been called.
14753  */
14754 void
14755 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14756     const void *src, uint_t srclen)
14757 {
14758         if (!src_valid)
14759                 srclen = 0;
14760 
14761         ASSERT(*dstlenp == srclen);
14762         if (src != NULL && srclen != 0)
14763                 bcopy(src, *dstp, srclen);
14764 }
14765 
14766 /*
14767  * Free the storage pointed to by the members of an ip_pkt_t.
14768  */
14769 void
14770 ip_pkt_free(ip_pkt_t *ipp)
14771 {
14772         uint_t  fields = ipp->ipp_fields;
14773 
14774         if (fields & IPPF_HOPOPTS) {
14775                 kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14776                 ipp->ipp_hopopts = NULL;
14777                 ipp->ipp_hopoptslen = 0;
14778         }
14779         if (fields & IPPF_RTHDRDSTOPTS) {
14780                 kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14781                 ipp->ipp_rthdrdstopts = NULL;
14782                 ipp->ipp_rthdrdstoptslen = 0;
14783         }
14784         if (fields & IPPF_DSTOPTS) {
14785                 kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14786                 ipp->ipp_dstopts = NULL;
14787                 ipp->ipp_dstoptslen = 0;
14788         }
14789         if (fields & IPPF_RTHDR) {
14790                 kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14791                 ipp->ipp_rthdr = NULL;
14792                 ipp->ipp_rthdrlen = 0;
14793         }
14794         if (fields & IPPF_IPV4_OPTIONS) {
14795                 kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14796                 ipp->ipp_ipv4_options = NULL;
14797                 ipp->ipp_ipv4_options_len = 0;
14798         }
14799         if (fields & IPPF_LABEL_V4) {
14800                 kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14801                 ipp->ipp_label_v4 = NULL;
14802                 ipp->ipp_label_len_v4 = 0;
14803         }
14804         if (fields & IPPF_LABEL_V6) {
14805                 kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14806                 ipp->ipp_label_v6 = NULL;
14807                 ipp->ipp_label_len_v6 = 0;
14808         }
14809         ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14810             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14811 }
14812 
14813 /*
14814  * Copy from src to dst and allocate as needed.
14815  * Returns zero or ENOMEM.
14816  *
14817  * The caller must initialize dst to zero.
14818  */
14819 int
14820 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14821 {
14822         uint_t  fields = src->ipp_fields;
14823 
14824         /* Start with fields that don't require memory allocation */
14825         dst->ipp_fields = fields &
14826             ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14827             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14828 
14829         dst->ipp_addr = src->ipp_addr;
14830         dst->ipp_unicast_hops = src->ipp_unicast_hops;
14831         dst->ipp_hoplimit = src->ipp_hoplimit;
14832         dst->ipp_tclass = src->ipp_tclass;
14833         dst->ipp_type_of_service = src->ipp_type_of_service;
14834 
14835         if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14836             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14837                 return (0);
14838 
14839         if (fields & IPPF_HOPOPTS) {
14840                 dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14841                 if (dst->ipp_hopopts == NULL) {
14842                         ip_pkt_free(dst);
14843                         return (ENOMEM);
14844                 }
14845                 dst->ipp_fields |= IPPF_HOPOPTS;
14846                 bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14847                     src->ipp_hopoptslen);
14848                 dst->ipp_hopoptslen = src->ipp_hopoptslen;
14849         }
14850         if (fields & IPPF_RTHDRDSTOPTS) {
14851                 dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14852                     kmflag);
14853                 if (dst->ipp_rthdrdstopts == NULL) {
14854                         ip_pkt_free(dst);
14855                         return (ENOMEM);
14856                 }
14857                 dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14858                 bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14859                     src->ipp_rthdrdstoptslen);
14860                 dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14861         }
14862         if (fields & IPPF_DSTOPTS) {
14863                 dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14864                 if (dst->ipp_dstopts == NULL) {
14865                         ip_pkt_free(dst);
14866                         return (ENOMEM);
14867                 }
14868                 dst->ipp_fields |= IPPF_DSTOPTS;
14869                 bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14870                     src->ipp_dstoptslen);
14871                 dst->ipp_dstoptslen = src->ipp_dstoptslen;
14872         }
14873         if (fields & IPPF_RTHDR) {
14874                 dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14875                 if (dst->ipp_rthdr == NULL) {
14876                         ip_pkt_free(dst);
14877                         return (ENOMEM);
14878                 }
14879                 dst->ipp_fields |= IPPF_RTHDR;
14880                 bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14881                     src->ipp_rthdrlen);
14882                 dst->ipp_rthdrlen = src->ipp_rthdrlen;
14883         }
14884         if (fields & IPPF_IPV4_OPTIONS) {
14885                 dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14886                     kmflag);
14887                 if (dst->ipp_ipv4_options == NULL) {
14888                         ip_pkt_free(dst);
14889                         return (ENOMEM);
14890                 }
14891                 dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14892                 bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14893                     src->ipp_ipv4_options_len);
14894                 dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14895         }
14896         if (fields & IPPF_LABEL_V4) {
14897                 dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14898                 if (dst->ipp_label_v4 == NULL) {
14899                         ip_pkt_free(dst);
14900                         return (ENOMEM);
14901                 }
14902                 dst->ipp_fields |= IPPF_LABEL_V4;
14903                 bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14904                     src->ipp_label_len_v4);
14905                 dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14906         }
14907         if (fields & IPPF_LABEL_V6) {
14908                 dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14909                 if (dst->ipp_label_v6 == NULL) {
14910                         ip_pkt_free(dst);
14911                         return (ENOMEM);
14912                 }
14913                 dst->ipp_fields |= IPPF_LABEL_V6;
14914                 bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14915                     src->ipp_label_len_v6);
14916                 dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14917         }
14918         if (fields & IPPF_FRAGHDR) {
14919                 dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14920                 if (dst->ipp_fraghdr == NULL) {
14921                         ip_pkt_free(dst);
14922                         return (ENOMEM);
14923                 }
14924                 dst->ipp_fields |= IPPF_FRAGHDR;
14925                 bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14926                     src->ipp_fraghdrlen);
14927                 dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14928         }
14929         return (0);
14930 }
14931 
14932 /*
14933  * Returns INADDR_ANY if no source route
14934  */
14935 ipaddr_t
14936 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14937 {
14938         ipaddr_t        nexthop = INADDR_ANY;
14939         ipoptp_t        opts;
14940         uchar_t         *opt;
14941         uint8_t         optval;
14942         uint8_t         optlen;
14943         uint32_t        totallen;
14944 
14945         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14946                 return (INADDR_ANY);
14947 
14948         totallen = ipp->ipp_ipv4_options_len;
14949         if (totallen & 0x3)
14950                 return (INADDR_ANY);
14951 
14952         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14953             optval != IPOPT_EOL;
14954             optval = ipoptp_next(&opts)) {
14955                 opt = opts.ipoptp_cur;
14956                 switch (optval) {
14957                         uint8_t off;
14958                 case IPOPT_SSRR:
14959                 case IPOPT_LSRR:
14960                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14961                                 break;
14962                         }
14963                         optlen = opts.ipoptp_len;
14964                         off = opt[IPOPT_OFFSET];
14965                         off--;
14966                         if (optlen < IP_ADDR_LEN ||
14967                             off > optlen - IP_ADDR_LEN) {
14968                                 /* End of source route */
14969                                 break;
14970                         }
14971                         bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14972                         if (nexthop == htonl(INADDR_LOOPBACK)) {
14973                                 /* Ignore */
14974                                 nexthop = INADDR_ANY;
14975                                 break;
14976                         }
14977                         break;
14978                 }
14979         }
14980         return (nexthop);
14981 }
14982 
14983 /*
14984  * Reverse a source route.
14985  */
14986 void
14987 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
14988 {
14989         ipaddr_t        tmp;
14990         ipoptp_t        opts;
14991         uchar_t         *opt;
14992         uint8_t         optval;
14993         uint32_t        totallen;
14994 
14995         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14996                 return;
14997 
14998         totallen = ipp->ipp_ipv4_options_len;
14999         if (totallen & 0x3)
15000                 return;
15001 
15002         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15003             optval != IPOPT_EOL;
15004             optval = ipoptp_next(&opts)) {
15005                 uint8_t off1, off2;
15006 
15007                 opt = opts.ipoptp_cur;
15008                 switch (optval) {
15009                 case IPOPT_SSRR:
15010                 case IPOPT_LSRR:
15011                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15012                                 break;
15013                         }
15014                         off1 = IPOPT_MINOFF_SR - 1;
15015                         off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15016                         while (off2 > off1) {
15017                                 bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15018                                 bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15019                                 bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15020                                 off2 -= IP_ADDR_LEN;
15021                                 off1 += IP_ADDR_LEN;
15022                         }
15023                         opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15024                         break;
15025                 }
15026         }
15027 }
15028 
15029 /*
15030  * Returns NULL if no routing header
15031  */
15032 in6_addr_t *
15033 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15034 {
15035         in6_addr_t      *nexthop = NULL;
15036         ip6_rthdr0_t    *rthdr;
15037 
15038         if (!(ipp->ipp_fields & IPPF_RTHDR))
15039                 return (NULL);
15040 
15041         rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15042         if (rthdr->ip6r0_segleft == 0)
15043                 return (NULL);
15044 
15045         nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15046         return (nexthop);
15047 }
15048 
15049 zoneid_t
15050 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15051     zoneid_t lookup_zoneid)
15052 {
15053         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
15054         ire_t           *ire;
15055         int             ire_flags = MATCH_IRE_TYPE;
15056         zoneid_t        zoneid = ALL_ZONES;
15057 
15058         if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15059                 return (ALL_ZONES);
15060 
15061         if (lookup_zoneid != ALL_ZONES)
15062                 ire_flags |= MATCH_IRE_ZONEONLY;
15063         ire = ire_ftable_lookup_v4(addr, 0, 0, IRE_LOCAL | IRE_LOOPBACK,
15064             NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15065         if (ire != NULL) {
15066                 zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15067                 ire_refrele(ire);
15068         }
15069         return (zoneid);
15070 }
15071 
15072 zoneid_t
15073 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15074     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15075 {
15076         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
15077         ire_t           *ire;
15078         int             ire_flags = MATCH_IRE_TYPE;
15079         zoneid_t        zoneid = ALL_ZONES;
15080 
15081         if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15082                 return (ALL_ZONES);
15083 
15084         if (IN6_IS_ADDR_LINKLOCAL(addr))
15085                 ire_flags |= MATCH_IRE_ILL;
15086 
15087         if (lookup_zoneid != ALL_ZONES)
15088                 ire_flags |= MATCH_IRE_ZONEONLY;
15089         ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15090             ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15091         if (ire != NULL) {
15092                 zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15093                 ire_refrele(ire);
15094         }
15095         return (zoneid);
15096 }
15097 
15098 /*
15099  * IP obserability hook support functions.
15100  */
15101 static void
15102 ipobs_init(ip_stack_t *ipst)
15103 {
15104         netid_t id;
15105 
15106         id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15107 
15108         ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15109         VERIFY(ipst->ips_ip4_observe_pr != NULL);
15110 
15111         ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15112         VERIFY(ipst->ips_ip6_observe_pr != NULL);
15113 }
15114 
15115 static void
15116 ipobs_fini(ip_stack_t *ipst)
15117 {
15118 
15119         VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15120         VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15121 }
15122 
15123 /*
15124  * hook_pkt_observe_t is composed in network byte order so that the
15125  * entire mblk_t chain handed into hook_run can be used as-is.
15126  * The caveat is that use of the fields, such as the zone fields,
15127  * requires conversion into host byte order first.
15128  */
15129 void
15130 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15131     const ill_t *ill, ip_stack_t *ipst)
15132 {
15133         hook_pkt_observe_t *hdr;
15134         uint64_t grifindex;
15135         mblk_t *imp;
15136 
15137         imp = allocb(sizeof (*hdr), BPRI_HI);
15138         if (imp == NULL)
15139                 return;
15140 
15141         hdr = (hook_pkt_observe_t *)imp->b_rptr;
15142         /*
15143          * b_wptr is set to make the apparent size of the data in the mblk_t
15144          * to exclude the pointers at the end of hook_pkt_observer_t.
15145          */
15146         imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15147         imp->b_cont = mp;
15148 
15149         ASSERT(DB_TYPE(mp) == M_DATA);
15150 
15151         if (IS_UNDER_IPMP(ill))
15152                 grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15153         else
15154                 grifindex = 0;
15155 
15156         hdr->hpo_version = 1;
15157         hdr->hpo_htype = htons(htype);
15158         hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15159         hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15160         hdr->hpo_grifindex = htonl(grifindex);
15161         hdr->hpo_zsrc = htonl(zsrc);
15162         hdr->hpo_zdst = htonl(zdst);
15163         hdr->hpo_pkt = imp;
15164         hdr->hpo_ctx = ipst->ips_netstack;
15165 
15166         if (ill->ill_isv6) {
15167                 hdr->hpo_family = AF_INET6;
15168                 (void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15169                     ipst->ips_ipv6observing, (hook_data_t)hdr);
15170         } else {
15171                 hdr->hpo_family = AF_INET;
15172                 (void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15173                     ipst->ips_ipv4observing, (hook_data_t)hdr);
15174         }
15175 
15176         imp->b_cont = NULL;
15177         freemsg(imp);
15178 }
15179 
15180 /*
15181  * Utility routine that checks if `v4srcp' is a valid address on underlying
15182  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15183  * associated with `v4srcp' on success.  NOTE: if this is not called from
15184  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15185  * group during or after this lookup.
15186  */
15187 boolean_t
15188 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15189 {
15190         ipif_t *ipif;
15191 
15192         ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15193         if (ipif != NULL) {
15194                 if (ipifp != NULL)
15195                         *ipifp = ipif;
15196                 else
15197                         ipif_refrele(ipif);
15198                 return (B_TRUE);
15199         }
15200 
15201         ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15202             *v4srcp));
15203         return (B_FALSE);
15204 }
15205 
15206 /*
15207  * Transport protocol call back function for CPU state change.
15208  */
15209 /* ARGSUSED */
15210 static int
15211 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15212 {
15213         processorid_t cpu_seqid;
15214         netstack_handle_t nh;
15215         netstack_t *ns;
15216 
15217         ASSERT(MUTEX_HELD(&cpu_lock));
15218 
15219         switch (what) {
15220         case CPU_CONFIG:
15221         case CPU_ON:
15222         case CPU_INIT:
15223         case CPU_CPUPART_IN:
15224                 cpu_seqid = cpu[id]->cpu_seqid;
15225                 netstack_next_init(&nh);
15226                 while ((ns = netstack_next(&nh)) != NULL) {
15227                         tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15228                         sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15229                         udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15230                         netstack_rele(ns);
15231                 }
15232                 netstack_next_fini(&nh);
15233                 break;
15234         case CPU_UNCONFIG:
15235         case CPU_OFF:
15236         case CPU_CPUPART_OUT:
15237                 /*
15238                  * Nothing to do.  We don't remove the per CPU stats from
15239                  * the IP stack even when the CPU goes offline.
15240                  */
15241                 break;
15242         default:
15243                 break;
15244         }
15245         return (0);
15246 }