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) 2018 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 
  99 #include <net/pfkeyv2.h>
 100 #include <inet/sadb.h>
 101 #include <inet/ipsec_impl.h>
 102 #include <inet/iptun/iptun_impl.h>
 103 #include <inet/ipdrop.h>
 104 #include <inet/ip_netinfo.h>
 105 #include <inet/ilb_ip.h>
 106 
 107 #include <sys/ethernet.h>
 108 #include <net/if_types.h>
 109 #include <sys/cpuvar.h>
 110 
 111 #include <ipp/ipp.h>
 112 #include <ipp/ipp_impl.h>
 113 #include <ipp/ipgpc/ipgpc.h>
 114 
 115 #include <sys/pattr.h>
 116 #include <inet/ipclassifier.h>
 117 #include <inet/sctp_ip.h>
 118 #include <inet/sctp/sctp_impl.h>
 119 #include <inet/udp_impl.h>
 120 #include <inet/rawip_impl.h>
 121 #include <inet/rts_impl.h>
 122 
 123 #include <sys/tsol/label.h>
 124 #include <sys/tsol/tnet.h>
 125 
 126 #include <sys/squeue_impl.h>
 127 #include <inet/ip_arp.h>
 128 
 129 #include <sys/clock_impl.h>       /* For LBOLT_FASTPATH{,64} */
 130 
 131 /*
 132  * Values for squeue switch:
 133  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
 134  * IP_SQUEUE_ENTER: SQ_PROCESS
 135  * IP_SQUEUE_FILL: SQ_FILL
 136  */
 137 int ip_squeue_enter = IP_SQUEUE_ENTER;  /* Setable in /etc/system */
 138 
 139 int ip_squeue_flag;
 140 
 141 /*
 142  * Setable in /etc/system
 143  */
 144 int ip_poll_normal_ms = 100;
 145 int ip_poll_normal_ticks = 0;
 146 int ip_modclose_ackwait_ms = 3000;
 147 
 148 /*
 149  * It would be nice to have these present only in DEBUG systems, but the
 150  * current design of the global symbol checking logic requires them to be
 151  * unconditionally present.
 152  */
 153 uint_t ip_thread_data;                  /* TSD key for debug support */
 154 krwlock_t ip_thread_rwlock;
 155 list_t  ip_thread_list;
 156 
 157 /*
 158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
 159  */
 160 
 161 struct listptr_s {
 162         mblk_t  *lp_head;       /* pointer to the head of the list */
 163         mblk_t  *lp_tail;       /* pointer to the tail of the list */
 164 };
 165 
 166 typedef struct listptr_s listptr_t;
 167 
 168 /*
 169  * This is used by ip_snmp_get_mib2_ip_route_media and
 170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
 171  */
 172 typedef struct iproutedata_s {
 173         uint_t          ird_idx;
 174         uint_t          ird_flags;      /* see below */
 175         listptr_t       ird_route;      /* ipRouteEntryTable */
 176         listptr_t       ird_netmedia;   /* ipNetToMediaEntryTable */
 177         listptr_t       ird_attrs;      /* ipRouteAttributeTable */
 178 } iproutedata_t;
 179 
 180 /* Include ire_testhidden and IRE_IF_CLONE routes */
 181 #define IRD_REPORT_ALL  0x01
 182 
 183 /*
 184  * Cluster specific hooks. These should be NULL when booted as a non-cluster
 185  */
 186 
 187 /*
 188  * Hook functions to enable cluster networking
 189  * On non-clustered systems these vectors must always be NULL.
 190  *
 191  * Hook function to Check ip specified ip address is a shared ip address
 192  * in the cluster
 193  *
 194  */
 195 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
 196     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
 197 
 198 /*
 199  * Hook function to generate cluster wide ip fragment identifier
 200  */
 201 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
 202     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
 203     void *args) = NULL;
 204 
 205 /*
 206  * Hook function to generate cluster wide SPI.
 207  */
 208 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
 209     void *) = NULL;
 210 
 211 /*
 212  * Hook function to verify if the SPI is already utlized.
 213  */
 214 
 215 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
 216 
 217 /*
 218  * Hook function to delete the SPI from the cluster wide repository.
 219  */
 220 
 221 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
 222 
 223 /*
 224  * Hook function to inform the cluster when packet received on an IDLE SA
 225  */
 226 
 227 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
 228     in6_addr_t, in6_addr_t, void *) = NULL;
 229 
 230 /*
 231  * Synchronization notes:
 232  *
 233  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
 234  * MT level protection given by STREAMS. IP uses a combination of its own
 235  * internal serialization mechanism and standard Solaris locking techniques.
 236  * The internal serialization is per phyint.  This is used to serialize
 237  * plumbing operations, IPMP operations, most set ioctls, etc.
 238  *
 239  * Plumbing is a long sequence of operations involving message
 240  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
 241  * involved in plumbing operations. A natural model is to serialize these
 242  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
 243  * parallel without any interference. But various set ioctls on hme0 are best
 244  * serialized, along with IPMP operations and processing of DLPI control
 245  * messages received from drivers on a per phyint basis. This serialization is
 246  * provided by the ipsq_t and primitives operating on this. Details can
 247  * be found in ip_if.c above the core primitives operating on ipsq_t.
 248  *
 249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
 250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
 251  * In addition ipif's and ill's referenced by the ire are also indirectly
 252  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
 253  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
 254  * address of an ipif has to go through the ipsq_t. This ensures that only
 255  * one such exclusive operation proceeds at any time on the ipif. It then
 256  * waits for all refcnts
 257  * associated with this ipif to come down to zero. The address is changed
 258  * only after the ipif has been quiesced. Then the ipif is brought up again.
 259  * More details are described above the comment in ip_sioctl_flags.
 260  *
 261  * Packet processing is based mostly on IREs and are fully multi-threaded
 262  * using standard Solaris MT techniques.
 263  *
 264  * There are explicit locks in IP to handle:
 265  * - The ip_g_head list maintained by mi_open_link() and friends.
 266  *
 267  * - The reassembly data structures (one lock per hash bucket)
 268  *
 269  * - conn_lock is meant to protect conn_t fields. The fields actually
 270  *   protected by conn_lock are documented in the conn_t definition.
 271  *
 272  * - ire_lock to protect some of the fields of the ire, IRE tables
 273  *   (one lock per hash bucket). Refer to ip_ire.c for details.
 274  *
 275  * - ndp_g_lock and ncec_lock for protecting NCEs.
 276  *
 277  * - ill_lock protects fields of the ill and ipif. Details in ip.h
 278  *
 279  * - ill_g_lock: This is a global reader/writer lock. Protects the following
 280  *      * The AVL tree based global multi list of all ills.
 281  *      * The linked list of all ipifs of an ill
 282  *      * The <ipsq-xop> mapping
 283  *      * <ill-phyint> association
 284  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
 285  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
 286  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
 287  *   writer for the actual duration of the insertion/deletion/change.
 288  *
 289  * - ill_lock:  This is a per ill mutex.
 290  *   It protects some members of the ill_t struct; see ip.h for details.
 291  *   It also protects the <ill-phyint> assoc.
 292  *   It also protects the list of ipifs hanging off the ill.
 293  *
 294  * - ipsq_lock: This is a per ipsq_t mutex lock.
 295  *   This protects some members of the ipsq_t struct; see ip.h for details.
 296  *   It also protects the <ipsq-ipxop> mapping
 297  *
 298  * - ipx_lock: This is a per ipxop_t mutex lock.
 299  *   This protects some members of the ipxop_t struct; see ip.h for details.
 300  *
 301  * - phyint_lock: This is a per phyint mutex lock. Protects just the
 302  *   phyint_flags
 303  *
 304  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
 305  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
 306  *   uniqueness check also done atomically.
 307  *
 308  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
 309  *   group list linked by ill_usesrc_grp_next. It also protects the
 310  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
 311  *   group is being added or deleted.  This lock is taken as a reader when
 312  *   walking the list/group(eg: to get the number of members in a usesrc group).
 313  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
 314  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
 315  *   example, it is not necessary to take this lock in the initial portion
 316  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
 317  *   operations are executed exclusively and that ensures that the "usesrc
 318  *   group state" cannot change. The "usesrc group state" change can happen
 319  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
 320  *
 321  * Changing <ill-phyint>, <ipsq-xop> assocications:
 322  *
 323  * To change the <ill-phyint> association, the ill_g_lock must be held
 324  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
 325  * must be held.
 326  *
 327  * To change the <ipsq-xop> association, the ill_g_lock must be held as
 328  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
 329  * This is only done when ills are added or removed from IPMP groups.
 330  *
 331  * To add or delete an ipif from the list of ipifs hanging off the ill,
 332  * ill_g_lock (writer) and ill_lock must be held and the thread must be
 333  * a writer on the associated ipsq.
 334  *
 335  * To add or delete an ill to the system, the ill_g_lock must be held as
 336  * writer and the thread must be a writer on the associated ipsq.
 337  *
 338  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
 339  * must be a writer on the associated ipsq.
 340  *
 341  * Lock hierarchy
 342  *
 343  * Some lock hierarchy scenarios are listed below.
 344  *
 345  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
 346  * ill_g_lock -> ill_lock(s) -> phyint_lock
 347  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
 348  * ill_g_lock -> ip_addr_avail_lock
 349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
 350  * ill_g_lock -> ip_g_nd_lock
 351  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
 352  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
 353  * arl_lock -> ill_lock
 354  * ips_ire_dep_lock -> irb_lock
 355  *
 356  * When more than 1 ill lock is needed to be held, all ill lock addresses
 357  * are sorted on address and locked starting from highest addressed lock
 358  * downward.
 359  *
 360  * Multicast scenarios
 361  * ips_ill_g_lock -> ill_mcast_lock
 362  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
 363  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
 364  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
 365  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
 366  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
 367  *
 368  * IPsec scenarios
 369  *
 370  * ipsa_lock -> ill_g_lock -> ill_lock
 371  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
 372  *
 373  * Trusted Solaris scenarios
 374  *
 375  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
 376  * igsa_lock -> gcdb_lock
 377  * gcgrp_rwlock -> ire_lock
 378  * gcgrp_rwlock -> gcdb_lock
 379  *
 380  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
 381  *
 382  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
 383  * sq_lock -> conn_lock -> QLOCK(q)
 384  * ill_lock -> ft_lock -> fe_lock
 385  *
 386  * Routing/forwarding table locking notes:
 387  *
 388  * Lock acquisition order: Radix tree lock, irb_lock.
 389  * Requirements:
 390  * i.  Walker must not hold any locks during the walker callback.
 391  * ii  Walker must not see a truncated tree during the walk because of any node
 392  *     deletion.
 393  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
 394  *     in many places in the code to walk the irb list. Thus even if all the
 395  *     ires in a bucket have been deleted, we still can't free the radix node
 396  *     until the ires have actually been inactive'd (freed).
 397  *
 398  * Tree traversal - Need to hold the global tree lock in read mode.
 399  * Before dropping the global tree lock, need to either increment the ire_refcnt
 400  * to ensure that the radix node can't be deleted.
 401  *
 402  * Tree add - Need to hold the global tree lock in write mode to add a
 403  * radix node. To prevent the node from being deleted, increment the
 404  * irb_refcnt, after the node is added to the tree. The ire itself is
 405  * added later while holding the irb_lock, but not the tree lock.
 406  *
 407  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
 408  * All associated ires must be inactive (i.e. freed), and irb_refcnt
 409  * must be zero.
 410  *
 411  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
 412  * global tree lock (read mode) for traversal.
 413  *
 414  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
 415  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
 416  *
 417  * IPsec notes :
 418  *
 419  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
 420  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
 421  * ip_xmit_attr_t has the
 422  * information used by the IPsec code for applying the right level of
 423  * protection. The information initialized by IP in the ip_xmit_attr_t
 424  * is determined by the per-socket policy or global policy in the system.
 425  * For inbound datagrams, the ip_recv_attr_t
 426  * starts out with nothing in it. It gets filled
 427  * with the right information if it goes through the AH/ESP code, which
 428  * happens if the incoming packet is secure. The information initialized
 429  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
 430  * the policy requirements needed by per-socket policy or global policy
 431  * is met or not.
 432  *
 433  * For fully connected sockets i.e dst, src [addr, port] is known,
 434  * conn_policy_cached is set indicating that policy has been cached.
 435  * conn_in_enforce_policy may or may not be set depending on whether
 436  * there is a global policy match or per-socket policy match.
 437  * Policy inheriting happpens in ip_policy_set once the destination is known.
 438  * Once the right policy is set on the conn_t, policy cannot change for
 439  * this socket. This makes life simpler for TCP (UDP ?) where
 440  * re-transmissions go out with the same policy. For symmetry, policy
 441  * is cached for fully connected UDP sockets also. Thus if policy is cached,
 442  * it also implies that policy is latched i.e policy cannot change
 443  * on these sockets. As we have the right policy on the conn, we don't
 444  * have to lookup global policy for every outbound and inbound datagram
 445  * and thus serving as an optimization. Note that a global policy change
 446  * does not affect fully connected sockets if they have policy. If fully
 447  * connected sockets did not have any policy associated with it, global
 448  * policy change may affect them.
 449  *
 450  * IP Flow control notes:
 451  * ---------------------
 452  * Non-TCP streams are flow controlled by IP. The way this is accomplished
 453  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
 454  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
 455  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
 456  * functions.
 457  *
 458  * Per Tx ring udp flow control:
 459  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
 460  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
 461  *
 462  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
 463  * To achieve best performance, outgoing traffic need to be fanned out among
 464  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
 465  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
 466  * the address of connp as fanout hint to mac_tx(). Under flow controlled
 467  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
 468  * cookie points to a specific Tx ring that is blocked. The cookie is used to
 469  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
 470  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
 471  * connp's. The drain list is not a single list but a configurable number of
 472  * lists.
 473  *
 474  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
 475  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
 476  * which is equal to 128. This array in turn contains a pointer to idl_t[],
 477  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
 478  * list will point to the list of connp's that are flow controlled.
 479  *
 480  *                      ---------------   -------   -------   -------
 481  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 482  *                   |  ---------------   -------   -------   -------
 483  *                   |  ---------------   -------   -------   -------
 484  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 485  * ----------------  |  ---------------   -------   -------   -------
 486  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
 487  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
 488  *                   |  ---------------   -------   -------   -------
 489  *                   .        .              .         .         .
 490  *                   |  ---------------   -------   -------   -------
 491  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 492  *                      ---------------   -------   -------   -------
 493  *                      ---------------   -------   -------   -------
 494  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 495  *                   |  ---------------   -------   -------   -------
 496  *                   |  ---------------   -------   -------   -------
 497  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 498  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
 499  * ----------------  |        .              .         .         .
 500  *                   |  ---------------   -------   -------   -------
 501  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 502  *                      ---------------   -------   -------   -------
 503  *     .....
 504  * ----------------
 505  * |idl_tx_list[n]|-> ...
 506  * ----------------
 507  *
 508  * When mac_tx() returns a cookie, the cookie is hashed into an index into
 509  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
 510  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
 511  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
 512  * Further, conn_blocked is set to indicate that the conn is blocked.
 513  *
 514  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
 515  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
 516  * is again hashed to locate the appropriate idl_tx_list, which is then
 517  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
 518  * the drain list and calls conn_drain_remove() to clear flow control (via
 519  * calling su_txq_full() or clearing QFULL), and remove the conn from the
 520  * drain list.
 521  *
 522  * Note that the drain list is not a single list but a (configurable) array of
 523  * lists (8 elements by default).  Synchronization between drain insertion and
 524  * flow control wakeup is handled by using idl_txl->txl_lock, and only
 525  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
 526  *
 527  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
 528  * On the send side, if the packet cannot be sent down to the driver by IP
 529  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
 530  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
 531  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
 532  * control has been relieved, the blocked conns in the 0'th drain list are
 533  * drained as in the non-STREAMS case.
 534  *
 535  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
 536  * is done when the conn is inserted into the drain list (conn_drain_insert())
 537  * and cleared when the conn is removed from the it (conn_drain_remove()).
 538  *
 539  * IPQOS notes:
 540  *
 541  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
 542  * and IPQoS modules. IPPF includes hooks in IP at different control points
 543  * (callout positions) which direct packets to IPQoS modules for policy
 544  * processing. Policies, if present, are global.
 545  *
 546  * The callout positions are located in the following paths:
 547  *              o local_in (packets destined for this host)
 548  *              o local_out (packets orginating from this host )
 549  *              o fwd_in  (packets forwarded by this m/c - inbound)
 550  *              o fwd_out (packets forwarded by this m/c - outbound)
 551  * Hooks at these callout points can be enabled/disabled using the ndd variable
 552  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
 553  * By default all the callout positions are enabled.
 554  *
 555  * Outbound (local_out)
 556  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
 557  *
 558  * Inbound (local_in)
 559  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
 560  *
 561  * Forwarding (in and out)
 562  * Hooks are placed in ire_recv_forward_v4/v6.
 563  *
 564  * IP Policy Framework processing (IPPF processing)
 565  * Policy processing for a packet is initiated by ip_process, which ascertains
 566  * that the classifier (ipgpc) is loaded and configured, failing which the
 567  * packet resumes normal processing in IP. If the clasifier is present, the
 568  * packet is acted upon by one or more IPQoS modules (action instances), per
 569  * filters configured in ipgpc and resumes normal IP processing thereafter.
 570  * An action instance can drop a packet in course of its processing.
 571  *
 572  * Zones notes:
 573  *
 574  * The partitioning rules for networking are as follows:
 575  * 1) Packets coming from a zone must have a source address belonging to that
 576  * zone.
 577  * 2) Packets coming from a zone can only be sent on a physical interface on
 578  * which the zone has an IP address.
 579  * 3) Between two zones on the same machine, packet delivery is only allowed if
 580  * there's a matching route for the destination and zone in the forwarding
 581  * table.
 582  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
 583  * different zones can bind to the same port with the wildcard address
 584  * (INADDR_ANY).
 585  *
 586  * The granularity of interface partitioning is at the logical interface level.
 587  * Therefore, every zone has its own IP addresses, and incoming packets can be
 588  * attributed to a zone unambiguously. A logical interface is placed into a zone
 589  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
 590  * structure. Rule (1) is implemented by modifying the source address selection
 591  * algorithm so that the list of eligible addresses is filtered based on the
 592  * sending process zone.
 593  *
 594  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
 595  * across all zones, depending on their type. Here is the break-up:
 596  *
 597  * IRE type                             Shared/exclusive
 598  * --------                             ----------------
 599  * IRE_BROADCAST                        Exclusive
 600  * IRE_DEFAULT (default routes)         Shared (*)
 601  * IRE_LOCAL                            Exclusive (x)
 602  * IRE_LOOPBACK                         Exclusive
 603  * IRE_PREFIX (net routes)              Shared (*)
 604  * IRE_IF_NORESOLVER (interface routes) Exclusive
 605  * IRE_IF_RESOLVER (interface routes)   Exclusive
 606  * IRE_IF_CLONE (interface routes)      Exclusive
 607  * IRE_HOST (host routes)               Shared (*)
 608  *
 609  * (*) A zone can only use a default or off-subnet route if the gateway is
 610  * directly reachable from the zone, that is, if the gateway's address matches
 611  * one of the zone's logical interfaces.
 612  *
 613  * (x) IRE_LOCAL are handled a bit differently.
 614  * When ip_restrict_interzone_loopback is set (the default),
 615  * ire_route_recursive restricts loopback using an IRE_LOCAL
 616  * between zone to the case when L2 would have conceptually looped the packet
 617  * back, i.e. the loopback which is required since neither Ethernet drivers
 618  * nor Ethernet hardware loops them back. This is the case when the normal
 619  * routes (ignoring IREs with different zoneids) would send out the packet on
 620  * the same ill as the ill with which is IRE_LOCAL is associated.
 621  *
 622  * Multiple zones can share a common broadcast address; typically all zones
 623  * share the 255.255.255.255 address. Incoming as well as locally originated
 624  * broadcast packets must be dispatched to all the zones on the broadcast
 625  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
 626  * since some zones may not be on the 10.16.72/24 network. To handle this, each
 627  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
 628  * sent to every zone that has an IRE_BROADCAST entry for the destination
 629  * address on the input ill, see ip_input_broadcast().
 630  *
 631  * Applications in different zones can join the same multicast group address.
 632  * The same logic applies for multicast as for broadcast. ip_input_multicast
 633  * dispatches packets to all zones that have members on the physical interface.
 634  */
 635 
 636 /*
 637  * Squeue Fanout flags:
 638  *      0: No fanout.
 639  *      1: Fanout across all squeues
 640  */
 641 boolean_t       ip_squeue_fanout = 0;
 642 
 643 /*
 644  * Maximum dups allowed per packet.
 645  */
 646 uint_t ip_max_frag_dups = 10;
 647 
 648 static int      ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
 649                     cred_t *credp, boolean_t isv6);
 650 static mblk_t   *ip_xmit_attach_llhdr(mblk_t *, nce_t *);
 651 
 652 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
 653 static void     icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
 654 static void     icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
 655     ip_recv_attr_t *);
 656 static void     icmp_options_update(ipha_t *);
 657 static void     icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
 658 static void     icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
 659 static mblk_t   *icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
 660 static void     icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
 661     ip_recv_attr_t *);
 662 static void     icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
 663 static void     icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
 664     ip_recv_attr_t *);
 665 
 666 mblk_t          *ip_dlpi_alloc(size_t, t_uscalar_t);
 667 char            *ip_dot_addr(ipaddr_t, char *);
 668 mblk_t          *ip_carve_mp(mblk_t **, ssize_t);
 669 int             ip_close(queue_t *, int);
 670 static char     *ip_dot_saddr(uchar_t *, char *);
 671 static void     ip_lrput(queue_t *, mblk_t *);
 672 ipaddr_t        ip_net_mask(ipaddr_t);
 673 char            *ip_nv_lookup(nv_t *, int);
 674 void    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 int      ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
 711 static int      ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
 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         (pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1189         &ip_mod_info
1190 };
1191 
1192 struct qinit iprinitv6 = {
1193         (pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1194         &ip_mod_info
1195 };
1196 
1197 static struct qinit ipwinit = {
1198         (pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1199         &ip_mod_info
1200 };
1201 
1202 static struct qinit iplrinit = {
1203         (pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1204         &ip_mod_info
1205 };
1206 
1207 static struct qinit iplwinit = {
1208         (pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1209         &ip_mod_info
1210 };
1211 
1212 /* For AF_INET aka /dev/ip */
1213 struct streamtab ipinfov4 = {
1214         &iprinitv4, &ipwinit, &iplrinit, &iplwinit
1215 };
1216 
1217 /* For AF_INET6 aka /dev/ip6 */
1218 struct streamtab ipinfov6 = {
1219         &iprinitv6, &ipwinit, &iplrinit, &iplwinit
1220 };
1221 
1222 #ifdef  DEBUG
1223 boolean_t skip_sctp_cksum = B_FALSE;
1224 #endif
1225 
1226 /*
1227  * Generate an ICMP fragmentation needed message.
1228  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1229  * constructed by the caller.
1230  */
1231 void
1232 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1233 {
1234         icmph_t icmph;
1235         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
1236 
1237         mp = icmp_pkt_err_ok(mp, ira);
1238         if (mp == NULL)
1239                 return;
1240 
1241         bzero(&icmph, sizeof (icmph_t));
1242         icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1243         icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1244         icmph.icmph_du_mtu = htons((uint16_t)mtu);
1245         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1246         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1247 
1248         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1249 }
1250 
1251 /*
1252  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1253  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1254  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1255  * Likewise, if the ICMP error is misformed (too short, etc), then it
1256  * returns NULL. The caller uses this to determine whether or not to send
1257  * to raw sockets.
1258  *
1259  * All error messages are passed to the matching transport stream.
1260  *
1261  * The following cases are handled by icmp_inbound:
1262  * 1) It needs to send a reply back and possibly delivering it
1263  *    to the "interested" upper clients.
1264  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1265  * 3) It needs to change some values in IP only.
1266  * 4) It needs to change some values in IP and upper layers e.g TCP
1267  *    by delivering an error to the upper layers.
1268  *
1269  * We handle the above three cases in the context of IPsec in the
1270  * following way :
1271  *
1272  * 1) Send the reply back in the same way as the request came in.
1273  *    If it came in encrypted, it goes out encrypted. If it came in
1274  *    clear, it goes out in clear. Thus, this will prevent chosen
1275  *    plain text attack.
1276  * 2) The client may or may not expect things to come in secure.
1277  *    If it comes in secure, the policy constraints are checked
1278  *    before delivering it to the upper layers. If it comes in
1279  *    clear, ipsec_inbound_accept_clear will decide whether to
1280  *    accept this in clear or not. In both the cases, if the returned
1281  *    message (IP header + 8 bytes) that caused the icmp message has
1282  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1283  *    sending up. If there are only 8 bytes of returned message, then
1284  *    upper client will not be notified.
1285  * 3) Check with global policy to see whether it matches the constaints.
1286  *    But this will be done only if icmp_accept_messages_in_clear is
1287  *    zero.
1288  * 4) If we need to change both in IP and ULP, then the decision taken
1289  *    while affecting the values in IP and while delivering up to TCP
1290  *    should be the same.
1291  *
1292  *      There are two cases.
1293  *
1294  *      a) If we reject data at the IP layer (ipsec_check_global_policy()
1295  *         failed), we will not deliver it to the ULP, even though they
1296  *         are *willing* to accept in *clear*. This is fine as our global
1297  *         disposition to icmp messages asks us reject the datagram.
1298  *
1299  *      b) If we accept data at the IP layer (ipsec_check_global_policy()
1300  *         succeeded or icmp_accept_messages_in_clear is 1), and not able
1301  *         to deliver it to ULP (policy failed), it can lead to
1302  *         consistency problems. The cases known at this time are
1303  *         ICMP_DESTINATION_UNREACHABLE  messages with following code
1304  *         values :
1305  *
1306  *         - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1307  *           and Upper layer rejects. Then the communication will
1308  *           come to a stop. This is solved by making similar decisions
1309  *           at both levels. Currently, when we are unable to deliver
1310  *           to the Upper Layer (due to policy failures) while IP has
1311  *           adjusted dce_pmtu, the next outbound datagram would
1312  *           generate a local ICMP_FRAGMENTATION_NEEDED message - which
1313  *           will be with the right level of protection. Thus the right
1314  *           value will be communicated even if we are not able to
1315  *           communicate when we get from the wire initially. But this
1316  *           assumes there would be at least one outbound datagram after
1317  *           IP has adjusted its dce_pmtu value. To make things
1318  *           simpler, we accept in clear after the validation of
1319  *           AH/ESP headers.
1320  *
1321  *         - Other ICMP ERRORS : We may not be able to deliver it to the
1322  *           upper layer depending on the level of protection the upper
1323  *           layer expects and the disposition in ipsec_inbound_accept_clear().
1324  *           ipsec_inbound_accept_clear() decides whether a given ICMP error
1325  *           should be accepted in clear when the Upper layer expects secure.
1326  *           Thus the communication may get aborted by some bad ICMP
1327  *           packets.
1328  */
1329 mblk_t *
1330 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1331 {
1332         icmph_t         *icmph;
1333         ipha_t          *ipha;          /* Outer header */
1334         int             ip_hdr_length;  /* Outer header length */
1335         boolean_t       interested;
1336         ipif_t          *ipif;
1337         uint32_t        ts;
1338         uint32_t        *tsp;
1339         timestruc_t     now;
1340         ill_t           *ill = ira->ira_ill;
1341         ip_stack_t      *ipst = ill->ill_ipst;
1342         zoneid_t        zoneid = ira->ira_zoneid;
1343         int             len_needed;
1344         mblk_t          *mp_ret = NULL;
1345 
1346         ipha = (ipha_t *)mp->b_rptr;
1347 
1348         BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1349 
1350         ip_hdr_length = ira->ira_ip_hdr_length;
1351         if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1352                 if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1353                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1354                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1355                         freemsg(mp);
1356                         return (NULL);
1357                 }
1358                 /* Last chance to get real. */
1359                 ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1360                 if (ipha == NULL) {
1361                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1362                         freemsg(mp);
1363                         return (NULL);
1364                 }
1365         }
1366 
1367         /* The IP header will always be a multiple of four bytes */
1368         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1369         ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1370             icmph->icmph_code));
1371 
1372         /*
1373          * We will set "interested" to "true" if we should pass a copy to
1374          * the transport or if we handle the packet locally.
1375          */
1376         interested = B_FALSE;
1377         switch (icmph->icmph_type) {
1378         case ICMP_ECHO_REPLY:
1379                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1380                 break;
1381         case ICMP_DEST_UNREACHABLE:
1382                 if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1383                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1384                 interested = B_TRUE;    /* Pass up to transport */
1385                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1386                 break;
1387         case ICMP_SOURCE_QUENCH:
1388                 interested = B_TRUE;    /* Pass up to transport */
1389                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1390                 break;
1391         case ICMP_REDIRECT:
1392                 if (!ipst->ips_ip_ignore_redirect)
1393                         interested = B_TRUE;
1394                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1395                 break;
1396         case ICMP_ECHO_REQUEST:
1397                 /*
1398                  * Whether to respond to echo requests that come in as IP
1399                  * broadcasts or as IP multicast is subject to debate
1400                  * (what isn't?).  We aim to please, you pick it.
1401                  * Default is do it.
1402                  */
1403                 if (ira->ira_flags & IRAF_MULTICAST) {
1404                         /* multicast: respond based on tunable */
1405                         interested = ipst->ips_ip_g_resp_to_echo_mcast;
1406                 } else if (ira->ira_flags & IRAF_BROADCAST) {
1407                         /* broadcast: respond based on tunable */
1408                         interested = ipst->ips_ip_g_resp_to_echo_bcast;
1409                 } else {
1410                         /* unicast: always respond */
1411                         interested = B_TRUE;
1412                 }
1413                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1414                 if (!interested) {
1415                         /* We never pass these to RAW sockets */
1416                         freemsg(mp);
1417                         return (NULL);
1418                 }
1419 
1420                 /* Check db_ref to make sure we can modify the packet. */
1421                 if (mp->b_datap->db_ref > 1) {
1422                         mblk_t  *mp1;
1423 
1424                         mp1 = copymsg(mp);
1425                         freemsg(mp);
1426                         if (!mp1) {
1427                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1428                                 return (NULL);
1429                         }
1430                         mp = mp1;
1431                         ipha = (ipha_t *)mp->b_rptr;
1432                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1433                 }
1434                 icmph->icmph_type = ICMP_ECHO_REPLY;
1435                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1436                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1437                 return (NULL);
1438 
1439         case ICMP_ROUTER_ADVERTISEMENT:
1440         case ICMP_ROUTER_SOLICITATION:
1441                 break;
1442         case ICMP_TIME_EXCEEDED:
1443                 interested = B_TRUE;    /* Pass up to transport */
1444                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1445                 break;
1446         case ICMP_PARAM_PROBLEM:
1447                 interested = B_TRUE;    /* Pass up to transport */
1448                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1449                 break;
1450         case ICMP_TIME_STAMP_REQUEST:
1451                 /* Response to Time Stamp Requests is local policy. */
1452                 if (ipst->ips_ip_g_resp_to_timestamp) {
1453                         if (ira->ira_flags & IRAF_MULTIBROADCAST)
1454                                 interested =
1455                                     ipst->ips_ip_g_resp_to_timestamp_bcast;
1456                         else
1457                                 interested = B_TRUE;
1458                 }
1459                 if (!interested) {
1460                         /* We never pass these to RAW sockets */
1461                         freemsg(mp);
1462                         return (NULL);
1463                 }
1464 
1465                 /* Make sure we have enough of the packet */
1466                 len_needed = ip_hdr_length + ICMPH_SIZE +
1467                     3 * sizeof (uint32_t);
1468 
1469                 if (mp->b_wptr - mp->b_rptr < len_needed) {
1470                         ipha = ip_pullup(mp, len_needed, ira);
1471                         if (ipha == NULL) {
1472                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1473                                 ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1474                                     mp, ill);
1475                                 freemsg(mp);
1476                                 return (NULL);
1477                         }
1478                         /* Refresh following the pullup. */
1479                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1480                 }
1481                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1482                 /* Check db_ref to make sure we can modify the packet. */
1483                 if (mp->b_datap->db_ref > 1) {
1484                         mblk_t  *mp1;
1485 
1486                         mp1 = copymsg(mp);
1487                         freemsg(mp);
1488                         if (!mp1) {
1489                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1490                                 return (NULL);
1491                         }
1492                         mp = mp1;
1493                         ipha = (ipha_t *)mp->b_rptr;
1494                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1495                 }
1496                 icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1497                 tsp = (uint32_t *)&icmph[1];
1498                 tsp++;          /* Skip past 'originate time' */
1499                 /* Compute # of milliseconds since midnight */
1500                 gethrestime(&now);
1501                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1502                     NSEC2MSEC(now.tv_nsec);
1503                 *tsp++ = htonl(ts);     /* Lay in 'receive time' */
1504                 *tsp++ = htonl(ts);     /* Lay in 'send time' */
1505                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1506                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1507                 return (NULL);
1508 
1509         case ICMP_TIME_STAMP_REPLY:
1510                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1511                 break;
1512         case ICMP_INFO_REQUEST:
1513                 /* Per RFC 1122 3.2.2.7, ignore this. */
1514         case ICMP_INFO_REPLY:
1515                 break;
1516         case ICMP_ADDRESS_MASK_REQUEST:
1517                 if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1518                         interested =
1519                             ipst->ips_ip_respond_to_address_mask_broadcast;
1520                 } else {
1521                         interested = B_TRUE;
1522                 }
1523                 if (!interested) {
1524                         /* We never pass these to RAW sockets */
1525                         freemsg(mp);
1526                         return (NULL);
1527                 }
1528                 len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1529                 if (mp->b_wptr - mp->b_rptr < len_needed) {
1530                         ipha = ip_pullup(mp, len_needed, ira);
1531                         if (ipha == NULL) {
1532                                 BUMP_MIB(ill->ill_ip_mib,
1533                                     ipIfStatsInTruncatedPkts);
1534                                 ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1535                                     ill);
1536                                 freemsg(mp);
1537                                 return (NULL);
1538                         }
1539                         /* Refresh following the pullup. */
1540                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1541                 }
1542                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1543                 /* Check db_ref to make sure we can modify the packet. */
1544                 if (mp->b_datap->db_ref > 1) {
1545                         mblk_t  *mp1;
1546 
1547                         mp1 = copymsg(mp);
1548                         freemsg(mp);
1549                         if (!mp1) {
1550                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1551                                 return (NULL);
1552                         }
1553                         mp = mp1;
1554                         ipha = (ipha_t *)mp->b_rptr;
1555                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1556                 }
1557                 /*
1558                  * Need the ipif with the mask be the same as the source
1559                  * address of the mask reply. For unicast we have a specific
1560                  * ipif. For multicast/broadcast we only handle onlink
1561                  * senders, and use the source address to pick an ipif.
1562                  */
1563                 ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1564                 if (ipif == NULL) {
1565                         /* Broadcast or multicast */
1566                         ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1567                         if (ipif == NULL) {
1568                                 freemsg(mp);
1569                                 return (NULL);
1570                         }
1571                 }
1572                 icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1573                 bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1574                 ipif_refrele(ipif);
1575                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1576                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1577                 return (NULL);
1578 
1579         case ICMP_ADDRESS_MASK_REPLY:
1580                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1581                 break;
1582         default:
1583                 interested = B_TRUE;    /* Pass up to transport */
1584                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1585                 break;
1586         }
1587         /*
1588          * See if there is an ICMP client to avoid an extra copymsg/freemsg
1589          * if there isn't one.
1590          */
1591         if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1592                 /* If there is an ICMP client and we want one too, copy it. */
1593 
1594                 if (!interested) {
1595                         /* Caller will deliver to RAW sockets */
1596                         return (mp);
1597                 }
1598                 mp_ret = copymsg(mp);
1599                 if (mp_ret == NULL) {
1600                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1601                         ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1602                 }
1603         } else if (!interested) {
1604                 /* Neither we nor raw sockets are interested. Drop packet now */
1605                 freemsg(mp);
1606                 return (NULL);
1607         }
1608 
1609         /*
1610          * ICMP error or redirect packet. Make sure we have enough of
1611          * the header and that db_ref == 1 since we might end up modifying
1612          * the packet.
1613          */
1614         if (mp->b_cont != NULL) {
1615                 if (ip_pullup(mp, -1, ira) == NULL) {
1616                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1617                         ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1618                             mp, ill);
1619                         freemsg(mp);
1620                         return (mp_ret);
1621                 }
1622         }
1623 
1624         if (mp->b_datap->db_ref > 1) {
1625                 mblk_t  *mp1;
1626 
1627                 mp1 = copymsg(mp);
1628                 if (mp1 == NULL) {
1629                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1630                         ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1631                         freemsg(mp);
1632                         return (mp_ret);
1633                 }
1634                 freemsg(mp);
1635                 mp = mp1;
1636         }
1637 
1638         /*
1639          * In case mp has changed, verify the message before any further
1640          * processes.
1641          */
1642         ipha = (ipha_t *)mp->b_rptr;
1643         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1644         if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1645                 freemsg(mp);
1646                 return (mp_ret);
1647         }
1648 
1649         switch (icmph->icmph_type) {
1650         case ICMP_REDIRECT:
1651                 icmp_redirect_v4(mp, ipha, icmph, ira);
1652                 break;
1653         case ICMP_DEST_UNREACHABLE:
1654                 if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1655                         /* Update DCE and adjust MTU is icmp header if needed */
1656                         icmp_inbound_too_big_v4(icmph, ira);
1657                 }
1658                 /* FALLTHRU */
1659         default:
1660                 icmp_inbound_error_fanout_v4(mp, icmph, ira);
1661                 break;
1662         }
1663         return (mp_ret);
1664 }
1665 
1666 /*
1667  * Send an ICMP echo, timestamp or address mask reply.
1668  * The caller has already updated the payload part of the packet.
1669  * We handle the ICMP checksum, IP source address selection and feed
1670  * the packet into ip_output_simple.
1671  */
1672 static void
1673 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1674     ip_recv_attr_t *ira)
1675 {
1676         uint_t          ip_hdr_length = ira->ira_ip_hdr_length;
1677         ill_t           *ill = ira->ira_ill;
1678         ip_stack_t      *ipst = ill->ill_ipst;
1679         ip_xmit_attr_t  ixas;
1680 
1681         /* Send out an ICMP packet */
1682         icmph->icmph_checksum = 0;
1683         icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1684         /* Reset time to live. */
1685         ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1686         {
1687                 /* Swap source and destination addresses */
1688                 ipaddr_t tmp;
1689 
1690                 tmp = ipha->ipha_src;
1691                 ipha->ipha_src = ipha->ipha_dst;
1692                 ipha->ipha_dst = tmp;
1693         }
1694         ipha->ipha_ident = 0;
1695         if (!IS_SIMPLE_IPH(ipha))
1696                 icmp_options_update(ipha);
1697 
1698         bzero(&ixas, sizeof (ixas));
1699         ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1700         ixas.ixa_zoneid = ira->ira_zoneid;
1701         ixas.ixa_cred = kcred;
1702         ixas.ixa_cpid = NOPID;
1703         ixas.ixa_tsl = ira->ira_tsl; /* Behave as a multi-level responder */
1704         ixas.ixa_ifindex = 0;
1705         ixas.ixa_ipst = ipst;
1706         ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1707 
1708         if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1709                 /*
1710                  * This packet should go out the same way as it
1711                  * came in i.e in clear, independent of the IPsec policy
1712                  * for transmitting packets.
1713                  */
1714                 ixas.ixa_flags |= IXAF_NO_IPSEC;
1715         } else {
1716                 if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1717                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1718                         /* Note: mp already consumed and ip_drop_packet done */
1719                         return;
1720                 }
1721         }
1722         if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1723                 /*
1724                  * Not one or our addresses (IRE_LOCALs), thus we let
1725                  * ip_output_simple pick the source.
1726                  */
1727                 ipha->ipha_src = INADDR_ANY;
1728                 ixas.ixa_flags |= IXAF_SET_SOURCE;
1729         }
1730         /* Should we send with DF and use dce_pmtu? */
1731         if (ipst->ips_ipv4_icmp_return_pmtu) {
1732                 ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1733                 ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1734         }
1735 
1736         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1737 
1738         (void) ip_output_simple(mp, &ixas);
1739         ixa_cleanup(&ixas);
1740 }
1741 
1742 /*
1743  * Verify the ICMP messages for either for ICMP error or redirect packet.
1744  * The caller should have fully pulled up the message. If it's a redirect
1745  * packet, only basic checks on IP header will be done; otherwise, verify
1746  * the packet by looking at the included ULP header.
1747  *
1748  * Called before icmp_inbound_error_fanout_v4 is called.
1749  */
1750 static boolean_t
1751 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1752 {
1753         ill_t           *ill = ira->ira_ill;
1754         int             hdr_length;
1755         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
1756         conn_t          *connp;
1757         ipha_t          *ipha;  /* Inner IP header */
1758 
1759         ipha = (ipha_t *)&icmph[1];
1760         if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1761                 goto truncated;
1762 
1763         hdr_length = IPH_HDR_LENGTH(ipha);
1764 
1765         if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1766                 goto discard_pkt;
1767 
1768         if (hdr_length < sizeof (ipha_t))
1769                 goto truncated;
1770 
1771         if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1772                 goto truncated;
1773 
1774         /*
1775          * Stop here for ICMP_REDIRECT.
1776          */
1777         if (icmph->icmph_type == ICMP_REDIRECT)
1778                 return (B_TRUE);
1779 
1780         /*
1781          * ICMP errors only.
1782          */
1783         switch (ipha->ipha_protocol) {
1784         case IPPROTO_UDP:
1785                 /*
1786                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1787                  * transport header.
1788                  */
1789                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1790                     mp->b_wptr)
1791                         goto truncated;
1792                 break;
1793         case IPPROTO_TCP: {
1794                 tcpha_t         *tcpha;
1795 
1796                 /*
1797                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1798                  * transport header.
1799                  */
1800                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1801                     mp->b_wptr)
1802                         goto truncated;
1803 
1804                 tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1805                 connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1806                     ipst);
1807                 if (connp == NULL)
1808                         goto discard_pkt;
1809 
1810                 if ((connp->conn_verifyicmp != NULL) &&
1811                     !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1812                         CONN_DEC_REF(connp);
1813                         goto discard_pkt;
1814                 }
1815                 CONN_DEC_REF(connp);
1816                 break;
1817         }
1818         case IPPROTO_SCTP:
1819                 /*
1820                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1821                  * transport header.
1822                  */
1823                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1824                     mp->b_wptr)
1825                         goto truncated;
1826                 break;
1827         case IPPROTO_ESP:
1828         case IPPROTO_AH:
1829                 break;
1830         case IPPROTO_ENCAP:
1831                 if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1832                     mp->b_wptr)
1833                         goto truncated;
1834                 break;
1835         default:
1836                 break;
1837         }
1838 
1839         return (B_TRUE);
1840 
1841 discard_pkt:
1842         /* Bogus ICMP error. */
1843         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1844         return (B_FALSE);
1845 
1846 truncated:
1847         /* We pulled up everthing already. Must be truncated */
1848         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1849         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1850         return (B_FALSE);
1851 }
1852 
1853 /* Table from RFC 1191 */
1854 static int icmp_frag_size_table[] =
1855 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1856 
1857 /*
1858  * Process received ICMP Packet too big.
1859  * Just handles the DCE create/update, including using the above table of
1860  * PMTU guesses. The caller is responsible for validating the packet before
1861  * passing it in and also to fanout the ICMP error to any matching transport
1862  * conns. Assumes the message has been fully pulled up and verified.
1863  *
1864  * Before getting here, the caller has called icmp_inbound_verify_v4()
1865  * that should have verified with ULP to prevent undoing the changes we're
1866  * going to make to DCE. For example, TCP might have verified that the packet
1867  * which generated error is in the send window.
1868  *
1869  * In some cases modified this MTU in the ICMP header packet; the caller
1870  * should pass to the matching ULP after this returns.
1871  */
1872 static void
1873 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1874 {
1875         dce_t           *dce;
1876         int             old_mtu;
1877         int             mtu, orig_mtu;
1878         ipaddr_t        dst;
1879         boolean_t       disable_pmtud;
1880         ill_t           *ill = ira->ira_ill;
1881         ip_stack_t      *ipst = ill->ill_ipst;
1882         uint_t          hdr_length;
1883         ipha_t          *ipha;
1884 
1885         /* Caller already pulled up everything. */
1886         ipha = (ipha_t *)&icmph[1];
1887         ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1888             icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1889         ASSERT(ill != NULL);
1890 
1891         hdr_length = IPH_HDR_LENGTH(ipha);
1892 
1893         /*
1894          * We handle path MTU for source routed packets since the DCE
1895          * is looked up using the final destination.
1896          */
1897         dst = ip_get_dst(ipha);
1898 
1899         dce = dce_lookup_and_add_v4(dst, ipst);
1900         if (dce == NULL) {
1901                 /* Couldn't add a unique one - ENOMEM */
1902                 ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1903                     ntohl(dst)));
1904                 return;
1905         }
1906 
1907         /* Check for MTU discovery advice as described in RFC 1191 */
1908         mtu = ntohs(icmph->icmph_du_mtu);
1909         orig_mtu = mtu;
1910         disable_pmtud = B_FALSE;
1911 
1912         mutex_enter(&dce->dce_lock);
1913         if (dce->dce_flags & DCEF_PMTU)
1914                 old_mtu = dce->dce_pmtu;
1915         else
1916                 old_mtu = ill->ill_mtu;
1917 
1918         if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1919                 uint32_t length;
1920                 int     i;
1921 
1922                 /*
1923                  * Use the table from RFC 1191 to figure out
1924                  * the next "plateau" based on the length in
1925                  * the original IP packet.
1926                  */
1927                 length = ntohs(ipha->ipha_length);
1928                 DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1929                     uint32_t, length);
1930                 if (old_mtu <= length &&
1931                     old_mtu >= length - hdr_length) {
1932                         /*
1933                          * Handle broken BSD 4.2 systems that
1934                          * return the wrong ipha_length in ICMP
1935                          * errors.
1936                          */
1937                         ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1938                             length, old_mtu));
1939                         length -= hdr_length;
1940                 }
1941                 for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1942                         if (length > icmp_frag_size_table[i])
1943                                 break;
1944                 }
1945                 if (i == A_CNT(icmp_frag_size_table)) {
1946                         /* Smaller than IP_MIN_MTU! */
1947                         ip1dbg(("Too big for packet size %d\n",
1948                             length));
1949                         disable_pmtud = B_TRUE;
1950                         mtu = ipst->ips_ip_pmtu_min;
1951                 } else {
1952                         mtu = icmp_frag_size_table[i];
1953                         ip1dbg(("Calculated mtu %d, packet size %d, "
1954                             "before %d\n", mtu, length, old_mtu));
1955                         if (mtu < ipst->ips_ip_pmtu_min) {
1956                                 mtu = ipst->ips_ip_pmtu_min;
1957                                 disable_pmtud = B_TRUE;
1958                         }
1959                 }
1960         }
1961         if (disable_pmtud)
1962                 dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1963         else
1964                 dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1965 
1966         dce->dce_pmtu = MIN(old_mtu, mtu);
1967         /* Prepare to send the new max frag size for the ULP. */
1968         icmph->icmph_du_zero = 0;
1969         icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1970         DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1971             dce, int, orig_mtu, int, mtu);
1972 
1973         /* We now have a PMTU for sure */
1974         dce->dce_flags |= DCEF_PMTU;
1975         dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1976         mutex_exit(&dce->dce_lock);
1977         /*
1978          * After dropping the lock the new value is visible to everyone.
1979          * Then we bump the generation number so any cached values reinspect
1980          * the dce_t.
1981          */
1982         dce_increment_generation(dce);
1983         dce_refrele(dce);
1984 }
1985 
1986 /*
1987  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1988  * calls this function.
1989  */
1990 static mblk_t *
1991 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1992 {
1993         int length;
1994 
1995         ASSERT(mp->b_datap->db_type == M_DATA);
1996 
1997         /* icmp_inbound_v4 has already pulled up the whole error packet */
1998         ASSERT(mp->b_cont == NULL);
1999 
2000         /*
2001          * The length that we want to overlay is the inner header
2002          * and what follows it.
2003          */
2004         length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2005 
2006         /*
2007          * Overlay the inner header and whatever follows it over the
2008          * outer header.
2009          */
2010         bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2011 
2012         /* Adjust for what we removed */
2013         mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2014         return (mp);
2015 }
2016 
2017 /*
2018  * Try to pass the ICMP message upstream in case the ULP cares.
2019  *
2020  * If the packet that caused the ICMP error is secure, we send
2021  * it to AH/ESP to make sure that the attached packet has a
2022  * valid association. ipha in the code below points to the
2023  * IP header of the packet that caused the error.
2024  *
2025  * For IPsec cases, we let the next-layer-up (which has access to
2026  * cached policy on the conn_t, or can query the SPD directly)
2027  * subtract out any IPsec overhead if they must.  We therefore make no
2028  * adjustments here for IPsec overhead.
2029  *
2030  * IFN could have been generated locally or by some router.
2031  *
2032  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2033  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2034  *          This happens because IP adjusted its value of MTU on an
2035  *          earlier IFN message and could not tell the upper layer,
2036  *          the new adjusted value of MTU e.g. Packet was encrypted
2037  *          or there was not enough information to fanout to upper
2038  *          layers. Thus on the next outbound datagram, ire_send_wire
2039  *          generates the IFN, where IPsec processing has *not* been
2040  *          done.
2041  *
2042  *          Note that we retain ixa_fragsize across IPsec thus once
2043  *          we have picking ixa_fragsize and entered ipsec_out_process we do
2044  *          no change the fragsize even if the path MTU changes before
2045  *          we reach ip_output_post_ipsec.
2046  *
2047  *          In the local case, IRAF_LOOPBACK will be set indicating
2048  *          that IFN was generated locally.
2049  *
2050  * ROUTER : IFN could be secure or non-secure.
2051  *
2052  *          * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2053  *            packet in error has AH/ESP headers to validate the AH/ESP
2054  *            headers. AH/ESP will verify whether there is a valid SA or
2055  *            not and send it back. We will fanout again if we have more
2056  *            data in the packet.
2057  *
2058  *            If the packet in error does not have AH/ESP, we handle it
2059  *            like any other case.
2060  *
2061  *          * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2062  *            up to AH/ESP for validation. AH/ESP will verify whether there is a
2063  *            valid SA or not and send it back. We will fanout again if
2064  *            we have more data in the packet.
2065  *
2066  *            If the packet in error does not have AH/ESP, we handle it
2067  *            like any other case.
2068  *
2069  * The caller must have called icmp_inbound_verify_v4.
2070  */
2071 static void
2072 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2073 {
2074         uint16_t        *up;    /* Pointer to ports in ULP header */
2075         uint32_t        ports;  /* reversed ports for fanout */
2076         ipha_t          ripha;  /* With reversed addresses */
2077         ipha_t          *ipha;  /* Inner IP header */
2078         uint_t          hdr_length; /* Inner IP header length */
2079         tcpha_t         *tcpha;
2080         conn_t          *connp;
2081         ill_t           *ill = ira->ira_ill;
2082         ip_stack_t      *ipst = ill->ill_ipst;
2083         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
2084         ill_t           *rill = ira->ira_rill;
2085 
2086         /* Caller already pulled up everything. */
2087         ipha = (ipha_t *)&icmph[1];
2088         ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2089         ASSERT(mp->b_cont == NULL);
2090 
2091         hdr_length = IPH_HDR_LENGTH(ipha);
2092         ira->ira_protocol = ipha->ipha_protocol;
2093 
2094         /*
2095          * We need a separate IP header with the source and destination
2096          * addresses reversed to do fanout/classification because the ipha in
2097          * the ICMP error is in the form we sent it out.
2098          */
2099         ripha.ipha_src = ipha->ipha_dst;
2100         ripha.ipha_dst = ipha->ipha_src;
2101         ripha.ipha_protocol = ipha->ipha_protocol;
2102         ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2103 
2104         ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2105             ripha.ipha_protocol, ntohl(ipha->ipha_src),
2106             ntohl(ipha->ipha_dst),
2107             icmph->icmph_type, icmph->icmph_code));
2108 
2109         switch (ipha->ipha_protocol) {
2110         case IPPROTO_UDP:
2111                 up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2112 
2113                 /* Attempt to find a client stream based on port. */
2114                 ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2115                     ntohs(up[0]), ntohs(up[1])));
2116 
2117                 /* Note that we send error to all matches. */
2118                 ira->ira_flags |= IRAF_ICMP_ERROR;
2119                 ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2120                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2121                 return;
2122 
2123         case IPPROTO_TCP:
2124                 /*
2125                  * Find a TCP client stream for this packet.
2126                  * Note that we do a reverse lookup since the header is
2127                  * in the form we sent it out.
2128                  */
2129                 tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2130                 connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2131                     ipst);
2132                 if (connp == NULL)
2133                         goto discard_pkt;
2134 
2135                 if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2136                     (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2137                         mp = ipsec_check_inbound_policy(mp, connp,
2138                             ipha, NULL, ira);
2139                         if (mp == NULL) {
2140                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2141                                 /* Note that mp is NULL */
2142                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
2143                                 CONN_DEC_REF(connp);
2144                                 return;
2145                         }
2146                 }
2147 
2148                 ira->ira_flags |= IRAF_ICMP_ERROR;
2149                 ira->ira_ill = ira->ira_rill = NULL;
2150                 if (IPCL_IS_TCP(connp)) {
2151                         SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2152                             connp->conn_recvicmp, connp, ira, SQ_FILL,
2153                             SQTAG_TCP_INPUT_ICMP_ERR);
2154                 } else {
2155                         /* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2156                         (connp->conn_recv)(connp, mp, NULL, ira);
2157                         CONN_DEC_REF(connp);
2158                 }
2159                 ira->ira_ill = ill;
2160                 ira->ira_rill = rill;
2161                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2162                 return;
2163 
2164         case IPPROTO_SCTP:
2165                 up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2166                 /* Find a SCTP client stream for this packet. */
2167                 ((uint16_t *)&ports)[0] = up[1];
2168                 ((uint16_t *)&ports)[1] = up[0];
2169 
2170                 ira->ira_flags |= IRAF_ICMP_ERROR;
2171                 ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2172                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2173                 return;
2174 
2175         case IPPROTO_ESP:
2176         case IPPROTO_AH:
2177                 if (!ipsec_loaded(ipss)) {
2178                         ip_proto_not_sup(mp, ira);
2179                         return;
2180                 }
2181 
2182                 if (ipha->ipha_protocol == IPPROTO_ESP)
2183                         mp = ipsecesp_icmp_error(mp, ira);
2184                 else
2185                         mp = ipsecah_icmp_error(mp, ira);
2186                 if (mp == NULL)
2187                         return;
2188 
2189                 /* Just in case ipsec didn't preserve the NULL b_cont */
2190                 if (mp->b_cont != NULL) {
2191                         if (!pullupmsg(mp, -1))
2192                                 goto discard_pkt;
2193                 }
2194 
2195                 /*
2196                  * Note that ira_pktlen and ira_ip_hdr_length are no longer
2197                  * correct, but we don't use them any more here.
2198                  *
2199                  * If succesful, the mp has been modified to not include
2200                  * the ESP/AH header so we can fanout to the ULP's icmp
2201                  * error handler.
2202                  */
2203                 if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2204                         goto truncated;
2205 
2206                 /* Verify the modified message before any further processes. */
2207                 ipha = (ipha_t *)mp->b_rptr;
2208                 hdr_length = IPH_HDR_LENGTH(ipha);
2209                 icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2210                 if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2211                         freemsg(mp);
2212                         return;
2213                 }
2214 
2215                 icmp_inbound_error_fanout_v4(mp, icmph, ira);
2216                 return;
2217 
2218         case IPPROTO_ENCAP: {
2219                 /* Look for self-encapsulated packets that caused an error */
2220                 ipha_t *in_ipha;
2221 
2222                 /*
2223                  * Caller has verified that length has to be
2224                  * at least the size of IP header.
2225                  */
2226                 ASSERT(hdr_length >= sizeof (ipha_t));
2227                 /*
2228                  * Check the sanity of the inner IP header like
2229                  * we did for the outer header.
2230                  */
2231                 in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2232                 if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2233                         goto discard_pkt;
2234                 }
2235                 if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2236                         goto discard_pkt;
2237                 }
2238                 /* Check for Self-encapsulated tunnels */
2239                 if (in_ipha->ipha_src == ipha->ipha_src &&
2240                     in_ipha->ipha_dst == ipha->ipha_dst) {
2241 
2242                         mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2243                             in_ipha);
2244                         if (mp == NULL)
2245                                 goto discard_pkt;
2246 
2247                         /*
2248                          * Just in case self_encap didn't preserve the NULL
2249                          * b_cont
2250                          */
2251                         if (mp->b_cont != NULL) {
2252                                 if (!pullupmsg(mp, -1))
2253                                         goto discard_pkt;
2254                         }
2255                         /*
2256                          * Note that ira_pktlen and ira_ip_hdr_length are no
2257                          * longer correct, but we don't use them any more here.
2258                          */
2259                         if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2260                                 goto truncated;
2261 
2262                         /*
2263                          * Verify the modified message before any further
2264                          * processes.
2265                          */
2266                         ipha = (ipha_t *)mp->b_rptr;
2267                         hdr_length = IPH_HDR_LENGTH(ipha);
2268                         icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2269                         if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2270                                 freemsg(mp);
2271                                 return;
2272                         }
2273 
2274                         /*
2275                          * The packet in error is self-encapsualted.
2276                          * And we are finding it further encapsulated
2277                          * which we could not have possibly generated.
2278                          */
2279                         if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2280                                 goto discard_pkt;
2281                         }
2282                         icmp_inbound_error_fanout_v4(mp, icmph, ira);
2283                         return;
2284                 }
2285                 /* No self-encapsulated */
2286                 /* FALLTHRU */
2287         }
2288         case IPPROTO_IPV6:
2289                 if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2290                     &ripha.ipha_dst, ipst)) != NULL) {
2291                         ira->ira_flags |= IRAF_ICMP_ERROR;
2292                         connp->conn_recvicmp(connp, mp, NULL, ira);
2293                         CONN_DEC_REF(connp);
2294                         ira->ira_flags &= ~IRAF_ICMP_ERROR;
2295                         return;
2296                 }
2297                 /*
2298                  * No IP tunnel is interested, fallthrough and see
2299                  * if a raw socket will want it.
2300                  */
2301                 /* FALLTHRU */
2302         default:
2303                 ira->ira_flags |= IRAF_ICMP_ERROR;
2304                 ip_fanout_proto_v4(mp, &ripha, ira);
2305                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2306                 return;
2307         }
2308         /* NOTREACHED */
2309 discard_pkt:
2310         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2311         ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2312         ip_drop_input("ipIfStatsInDiscards", mp, ill);
2313         freemsg(mp);
2314         return;
2315 
2316 truncated:
2317         /* We pulled up everthing already. Must be truncated */
2318         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2319         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2320         freemsg(mp);
2321 }
2322 
2323 /*
2324  * Common IP options parser.
2325  *
2326  * Setup routine: fill in *optp with options-parsing state, then
2327  * tail-call ipoptp_next to return the first option.
2328  */
2329 uint8_t
2330 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2331 {
2332         uint32_t totallen; /* total length of all options */
2333 
2334         totallen = ipha->ipha_version_and_hdr_length -
2335             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2336         totallen <<= 2;
2337         optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2338         optp->ipoptp_end = optp->ipoptp_next + totallen;
2339         optp->ipoptp_flags = 0;
2340         return (ipoptp_next(optp));
2341 }
2342 
2343 /* Like above but without an ipha_t */
2344 uint8_t
2345 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2346 {
2347         optp->ipoptp_next = opt;
2348         optp->ipoptp_end = optp->ipoptp_next + totallen;
2349         optp->ipoptp_flags = 0;
2350         return (ipoptp_next(optp));
2351 }
2352 
2353 /*
2354  * Common IP options parser: extract next option.
2355  */
2356 uint8_t
2357 ipoptp_next(ipoptp_t *optp)
2358 {
2359         uint8_t *end = optp->ipoptp_end;
2360         uint8_t *cur = optp->ipoptp_next;
2361         uint8_t opt, len, pointer;
2362 
2363         /*
2364          * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2365          * has been corrupted.
2366          */
2367         ASSERT(cur <= end);
2368 
2369         if (cur == end)
2370                 return (IPOPT_EOL);
2371 
2372         opt = cur[IPOPT_OPTVAL];
2373 
2374         /*
2375          * Skip any NOP options.
2376          */
2377         while (opt == IPOPT_NOP) {
2378                 cur++;
2379                 if (cur == end)
2380                         return (IPOPT_EOL);
2381                 opt = cur[IPOPT_OPTVAL];
2382         }
2383 
2384         if (opt == IPOPT_EOL)
2385                 return (IPOPT_EOL);
2386 
2387         /*
2388          * Option requiring a length.
2389          */
2390         if ((cur + 1) >= end) {
2391                 optp->ipoptp_flags |= IPOPTP_ERROR;
2392                 return (IPOPT_EOL);
2393         }
2394         len = cur[IPOPT_OLEN];
2395         if (len < 2) {
2396                 optp->ipoptp_flags |= IPOPTP_ERROR;
2397                 return (IPOPT_EOL);
2398         }
2399         optp->ipoptp_cur = cur;
2400         optp->ipoptp_len = len;
2401         optp->ipoptp_next = cur + len;
2402         if (cur + len > end) {
2403                 optp->ipoptp_flags |= IPOPTP_ERROR;
2404                 return (IPOPT_EOL);
2405         }
2406 
2407         /*
2408          * For the options which require a pointer field, make sure
2409          * its there, and make sure it points to either something
2410          * inside this option, or the end of the option.
2411          */
2412         switch (opt) {
2413         case IPOPT_RR:
2414         case IPOPT_TS:
2415         case IPOPT_LSRR:
2416         case IPOPT_SSRR:
2417                 if (len <= IPOPT_OFFSET) {
2418                         optp->ipoptp_flags |= IPOPTP_ERROR;
2419                         return (opt);
2420                 }
2421                 pointer = cur[IPOPT_OFFSET];
2422                 if (pointer - 1 > len) {
2423                         optp->ipoptp_flags |= IPOPTP_ERROR;
2424                         return (opt);
2425                 }
2426                 break;
2427         }
2428 
2429         /*
2430          * Sanity check the pointer field based on the type of the
2431          * option.
2432          */
2433         switch (opt) {
2434         case IPOPT_RR:
2435         case IPOPT_SSRR:
2436         case IPOPT_LSRR:
2437                 if (pointer < IPOPT_MINOFF_SR)
2438                         optp->ipoptp_flags |= IPOPTP_ERROR;
2439                 break;
2440         case IPOPT_TS:
2441                 if (pointer < IPOPT_MINOFF_IT)
2442                         optp->ipoptp_flags |= IPOPTP_ERROR;
2443                 /*
2444                  * Note that the Internet Timestamp option also
2445                  * contains two four bit fields (the Overflow field,
2446                  * and the Flag field), which follow the pointer
2447                  * field.  We don't need to check that these fields
2448                  * fall within the length of the option because this
2449                  * was implicitely done above.  We've checked that the
2450                  * pointer value is at least IPOPT_MINOFF_IT, and that
2451                  * it falls within the option.  Since IPOPT_MINOFF_IT >
2452                  * IPOPT_POS_OV_FLG, we don't need the explicit check.
2453                  */
2454                 ASSERT(len > IPOPT_POS_OV_FLG);
2455                 break;
2456         }
2457 
2458         return (opt);
2459 }
2460 
2461 /*
2462  * Use the outgoing IP header to create an IP_OPTIONS option the way
2463  * it was passed down from the application.
2464  *
2465  * This is compatible with BSD in that it returns
2466  * the reverse source route with the final destination
2467  * as the last entry. The first 4 bytes of the option
2468  * will contain the final destination.
2469  */
2470 int
2471 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2472 {
2473         ipoptp_t        opts;
2474         uchar_t         *opt;
2475         uint8_t         optval;
2476         uint8_t         optlen;
2477         uint32_t        len = 0;
2478         uchar_t         *buf1 = buf;
2479         uint32_t        totallen;
2480         ipaddr_t        dst;
2481         ip_pkt_t        *ipp = &connp->conn_xmit_ipp;
2482 
2483         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2484                 return (0);
2485 
2486         totallen = ipp->ipp_ipv4_options_len;
2487         if (totallen & 0x3)
2488                 return (0);
2489 
2490         buf += IP_ADDR_LEN;     /* Leave room for final destination */
2491         len += IP_ADDR_LEN;
2492         bzero(buf1, IP_ADDR_LEN);
2493 
2494         dst = connp->conn_faddr_v4;
2495 
2496         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2497             optval != IPOPT_EOL;
2498             optval = ipoptp_next(&opts)) {
2499                 int     off;
2500 
2501                 opt = opts.ipoptp_cur;
2502                 if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2503                         break;
2504                 }
2505                 optlen = opts.ipoptp_len;
2506 
2507                 switch (optval) {
2508                 case IPOPT_SSRR:
2509                 case IPOPT_LSRR:
2510 
2511                         /*
2512                          * Insert destination as the first entry in the source
2513                          * route and move down the entries on step.
2514                          * The last entry gets placed at buf1.
2515                          */
2516                         buf[IPOPT_OPTVAL] = optval;
2517                         buf[IPOPT_OLEN] = optlen;
2518                         buf[IPOPT_OFFSET] = optlen;
2519 
2520                         off = optlen - IP_ADDR_LEN;
2521                         if (off < 0) {
2522                                 /* No entries in source route */
2523                                 break;
2524                         }
2525                         /* Last entry in source route if not already set */
2526                         if (dst == INADDR_ANY)
2527                                 bcopy(opt + off, buf1, IP_ADDR_LEN);
2528                         off -= IP_ADDR_LEN;
2529 
2530                         while (off > 0) {
2531                                 bcopy(opt + off,
2532                                     buf + off + IP_ADDR_LEN,
2533                                     IP_ADDR_LEN);
2534                                 off -= IP_ADDR_LEN;
2535                         }
2536                         /* ipha_dst into first slot */
2537                         bcopy(&dst, buf + off + IP_ADDR_LEN,
2538                             IP_ADDR_LEN);
2539                         buf += optlen;
2540                         len += optlen;
2541                         break;
2542 
2543                 default:
2544                         bcopy(opt, buf, optlen);
2545                         buf += optlen;
2546                         len += optlen;
2547                         break;
2548                 }
2549         }
2550 done:
2551         /* Pad the resulting options */
2552         while (len & 0x3) {
2553                 *buf++ = IPOPT_EOL;
2554                 len++;
2555         }
2556         return (len);
2557 }
2558 
2559 /*
2560  * Update any record route or timestamp options to include this host.
2561  * Reverse any source route option.
2562  * This routine assumes that the options are well formed i.e. that they
2563  * have already been checked.
2564  */
2565 static void
2566 icmp_options_update(ipha_t *ipha)
2567 {
2568         ipoptp_t        opts;
2569         uchar_t         *opt;
2570         uint8_t         optval;
2571         ipaddr_t        src;            /* Our local address */
2572         ipaddr_t        dst;
2573 
2574         ip2dbg(("icmp_options_update\n"));
2575         src = ipha->ipha_src;
2576         dst = ipha->ipha_dst;
2577 
2578         for (optval = ipoptp_first(&opts, ipha);
2579             optval != IPOPT_EOL;
2580             optval = ipoptp_next(&opts)) {
2581                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2582                 opt = opts.ipoptp_cur;
2583                 ip2dbg(("icmp_options_update: opt %d, len %d\n",
2584                     optval, opts.ipoptp_len));
2585                 switch (optval) {
2586                         int off1, off2;
2587                 case IPOPT_SSRR:
2588                 case IPOPT_LSRR:
2589                         /*
2590                          * Reverse the source route.  The first entry
2591                          * should be the next to last one in the current
2592                          * source route (the last entry is our address).
2593                          * The last entry should be the final destination.
2594                          */
2595                         off1 = IPOPT_MINOFF_SR - 1;
2596                         off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2597                         if (off2 < 0) {
2598                                 /* No entries in source route */
2599                                 ip1dbg((
2600                                     "icmp_options_update: bad src route\n"));
2601                                 break;
2602                         }
2603                         bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2604                         bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2605                         bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2606                         off2 -= IP_ADDR_LEN;
2607 
2608                         while (off1 < off2) {
2609                                 bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2610                                 bcopy((char *)opt + off2, (char *)opt + off1,
2611                                     IP_ADDR_LEN);
2612                                 bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2613                                 off1 += IP_ADDR_LEN;
2614                                 off2 -= IP_ADDR_LEN;
2615                         }
2616                         opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2617                         break;
2618                 }
2619         }
2620 }
2621 
2622 /*
2623  * Process received ICMP Redirect messages.
2624  * Assumes the caller has verified that the headers are in the pulled up mblk.
2625  * Consumes mp.
2626  */
2627 static void
2628 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2629 {
2630         ire_t           *ire, *nire;
2631         ire_t           *prev_ire;
2632         ipaddr_t        src, dst, gateway;
2633         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2634         ipha_t          *inner_ipha;    /* Inner IP header */
2635 
2636         /* Caller already pulled up everything. */
2637         inner_ipha = (ipha_t *)&icmph[1];
2638         src = ipha->ipha_src;
2639         dst = inner_ipha->ipha_dst;
2640         gateway = icmph->icmph_rd_gateway;
2641         /* Make sure the new gateway is reachable somehow. */
2642         ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2643             ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2644         /*
2645          * Make sure we had a route for the dest in question and that
2646          * that route was pointing to the old gateway (the source of the
2647          * redirect packet.)
2648          * We do longest match and then compare ire_gateway_addr below.
2649          */
2650         prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2651             NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2652         /*
2653          * Check that
2654          *      the redirect was not from ourselves
2655          *      the new gateway and the old gateway are directly reachable
2656          */
2657         if (prev_ire == NULL || ire == NULL ||
2658             (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2659             (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2660             !(ire->ire_type & IRE_IF_ALL) ||
2661             prev_ire->ire_gateway_addr != src) {
2662                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2663                 ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2664                 freemsg(mp);
2665                 if (ire != NULL)
2666                         ire_refrele(ire);
2667                 if (prev_ire != NULL)
2668                         ire_refrele(prev_ire);
2669                 return;
2670         }
2671 
2672         ire_refrele(prev_ire);
2673         ire_refrele(ire);
2674 
2675         /*
2676          * TODO: more precise handling for cases 0, 2, 3, the latter two
2677          * require TOS routing
2678          */
2679         switch (icmph->icmph_code) {
2680         case 0:
2681         case 1:
2682                 /* TODO: TOS specificity for cases 2 and 3 */
2683         case 2:
2684         case 3:
2685                 break;
2686         default:
2687                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2688                 ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2689                 freemsg(mp);
2690                 return;
2691         }
2692         /*
2693          * Create a Route Association.  This will allow us to remember that
2694          * someone we believe told us to use the particular gateway.
2695          */
2696         ire = ire_create(
2697             (uchar_t *)&dst,                        /* dest addr */
2698             (uchar_t *)&ip_g_all_ones,              /* mask */
2699             (uchar_t *)&gateway,            /* gateway addr */
2700             IRE_HOST,
2701             NULL,                               /* ill */
2702             ALL_ZONES,
2703             (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2704             NULL,                               /* tsol_gc_t */
2705             ipst);
2706 
2707         if (ire == NULL) {
2708                 freemsg(mp);
2709                 return;
2710         }
2711         nire = ire_add(ire);
2712         /* Check if it was a duplicate entry */
2713         if (nire != NULL && nire != ire) {
2714                 ASSERT(nire->ire_identical_ref > 1);
2715                 ire_delete(nire);
2716                 ire_refrele(nire);
2717                 nire = NULL;
2718         }
2719         ire = nire;
2720         if (ire != NULL) {
2721                 ire_refrele(ire);               /* Held in ire_add */
2722 
2723                 /* tell routing sockets that we received a redirect */
2724                 ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2725                     (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2726                     (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2727         }
2728 
2729         /*
2730          * Delete any existing IRE_HOST type redirect ires for this destination.
2731          * This together with the added IRE has the effect of
2732          * modifying an existing redirect.
2733          */
2734         prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2735             ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2736         if (prev_ire != NULL) {
2737                 if (prev_ire ->ire_flags & RTF_DYNAMIC)
2738                         ire_delete(prev_ire);
2739                 ire_refrele(prev_ire);
2740         }
2741 
2742         freemsg(mp);
2743 }
2744 
2745 /*
2746  * Generate an ICMP parameter problem message.
2747  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2748  * constructed by the caller.
2749  */
2750 static void
2751 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2752 {
2753         icmph_t icmph;
2754         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2755 
2756         mp = icmp_pkt_err_ok(mp, ira);
2757         if (mp == NULL)
2758                 return;
2759 
2760         bzero(&icmph, sizeof (icmph_t));
2761         icmph.icmph_type = ICMP_PARAM_PROBLEM;
2762         icmph.icmph_pp_ptr = ptr;
2763         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2764         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2765 }
2766 
2767 /*
2768  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2769  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2770  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2771  * an icmp error packet can be sent.
2772  * Assigns an appropriate source address to the packet. If ipha_dst is
2773  * one of our addresses use it for source. Otherwise let ip_output_simple
2774  * pick the source address.
2775  */
2776 static void
2777 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2778 {
2779         ipaddr_t dst;
2780         icmph_t *icmph;
2781         ipha_t  *ipha;
2782         uint_t  len_needed;
2783         size_t  msg_len;
2784         mblk_t  *mp1;
2785         ipaddr_t src;
2786         ire_t   *ire;
2787         ip_xmit_attr_t ixas;
2788         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2789 
2790         ipha = (ipha_t *)mp->b_rptr;
2791 
2792         bzero(&ixas, sizeof (ixas));
2793         ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2794         ixas.ixa_zoneid = ira->ira_zoneid;
2795         ixas.ixa_ifindex = 0;
2796         ixas.ixa_ipst = ipst;
2797         ixas.ixa_cred = kcred;
2798         ixas.ixa_cpid = NOPID;
2799         ixas.ixa_tsl = ira->ira_tsl; /* Behave as a multi-level responder */
2800         ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2801 
2802         if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2803                 /*
2804                  * Apply IPsec based on how IPsec was applied to
2805                  * the packet that had the error.
2806                  *
2807                  * If it was an outbound packet that caused the ICMP
2808                  * error, then the caller will have setup the IRA
2809                  * appropriately.
2810                  */
2811                 if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2812                         BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2813                         /* Note: mp already consumed and ip_drop_packet done */
2814                         return;
2815                 }
2816         } else {
2817                 /*
2818                  * This is in clear. The icmp message we are building
2819                  * here should go out in clear, independent of our policy.
2820                  */
2821                 ixas.ixa_flags |= IXAF_NO_IPSEC;
2822         }
2823 
2824         /* Remember our eventual destination */
2825         dst = ipha->ipha_src;
2826 
2827         /*
2828          * If the packet was for one of our unicast addresses, make
2829          * sure we respond with that as the source. Otherwise
2830          * have ip_output_simple pick the source address.
2831          */
2832         ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2833             (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2834             MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2835         if (ire != NULL) {
2836                 ire_refrele(ire);
2837                 src = ipha->ipha_dst;
2838         } else {
2839                 src = INADDR_ANY;
2840                 ixas.ixa_flags |= IXAF_SET_SOURCE;
2841         }
2842 
2843         /*
2844          * Check if we can send back more then 8 bytes in addition to
2845          * the IP header.  We try to send 64 bytes of data and the internal
2846          * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2847          */
2848         len_needed = IPH_HDR_LENGTH(ipha);
2849         if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2850             ipha->ipha_protocol == IPPROTO_IPV6) {
2851                 if (!pullupmsg(mp, -1)) {
2852                         BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2853                         ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2854                         freemsg(mp);
2855                         return;
2856                 }
2857                 ipha = (ipha_t *)mp->b_rptr;
2858 
2859                 if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2860                         len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2861                             len_needed));
2862                 } else {
2863                         ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2864 
2865                         ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2866                         len_needed += ip_hdr_length_v6(mp, ip6h);
2867                 }
2868         }
2869         len_needed += ipst->ips_ip_icmp_return;
2870         msg_len = msgdsize(mp);
2871         if (msg_len > len_needed) {
2872                 (void) adjmsg(mp, len_needed - msg_len);
2873                 msg_len = len_needed;
2874         }
2875         mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2876         if (mp1 == NULL) {
2877                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2878                 freemsg(mp);
2879                 return;
2880         }
2881         mp1->b_cont = mp;
2882         mp = mp1;
2883 
2884         /*
2885          * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2886          * node generates be accepted in peace by all on-host destinations.
2887          * If we do NOT assume that all on-host destinations trust
2888          * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2889          * (Look for IXAF_TRUSTED_ICMP).
2890          */
2891         ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2892 
2893         ipha = (ipha_t *)mp->b_rptr;
2894         mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2895         *ipha = icmp_ipha;
2896         ipha->ipha_src = src;
2897         ipha->ipha_dst = dst;
2898         ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2899         msg_len += sizeof (icmp_ipha) + len;
2900         if (msg_len > IP_MAXPACKET) {
2901                 (void) adjmsg(mp, IP_MAXPACKET - msg_len);
2902                 msg_len = IP_MAXPACKET;
2903         }
2904         ipha->ipha_length = htons((uint16_t)msg_len);
2905         icmph = (icmph_t *)&ipha[1];
2906         bcopy(stuff, icmph, len);
2907         icmph->icmph_checksum = 0;
2908         icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2909         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2910 
2911         (void) ip_output_simple(mp, &ixas);
2912         ixa_cleanup(&ixas);
2913 }
2914 
2915 /*
2916  * Determine if an ICMP error packet can be sent given the rate limit.
2917  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2918  * in milliseconds) and a burst size. Burst size number of packets can
2919  * be sent arbitrarely closely spaced.
2920  * The state is tracked using two variables to implement an approximate
2921  * token bucket filter:
2922  *      icmp_pkt_err_last - lbolt value when the last burst started
2923  *      icmp_pkt_err_sent - number of packets sent in current burst
2924  */
2925 boolean_t
2926 icmp_err_rate_limit(ip_stack_t *ipst)
2927 {
2928         clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2929         uint_t refilled; /* Number of packets refilled in tbf since last */
2930         /* Guard against changes by loading into local variable */
2931         uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2932 
2933         if (err_interval == 0)
2934                 return (B_FALSE);
2935 
2936         if (ipst->ips_icmp_pkt_err_last > now) {
2937                 /* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2938                 ipst->ips_icmp_pkt_err_last = 0;
2939                 ipst->ips_icmp_pkt_err_sent = 0;
2940         }
2941         /*
2942          * If we are in a burst update the token bucket filter.
2943          * Update the "last" time to be close to "now" but make sure
2944          * we don't loose precision.
2945          */
2946         if (ipst->ips_icmp_pkt_err_sent != 0) {
2947                 refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2948                 if (refilled > ipst->ips_icmp_pkt_err_sent) {
2949                         ipst->ips_icmp_pkt_err_sent = 0;
2950                 } else {
2951                         ipst->ips_icmp_pkt_err_sent -= refilled;
2952                         ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2953                 }
2954         }
2955         if (ipst->ips_icmp_pkt_err_sent == 0) {
2956                 /* Start of new burst */
2957                 ipst->ips_icmp_pkt_err_last = now;
2958         }
2959         if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2960                 ipst->ips_icmp_pkt_err_sent++;
2961                 ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2962                     ipst->ips_icmp_pkt_err_sent));
2963                 return (B_FALSE);
2964         }
2965         ip1dbg(("icmp_err_rate_limit: dropped\n"));
2966         return (B_TRUE);
2967 }
2968 
2969 /*
2970  * Check if it is ok to send an IPv4 ICMP error packet in
2971  * response to the IPv4 packet in mp.
2972  * Free the message and return null if no
2973  * ICMP error packet should be sent.
2974  */
2975 static mblk_t *
2976 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2977 {
2978         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2979         icmph_t *icmph;
2980         ipha_t  *ipha;
2981         uint_t  len_needed;
2982 
2983         if (!mp)
2984                 return (NULL);
2985         ipha = (ipha_t *)mp->b_rptr;
2986         if (ip_csum_hdr(ipha)) {
2987                 BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2988                 ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2989                 freemsg(mp);
2990                 return (NULL);
2991         }
2992         if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2993             ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2994             CLASSD(ipha->ipha_dst) ||
2995             CLASSD(ipha->ipha_src) ||
2996             (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2997                 /* Note: only errors to the fragment with offset 0 */
2998                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2999                 freemsg(mp);
3000                 return (NULL);
3001         }
3002         if (ipha->ipha_protocol == IPPROTO_ICMP) {
3003                 /*
3004                  * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3005                  * errors in response to any ICMP errors.
3006                  */
3007                 len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3008                 if (mp->b_wptr - mp->b_rptr < len_needed) {
3009                         if (!pullupmsg(mp, len_needed)) {
3010                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3011                                 freemsg(mp);
3012                                 return (NULL);
3013                         }
3014                         ipha = (ipha_t *)mp->b_rptr;
3015                 }
3016                 icmph = (icmph_t *)
3017                     (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3018                 switch (icmph->icmph_type) {
3019                 case ICMP_DEST_UNREACHABLE:
3020                 case ICMP_SOURCE_QUENCH:
3021                 case ICMP_TIME_EXCEEDED:
3022                 case ICMP_PARAM_PROBLEM:
3023                 case ICMP_REDIRECT:
3024                         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3025                         freemsg(mp);
3026                         return (NULL);
3027                 default:
3028                         break;
3029                 }
3030         }
3031         /*
3032          * If this is a labeled system, then check to see if we're allowed to
3033          * send a response to this particular sender.  If not, then just drop.
3034          */
3035         if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3036                 ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3037                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3038                 freemsg(mp);
3039                 return (NULL);
3040         }
3041         if (icmp_err_rate_limit(ipst)) {
3042                 /*
3043                  * Only send ICMP error packets every so often.
3044                  * This should be done on a per port/source basis,
3045                  * but for now this will suffice.
3046                  */
3047                 freemsg(mp);
3048                 return (NULL);
3049         }
3050         return (mp);
3051 }
3052 
3053 /*
3054  * Called when a packet was sent out the same link that it arrived on.
3055  * Check if it is ok to send a redirect and then send it.
3056  */
3057 void
3058 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3059     ip_recv_attr_t *ira)
3060 {
3061         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
3062         ipaddr_t        src, nhop;
3063         mblk_t          *mp1;
3064         ire_t           *nhop_ire;
3065 
3066         /*
3067          * Check the source address to see if it originated
3068          * on the same logical subnet it is going back out on.
3069          * If so, we should be able to send it a redirect.
3070          * Avoid sending a redirect if the destination
3071          * is directly connected (i.e., we matched an IRE_ONLINK),
3072          * or if the packet was source routed out this interface.
3073          *
3074          * We avoid sending a redirect if the
3075          * destination is directly connected
3076          * because it is possible that multiple
3077          * IP subnets may have been configured on
3078          * the link, and the source may not
3079          * be on the same subnet as ip destination,
3080          * even though they are on the same
3081          * physical link.
3082          */
3083         if ((ire->ire_type & IRE_ONLINK) ||
3084             ip_source_routed(ipha, ipst))
3085                 return;
3086 
3087         nhop_ire = ire_nexthop(ire);
3088         if (nhop_ire == NULL)
3089                 return;
3090 
3091         nhop = nhop_ire->ire_addr;
3092 
3093         if (nhop_ire->ire_type & IRE_IF_CLONE) {
3094                 ire_t   *ire2;
3095 
3096                 /* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3097                 mutex_enter(&nhop_ire->ire_lock);
3098                 ire2 = nhop_ire->ire_dep_parent;
3099                 if (ire2 != NULL)
3100                         ire_refhold(ire2);
3101                 mutex_exit(&nhop_ire->ire_lock);
3102                 ire_refrele(nhop_ire);
3103                 nhop_ire = ire2;
3104         }
3105         if (nhop_ire == NULL)
3106                 return;
3107 
3108         ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3109 
3110         src = ipha->ipha_src;
3111 
3112         /*
3113          * We look at the interface ire for the nexthop,
3114          * to see if ipha_src is in the same subnet
3115          * as the nexthop.
3116          */
3117         if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3118                 /*
3119                  * The source is directly connected.
3120                  */
3121                 mp1 = copymsg(mp);
3122                 if (mp1 != NULL) {
3123                         icmp_send_redirect(mp1, nhop, ira);
3124                 }
3125         }
3126         ire_refrele(nhop_ire);
3127 }
3128 
3129 /*
3130  * Generate an ICMP redirect message.
3131  */
3132 static void
3133 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3134 {
3135         icmph_t icmph;
3136         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3137 
3138         mp = icmp_pkt_err_ok(mp, ira);
3139         if (mp == NULL)
3140                 return;
3141 
3142         bzero(&icmph, sizeof (icmph_t));
3143         icmph.icmph_type = ICMP_REDIRECT;
3144         icmph.icmph_code = 1;
3145         icmph.icmph_rd_gateway = gateway;
3146         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3147         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3148 }
3149 
3150 /*
3151  * Generate an ICMP time exceeded message.
3152  */
3153 void
3154 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3155 {
3156         icmph_t icmph;
3157         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3158 
3159         mp = icmp_pkt_err_ok(mp, ira);
3160         if (mp == NULL)
3161                 return;
3162 
3163         bzero(&icmph, sizeof (icmph_t));
3164         icmph.icmph_type = ICMP_TIME_EXCEEDED;
3165         icmph.icmph_code = code;
3166         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3167         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3168 }
3169 
3170 /*
3171  * Generate an ICMP unreachable message.
3172  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3173  * constructed by the caller.
3174  */
3175 void
3176 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3177 {
3178         icmph_t icmph;
3179         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3180 
3181         mp = icmp_pkt_err_ok(mp, ira);
3182         if (mp == NULL)
3183                 return;
3184 
3185         bzero(&icmph, sizeof (icmph_t));
3186         icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3187         icmph.icmph_code = code;
3188         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3189         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3190 }
3191 
3192 /*
3193  * Latch in the IPsec state for a stream based the policy in the listener
3194  * and the actions in the ip_recv_attr_t.
3195  * Called directly from TCP and SCTP.
3196  */
3197 boolean_t
3198 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3199 {
3200         ASSERT(lconnp->conn_policy != NULL);
3201         ASSERT(connp->conn_policy == NULL);
3202 
3203         IPPH_REFHOLD(lconnp->conn_policy);
3204         connp->conn_policy = lconnp->conn_policy;
3205 
3206         if (ira->ira_ipsec_action != NULL) {
3207                 if (connp->conn_latch == NULL) {
3208                         connp->conn_latch = iplatch_create();
3209                         if (connp->conn_latch == NULL)
3210                                 return (B_FALSE);
3211                 }
3212                 ipsec_latch_inbound(connp, ira);
3213         }
3214         return (B_TRUE);
3215 }
3216 
3217 /*
3218  * Verify whether or not the IP address is a valid local address.
3219  * Could be a unicast, including one for a down interface.
3220  * If allow_mcbc then a multicast or broadcast address is also
3221  * acceptable.
3222  *
3223  * In the case of a broadcast/multicast address, however, the
3224  * upper protocol is expected to reset the src address
3225  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3226  * no packets are emitted with broadcast/multicast address as
3227  * source address (that violates hosts requirements RFC 1122)
3228  * The addresses valid for bind are:
3229  *      (1) - INADDR_ANY (0)
3230  *      (2) - IP address of an UP interface
3231  *      (3) - IP address of a DOWN interface
3232  *      (4) - valid local IP broadcast addresses. In this case
3233  *      the conn will only receive packets destined to
3234  *      the specified broadcast address.
3235  *      (5) - a multicast address. In this case
3236  *      the conn will only receive packets destined to
3237  *      the specified multicast address. Note: the
3238  *      application still has to issue an
3239  *      IP_ADD_MEMBERSHIP socket option.
3240  *
3241  * In all the above cases, the bound address must be valid in the current zone.
3242  * When the address is loopback, multicast or broadcast, there might be many
3243  * matching IREs so bind has to look up based on the zone.
3244  */
3245 ip_laddr_t
3246 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3247     ip_stack_t *ipst, boolean_t allow_mcbc)
3248 {
3249         ire_t *src_ire;
3250 
3251         ASSERT(src_addr != INADDR_ANY);
3252 
3253         src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3254             NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3255 
3256         /*
3257          * If an address other than in6addr_any is requested,
3258          * we verify that it is a valid address for bind
3259          * Note: Following code is in if-else-if form for
3260          * readability compared to a condition check.
3261          */
3262         if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3263                 /*
3264                  * (2) Bind to address of local UP interface
3265                  */
3266                 ire_refrele(src_ire);
3267                 return (IPVL_UNICAST_UP);
3268         } else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3269                 /*
3270                  * (4) Bind to broadcast address
3271                  */
3272                 ire_refrele(src_ire);
3273                 if (allow_mcbc)
3274                         return (IPVL_BCAST);
3275                 else
3276                         return (IPVL_BAD);
3277         } else if (CLASSD(src_addr)) {
3278                 /* (5) bind to multicast address. */
3279                 if (src_ire != NULL)
3280                         ire_refrele(src_ire);
3281 
3282                 if (allow_mcbc)
3283                         return (IPVL_MCAST);
3284                 else
3285                         return (IPVL_BAD);
3286         } else {
3287                 ipif_t *ipif;
3288 
3289                 /*
3290                  * (3) Bind to address of local DOWN interface?
3291                  * (ipif_lookup_addr() looks up all interfaces
3292                  * but we do not get here for UP interfaces
3293                  * - case (2) above)
3294                  */
3295                 if (src_ire != NULL)
3296                         ire_refrele(src_ire);
3297 
3298                 ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3299                 if (ipif == NULL)
3300                         return (IPVL_BAD);
3301 
3302                 /* Not a useful source? */
3303                 if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3304                         ipif_refrele(ipif);
3305                         return (IPVL_BAD);
3306                 }
3307                 ipif_refrele(ipif);
3308                 return (IPVL_UNICAST_DOWN);
3309         }
3310 }
3311 
3312 /*
3313  * Insert in the bind fanout for IPv4 and IPv6.
3314  * The caller should already have used ip_laddr_verify_v*() before calling
3315  * this.
3316  */
3317 int
3318 ip_laddr_fanout_insert(conn_t *connp)
3319 {
3320         int             error;
3321 
3322         /*
3323          * Allow setting new policies. For example, disconnects result
3324          * in us being called. As we would have set conn_policy_cached
3325          * to B_TRUE before, we should set it to B_FALSE, so that policy
3326          * can change after the disconnect.
3327          */
3328         connp->conn_policy_cached = B_FALSE;
3329 
3330         error = ipcl_bind_insert(connp);
3331         if (error != 0) {
3332                 if (connp->conn_anon_port) {
3333                         (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3334                             connp->conn_mlp_type, connp->conn_proto,
3335                             ntohs(connp->conn_lport), B_FALSE);
3336                 }
3337                 connp->conn_mlp_type = mlptSingle;
3338         }
3339         return (error);
3340 }
3341 
3342 /*
3343  * Verify that both the source and destination addresses are valid. If
3344  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3345  * i.e. have no route to it.  Protocols like TCP want to verify destination
3346  * reachability, while tunnels do not.
3347  *
3348  * Determine the route, the interface, and (optionally) the source address
3349  * to use to reach a given destination.
3350  * Note that we allow connect to broadcast and multicast addresses when
3351  * IPDF_ALLOW_MCBC is set.
3352  * first_hop and dst_addr are normally the same, but if source routing
3353  * they will differ; in that case the first_hop is what we'll use for the
3354  * routing lookup but the dce and label checks will be done on dst_addr,
3355  *
3356  * If uinfo is set, then we fill in the best available information
3357  * we have for the destination. This is based on (in priority order) any
3358  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3359  * ill_mtu/ill_mc_mtu.
3360  *
3361  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3362  * always do the label check on dst_addr.
3363  */
3364 int
3365 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3366     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3367 {
3368         ire_t           *ire = NULL;
3369         int             error = 0;
3370         ipaddr_t        setsrc;                         /* RTF_SETSRC */
3371         zoneid_t        zoneid = ixa->ixa_zoneid;    /* Honors SO_ALLZONES */
3372         ip_stack_t      *ipst = ixa->ixa_ipst;
3373         dce_t           *dce;
3374         uint_t          pmtu;
3375         uint_t          generation;
3376         nce_t           *nce;
3377         ill_t           *ill = NULL;
3378         boolean_t       multirt = B_FALSE;
3379 
3380         ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3381 
3382         /*
3383          * We never send to zero; the ULPs map it to the loopback address.
3384          * We can't allow it since we use zero to mean unitialized in some
3385          * places.
3386          */
3387         ASSERT(dst_addr != INADDR_ANY);
3388 
3389         if (is_system_labeled()) {
3390                 ts_label_t *tsl = NULL;
3391 
3392                 error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3393                     mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3394                 if (error != 0)
3395                         return (error);
3396                 if (tsl != NULL) {
3397                         /* Update the label */
3398                         ip_xmit_attr_replace_tsl(ixa, tsl);
3399                 }
3400         }
3401 
3402         setsrc = INADDR_ANY;
3403         /*
3404          * Select a route; For IPMP interfaces, we would only select
3405          * a "hidden" route (i.e., going through a specific under_ill)
3406          * if ixa_ifindex has been specified.
3407          */
3408         ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3409             &generation, &setsrc, &error, &multirt);
3410         ASSERT(ire != NULL);    /* IRE_NOROUTE if none found */
3411         if (error != 0)
3412                 goto bad_addr;
3413 
3414         /*
3415          * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3416          * If IPDF_VERIFY_DST is set, the destination must be reachable;
3417          * Otherwise the destination needn't be reachable.
3418          *
3419          * If we match on a reject or black hole, then we've got a
3420          * local failure.  May as well fail out the connect() attempt,
3421          * since it's never going to succeed.
3422          */
3423         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3424                 /*
3425                  * If we're verifying destination reachability, we always want
3426                  * to complain here.
3427                  *
3428                  * If we're not verifying destination reachability but the
3429                  * destination has a route, we still want to fail on the
3430                  * temporary address and broadcast address tests.
3431                  *
3432                  * In both cases do we let the code continue so some reasonable
3433                  * information is returned to the caller. That enables the
3434                  * caller to use (and even cache) the IRE. conn_ip_ouput will
3435                  * use the generation mismatch path to check for the unreachable
3436                  * case thereby avoiding any specific check in the main path.
3437                  */
3438                 ASSERT(generation == IRE_GENERATION_VERIFY);
3439                 if (flags & IPDF_VERIFY_DST) {
3440                         /*
3441                          * Set errno but continue to set up ixa_ire to be
3442                          * the RTF_REJECT|RTF_BLACKHOLE IRE.
3443                          * That allows callers to use ip_output to get an
3444                          * ICMP error back.
3445                          */
3446                         if (!(ire->ire_type & IRE_HOST))
3447                                 error = ENETUNREACH;
3448                         else
3449                                 error = EHOSTUNREACH;
3450                 }
3451         }
3452 
3453         if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3454             !(flags & IPDF_ALLOW_MCBC)) {
3455                 ire_refrele(ire);
3456                 ire = ire_reject(ipst, B_FALSE);
3457                 generation = IRE_GENERATION_VERIFY;
3458                 error = ENETUNREACH;
3459         }
3460 
3461         /* Cache things */
3462         if (ixa->ixa_ire != NULL)
3463                 ire_refrele_notr(ixa->ixa_ire);
3464 #ifdef DEBUG
3465         ire_refhold_notr(ire);
3466         ire_refrele(ire);
3467 #endif
3468         ixa->ixa_ire = ire;
3469         ixa->ixa_ire_generation = generation;
3470 
3471         /*
3472          * Ensure that ixa_dce is always set any time that ixa_ire is set,
3473          * since some callers will send a packet to conn_ip_output() even if
3474          * there's an error.
3475          */
3476         if (flags & IPDF_UNIQUE_DCE) {
3477                 /* Fallback to the default dce if allocation fails */
3478                 dce = dce_lookup_and_add_v4(dst_addr, ipst);
3479                 if (dce != NULL)
3480                         generation = dce->dce_generation;
3481                 else
3482                         dce = dce_lookup_v4(dst_addr, ipst, &generation);
3483         } else {
3484                 dce = dce_lookup_v4(dst_addr, ipst, &generation);
3485         }
3486         ASSERT(dce != NULL);
3487         if (ixa->ixa_dce != NULL)
3488                 dce_refrele_notr(ixa->ixa_dce);
3489 #ifdef DEBUG
3490         dce_refhold_notr(dce);
3491         dce_refrele(dce);
3492 #endif
3493         ixa->ixa_dce = dce;
3494         ixa->ixa_dce_generation = generation;
3495 
3496         /*
3497          * For multicast with multirt we have a flag passed back from
3498          * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3499          * possible multicast address.
3500          * We also need a flag for multicast since we can't check
3501          * whether RTF_MULTIRT is set in ixa_ire for multicast.
3502          */
3503         if (multirt) {
3504                 ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3505                 ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3506         } else {
3507                 ixa->ixa_postfragfn = ire->ire_postfragfn;
3508                 ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3509         }
3510         if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3511                 /* Get an nce to cache. */
3512                 nce = ire_to_nce(ire, firsthop, NULL);
3513                 if (nce == NULL) {
3514                         /* Allocation failure? */
3515                         ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3516                 } else {
3517                         if (ixa->ixa_nce != NULL)
3518                                 nce_refrele(ixa->ixa_nce);
3519                         ixa->ixa_nce = nce;
3520                 }
3521         }
3522 
3523         /*
3524          * If the source address is a loopback address, the
3525          * destination had best be local or multicast.
3526          * If we are sending to an IRE_LOCAL using a loopback source then
3527          * it had better be the same zoneid.
3528          */
3529         if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3530                 if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3531                         ire = NULL;     /* Stored in ixa_ire */
3532                         error = EADDRNOTAVAIL;
3533                         goto bad_addr;
3534                 }
3535                 if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3536                         ire = NULL;     /* Stored in ixa_ire */
3537                         error = EADDRNOTAVAIL;
3538                         goto bad_addr;
3539                 }
3540         }
3541         if (ire->ire_type & IRE_BROADCAST) {
3542                 /*
3543                  * If the ULP didn't have a specified source, then we
3544                  * make sure we reselect the source when sending
3545                  * broadcasts out different interfaces.
3546                  */
3547                 if (flags & IPDF_SELECT_SRC)
3548                         ixa->ixa_flags |= IXAF_SET_SOURCE;
3549                 else
3550                         ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3551         }
3552 
3553         /*
3554          * Does the caller want us to pick a source address?
3555          */
3556         if (flags & IPDF_SELECT_SRC) {
3557                 ipaddr_t        src_addr;
3558 
3559                 /*
3560                  * We use use ire_nexthop_ill to avoid the under ipmp
3561                  * interface for source address selection. Note that for ipmp
3562                  * probe packets, ixa_ifindex would have been specified, and
3563                  * the ip_select_route() invocation would have picked an ire
3564                  * will ire_ill pointing at an under interface.
3565                  */
3566                 ill = ire_nexthop_ill(ire);
3567 
3568                 /* If unreachable we have no ill but need some source */
3569                 if (ill == NULL) {
3570                         src_addr = htonl(INADDR_LOOPBACK);
3571                         /* Make sure we look for a better source address */
3572                         generation = SRC_GENERATION_VERIFY;
3573                 } else {
3574                         error = ip_select_source_v4(ill, setsrc, dst_addr,
3575                             ixa->ixa_multicast_ifaddr, zoneid,
3576                             ipst, &src_addr, &generation, NULL);
3577                         if (error != 0) {
3578                                 ire = NULL;     /* Stored in ixa_ire */
3579                                 goto bad_addr;
3580                         }
3581                 }
3582 
3583                 /*
3584                  * We allow the source address to to down.
3585                  * However, we check that we don't use the loopback address
3586                  * as a source when sending out on the wire.
3587                  */
3588                 if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3589                     !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3590                     !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3591                         ire = NULL;     /* Stored in ixa_ire */
3592                         error = EADDRNOTAVAIL;
3593                         goto bad_addr;
3594                 }
3595 
3596                 *src_addrp = src_addr;
3597                 ixa->ixa_src_generation = generation;
3598         }
3599 
3600         /*
3601          * Make sure we don't leave an unreachable ixa_nce in place
3602          * since ip_select_route is used when we unplumb i.e., remove
3603          * references on ixa_ire, ixa_nce, and ixa_dce.
3604          */
3605         nce = ixa->ixa_nce;
3606         if (nce != NULL && nce->nce_is_condemned) {
3607                 nce_refrele(nce);
3608                 ixa->ixa_nce = NULL;
3609                 ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3610         }
3611 
3612         /*
3613          * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3614          * However, we can't do it for IPv4 multicast or broadcast.
3615          */
3616         if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3617                 ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3618 
3619         /*
3620          * Set initial value for fragmentation limit. Either conn_ip_output
3621          * or ULP might updates it when there are routing changes.
3622          * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3623          */
3624         pmtu = ip_get_pmtu(ixa);
3625         ixa->ixa_fragsize = pmtu;
3626         /* Make sure ixa_fragsize and ixa_pmtu remain identical */
3627         if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3628                 ixa->ixa_pmtu = pmtu;
3629 
3630         /*
3631          * Extract information useful for some transports.
3632          * First we look for DCE metrics. Then we take what we have in
3633          * the metrics in the route, where the offlink is used if we have
3634          * one.
3635          */
3636         if (uinfo != NULL) {
3637                 bzero(uinfo, sizeof (*uinfo));
3638 
3639                 if (dce->dce_flags & DCEF_UINFO)
3640                         *uinfo = dce->dce_uinfo;
3641 
3642                 rts_merge_metrics(uinfo, &ire->ire_metrics);
3643 
3644                 /* Allow ire_metrics to decrease the path MTU from above */
3645                 if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3646                         uinfo->iulp_mtu = pmtu;
3647 
3648                 uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3649                 uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3650                 uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3651         }
3652 
3653         if (ill != NULL)
3654                 ill_refrele(ill);
3655 
3656         return (error);
3657 
3658 bad_addr:
3659         if (ire != NULL)
3660                 ire_refrele(ire);
3661 
3662         if (ill != NULL)
3663                 ill_refrele(ill);
3664 
3665         /*
3666          * Make sure we don't leave an unreachable ixa_nce in place
3667          * since ip_select_route is used when we unplumb i.e., remove
3668          * references on ixa_ire, ixa_nce, and ixa_dce.
3669          */
3670         nce = ixa->ixa_nce;
3671         if (nce != NULL && nce->nce_is_condemned) {
3672                 nce_refrele(nce);
3673                 ixa->ixa_nce = NULL;
3674                 ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3675         }
3676 
3677         return (error);
3678 }
3679 
3680 
3681 /*
3682  * Get the base MTU for the case when path MTU discovery is not used.
3683  * Takes the MTU of the IRE into account.
3684  */
3685 uint_t
3686 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3687 {
3688         uint_t mtu;
3689         uint_t iremtu = ire->ire_metrics.iulp_mtu;
3690 
3691         if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST))
3692                 mtu = ill->ill_mc_mtu;
3693         else
3694                 mtu = ill->ill_mtu;
3695 
3696         if (iremtu != 0 && iremtu < mtu)
3697                 mtu = iremtu;
3698 
3699         return (mtu);
3700 }
3701 
3702 /*
3703  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3704  * Assumes that ixa_ire, dce, and nce have already been set up.
3705  *
3706  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3707  * We avoid path MTU discovery if it is disabled with ndd.
3708  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3709  *
3710  * NOTE: We also used to turn it off for source routed packets. That
3711  * is no longer required since the dce is per final destination.
3712  */
3713 uint_t
3714 ip_get_pmtu(ip_xmit_attr_t *ixa)
3715 {
3716         ip_stack_t      *ipst = ixa->ixa_ipst;
3717         dce_t           *dce;
3718         nce_t           *nce;
3719         ire_t           *ire;
3720         uint_t          pmtu;
3721 
3722         ire = ixa->ixa_ire;
3723         dce = ixa->ixa_dce;
3724         nce = ixa->ixa_nce;
3725 
3726         /*
3727          * If path MTU discovery has been turned off by ndd, then we ignore
3728          * any dce_pmtu and for IPv4 we will not set DF.
3729          */
3730         if (!ipst->ips_ip_path_mtu_discovery)
3731                 ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3732 
3733         pmtu = IP_MAXPACKET;
3734         /*
3735          * Decide whether whether IPv4 sets DF
3736          * For IPv6 "no DF" means to use the 1280 mtu
3737          */
3738         if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3739                 ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3740         } else {
3741                 ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3742                 if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3743                         pmtu = IPV6_MIN_MTU;
3744         }
3745 
3746         /* Check if the PMTU is to old before we use it */
3747         if ((dce->dce_flags & DCEF_PMTU) &&
3748             TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3749             ipst->ips_ip_pathmtu_interval) {
3750                 /*
3751                  * Older than 20 minutes. Drop the path MTU information.
3752                  */
3753                 mutex_enter(&dce->dce_lock);
3754                 dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3755                 dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3756                 mutex_exit(&dce->dce_lock);
3757                 dce_increment_generation(dce);
3758         }
3759 
3760         /* The metrics on the route can lower the path MTU */
3761         if (ire->ire_metrics.iulp_mtu != 0 &&
3762             ire->ire_metrics.iulp_mtu < pmtu)
3763                 pmtu = ire->ire_metrics.iulp_mtu;
3764 
3765         /*
3766          * If the path MTU is smaller than some minimum, we still use dce_pmtu
3767          * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3768          * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3769          */
3770         if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3771                 if (dce->dce_flags & DCEF_PMTU) {
3772                         if (dce->dce_pmtu < pmtu)
3773                                 pmtu = dce->dce_pmtu;
3774 
3775                         if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3776                                 ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3777                                 ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3778                         } else {
3779                                 ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3780                                 ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3781                         }
3782                 } else {
3783                         ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3784                         ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3785                 }
3786         }
3787 
3788         /*
3789          * If we have an IRE_LOCAL we use the loopback mtu instead of
3790          * the ill for going out the wire i.e., IRE_LOCAL gets the same
3791          * mtu as IRE_LOOPBACK.
3792          */
3793         if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3794                 uint_t loopback_mtu;
3795 
3796                 loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3797                     ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3798 
3799                 if (loopback_mtu < pmtu)
3800                         pmtu = loopback_mtu;
3801         } else if (nce != NULL) {
3802                 /*
3803                  * Make sure we don't exceed the interface MTU.
3804                  * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3805                  * an ill. We'd use the above IP_MAXPACKET in that case just
3806                  * to tell the transport something larger than zero.
3807                  */
3808                 if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST)) {
3809                         if (nce->nce_common->ncec_ill->ill_mc_mtu < pmtu)
3810                                 pmtu = nce->nce_common->ncec_ill->ill_mc_mtu;
3811                         if (nce->nce_common->ncec_ill != nce->nce_ill &&
3812                             nce->nce_ill->ill_mc_mtu < pmtu) {
3813                                 /*
3814                                  * for interfaces in an IPMP group, the mtu of
3815                                  * the nce_ill (under_ill) could be different
3816                                  * from the mtu of the ncec_ill, so we take the
3817                                  * min of the two.
3818                                  */
3819                                 pmtu = nce->nce_ill->ill_mc_mtu;
3820                         }
3821                 } else {
3822                         if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3823                                 pmtu = nce->nce_common->ncec_ill->ill_mtu;
3824                         if (nce->nce_common->ncec_ill != nce->nce_ill &&
3825                             nce->nce_ill->ill_mtu < pmtu) {
3826                                 /*
3827                                  * for interfaces in an IPMP group, the mtu of
3828                                  * the nce_ill (under_ill) could be different
3829                                  * from the mtu of the ncec_ill, so we take the
3830                                  * min of the two.
3831                                  */
3832                                 pmtu = nce->nce_ill->ill_mtu;
3833                         }
3834                 }
3835         }
3836 
3837         /*
3838          * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3839          * Only applies to IPv6.
3840          */
3841         if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3842                 if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3843                         switch (ixa->ixa_use_min_mtu) {
3844                         case IPV6_USE_MIN_MTU_MULTICAST:
3845                                 if (ire->ire_type & IRE_MULTICAST)
3846                                         pmtu = IPV6_MIN_MTU;
3847                                 break;
3848                         case IPV6_USE_MIN_MTU_ALWAYS:
3849                                 pmtu = IPV6_MIN_MTU;
3850                                 break;
3851                         case IPV6_USE_MIN_MTU_NEVER:
3852                                 break;
3853                         }
3854                 } else {
3855                         /* Default is IPV6_USE_MIN_MTU_MULTICAST */
3856                         if (ire->ire_type & IRE_MULTICAST)
3857                                 pmtu = IPV6_MIN_MTU;
3858                 }
3859         }
3860 
3861         /*
3862          * For multirouted IPv6 packets, the IP layer will insert a 8-byte
3863          * fragment header in every packet. We compensate for those cases by
3864          * returning a smaller path MTU to the ULP.
3865          *
3866          * In the case of CGTP then ip_output will add a fragment header.
3867          * Make sure there is room for it by telling a smaller number
3868          * to the transport.
3869          *
3870          * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3871          * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3872          * which is the size of the packets it can send.
3873          */
3874         if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3875                 if ((ire->ire_flags & RTF_MULTIRT) ||
3876                     (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3877                         pmtu -= sizeof (ip6_frag_t);
3878                         ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3879                 }
3880         }
3881 
3882         return (pmtu);
3883 }
3884 
3885 /*
3886  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3887  * the final piece where we don't.  Return a pointer to the first mblk in the
3888  * result, and update the pointer to the next mblk to chew on.  If anything
3889  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3890  * NULL pointer.
3891  */
3892 mblk_t *
3893 ip_carve_mp(mblk_t **mpp, ssize_t len)
3894 {
3895         mblk_t  *mp0;
3896         mblk_t  *mp1;
3897         mblk_t  *mp2;
3898 
3899         if (!len || !mpp || !(mp0 = *mpp))
3900                 return (NULL);
3901         /* If we aren't going to consume the first mblk, we need a dup. */
3902         if (mp0->b_wptr - mp0->b_rptr > len) {
3903                 mp1 = dupb(mp0);
3904                 if (mp1) {
3905                         /* Partition the data between the two mblks. */
3906                         mp1->b_wptr = mp1->b_rptr + len;
3907                         mp0->b_rptr = mp1->b_wptr;
3908                         /*
3909                          * after adjustments if mblk not consumed is now
3910                          * unaligned, try to align it. If this fails free
3911                          * all messages and let upper layer recover.
3912                          */
3913                         if (!OK_32PTR(mp0->b_rptr)) {
3914                                 if (!pullupmsg(mp0, -1)) {
3915                                         freemsg(mp0);
3916                                         freemsg(mp1);
3917                                         *mpp = NULL;
3918                                         return (NULL);
3919                                 }
3920                         }
3921                 }
3922                 return (mp1);
3923         }
3924         /* Eat through as many mblks as we need to get len bytes. */
3925         len -= mp0->b_wptr - mp0->b_rptr;
3926         for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3927                 if (mp2->b_wptr - mp2->b_rptr > len) {
3928                         /*
3929                          * We won't consume the entire last mblk.  Like
3930                          * above, dup and partition it.
3931                          */
3932                         mp1->b_cont = dupb(mp2);
3933                         mp1 = mp1->b_cont;
3934                         if (!mp1) {
3935                                 /*
3936                                  * Trouble.  Rather than go to a lot of
3937                                  * trouble to clean up, we free the messages.
3938                                  * This won't be any worse than losing it on
3939                                  * the wire.
3940                                  */
3941                                 freemsg(mp0);
3942                                 freemsg(mp2);
3943                                 *mpp = NULL;
3944                                 return (NULL);
3945                         }
3946                         mp1->b_wptr = mp1->b_rptr + len;
3947                         mp2->b_rptr = mp1->b_wptr;
3948                         /*
3949                          * after adjustments if mblk not consumed is now
3950                          * unaligned, try to align it. If this fails free
3951                          * all messages and let upper layer recover.
3952                          */
3953                         if (!OK_32PTR(mp2->b_rptr)) {
3954                                 if (!pullupmsg(mp2, -1)) {
3955                                         freemsg(mp0);
3956                                         freemsg(mp2);
3957                                         *mpp = NULL;
3958                                         return (NULL);
3959                                 }
3960                         }
3961                         *mpp = mp2;
3962                         return (mp0);
3963                 }
3964                 /* Decrement len by the amount we just got. */
3965                 len -= mp2->b_wptr - mp2->b_rptr;
3966         }
3967         /*
3968          * len should be reduced to zero now.  If not our caller has
3969          * screwed up.
3970          */
3971         if (len) {
3972                 /* Shouldn't happen! */
3973                 freemsg(mp0);
3974                 *mpp = NULL;
3975                 return (NULL);
3976         }
3977         /*
3978          * We consumed up to exactly the end of an mblk.  Detach the part
3979          * we are returning from the rest of the chain.
3980          */
3981         mp1->b_cont = NULL;
3982         *mpp = mp2;
3983         return (mp0);
3984 }
3985 
3986 /* The ill stream is being unplumbed. Called from ip_close */
3987 int
3988 ip_modclose(ill_t *ill)
3989 {
3990         boolean_t success;
3991         ipsq_t  *ipsq;
3992         ipif_t  *ipif;
3993         queue_t *q = ill->ill_rq;
3994         ip_stack_t      *ipst = ill->ill_ipst;
3995         int     i;
3996         arl_ill_common_t *ai = ill->ill_common;
3997 
3998         /*
3999          * The punlink prior to this may have initiated a capability
4000          * negotiation. But ipsq_enter will block until that finishes or
4001          * times out.
4002          */
4003         success = ipsq_enter(ill, B_FALSE, NEW_OP);
4004 
4005         /*
4006          * Open/close/push/pop is guaranteed to be single threaded
4007          * per stream by STREAMS. FS guarantees that all references
4008          * from top are gone before close is called. So there can't
4009          * be another close thread that has set CONDEMNED on this ill.
4010          * and cause ipsq_enter to return failure.
4011          */
4012         ASSERT(success);
4013         ipsq = ill->ill_phyint->phyint_ipsq;
4014 
4015         /*
4016          * Mark it condemned. No new reference will be made to this ill.
4017          * Lookup functions will return an error. Threads that try to
4018          * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4019          * that the refcnt will drop down to zero.
4020          */
4021         mutex_enter(&ill->ill_lock);
4022         ill->ill_state_flags |= ILL_CONDEMNED;
4023         for (ipif = ill->ill_ipif; ipif != NULL;
4024             ipif = ipif->ipif_next) {
4025                 ipif->ipif_state_flags |= IPIF_CONDEMNED;
4026         }
4027         /*
4028          * Wake up anybody waiting to enter the ipsq. ipsq_enter
4029          * returns  error if ILL_CONDEMNED is set
4030          */
4031         cv_broadcast(&ill->ill_cv);
4032         mutex_exit(&ill->ill_lock);
4033 
4034         /*
4035          * Send all the deferred DLPI messages downstream which came in
4036          * during the small window right before ipsq_enter(). We do this
4037          * without waiting for the ACKs because all the ACKs for M_PROTO
4038          * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4039          */
4040         ill_dlpi_send_deferred(ill);
4041 
4042         /*
4043          * Shut down fragmentation reassembly.
4044          * ill_frag_timer won't start a timer again.
4045          * Now cancel any existing timer
4046          */
4047         (void) untimeout(ill->ill_frag_timer_id);
4048         (void) ill_frag_timeout(ill, 0);
4049 
4050         /*
4051          * Call ill_delete to bring down the ipifs, ilms and ill on
4052          * this ill. Then wait for the refcnts to drop to zero.
4053          * ill_is_freeable checks whether the ill is really quiescent.
4054          * Then make sure that threads that are waiting to enter the
4055          * ipsq have seen the error returned by ipsq_enter and have
4056          * gone away. Then we call ill_delete_tail which does the
4057          * DL_UNBIND_REQ with the driver and then qprocsoff.
4058          */
4059         ill_delete(ill);
4060         mutex_enter(&ill->ill_lock);
4061         while (!ill_is_freeable(ill))
4062                 cv_wait(&ill->ill_cv, &ill->ill_lock);
4063 
4064         while (ill->ill_waiters)
4065                 cv_wait(&ill->ill_cv, &ill->ill_lock);
4066 
4067         mutex_exit(&ill->ill_lock);
4068 
4069         /*
4070          * ill_delete_tail drops reference on ill_ipst, but we need to keep
4071          * it held until the end of the function since the cleanup
4072          * below needs to be able to use the ip_stack_t.
4073          */
4074         netstack_hold(ipst->ips_netstack);
4075 
4076         /* qprocsoff is done via ill_delete_tail */
4077         ill_delete_tail(ill);
4078         /*
4079          * synchronously wait for arp stream to unbind. After this, we
4080          * cannot get any data packets up from the driver.
4081          */
4082         arp_unbind_complete(ill);
4083         ASSERT(ill->ill_ipst == NULL);
4084 
4085         /*
4086          * Walk through all conns and qenable those that have queued data.
4087          * Close synchronization needs this to
4088          * be done to ensure that all upper layers blocked
4089          * due to flow control to the closing device
4090          * get unblocked.
4091          */
4092         ip1dbg(("ip_wsrv: walking\n"));
4093         for (i = 0; i < TX_FANOUT_SIZE; i++) {
4094                 conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4095         }
4096 
4097         /*
4098          * ai can be null if this is an IPv6 ill, or if the IPv4
4099          * stream is being torn down before ARP was plumbed (e.g.,
4100          * /sbin/ifconfig plumbing a stream twice, and encountering
4101          * an error
4102          */
4103         if (ai != NULL) {
4104                 ASSERT(!ill->ill_isv6);
4105                 mutex_enter(&ai->ai_lock);
4106                 ai->ai_ill = NULL;
4107                 if (ai->ai_arl == NULL) {
4108                         mutex_destroy(&ai->ai_lock);
4109                         kmem_free(ai, sizeof (*ai));
4110                 } else {
4111                         cv_signal(&ai->ai_ill_unplumb_done);
4112                         mutex_exit(&ai->ai_lock);
4113                 }
4114         }
4115 
4116         mutex_enter(&ipst->ips_ip_mi_lock);
4117         mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4118         mutex_exit(&ipst->ips_ip_mi_lock);
4119 
4120         /*
4121          * credp could be null if the open didn't succeed and ip_modopen
4122          * itself calls ip_close.
4123          */
4124         if (ill->ill_credp != NULL)
4125                 crfree(ill->ill_credp);
4126 
4127         mutex_destroy(&ill->ill_saved_ire_lock);
4128         mutex_destroy(&ill->ill_lock);
4129         rw_destroy(&ill->ill_mcast_lock);
4130         mutex_destroy(&ill->ill_mcast_serializer);
4131         list_destroy(&ill->ill_nce);
4132 
4133         /*
4134          * Now we are done with the module close pieces that
4135          * need the netstack_t.
4136          */
4137         netstack_rele(ipst->ips_netstack);
4138 
4139         mi_close_free((IDP)ill);
4140         q->q_ptr = WR(q)->q_ptr = NULL;
4141 
4142         ipsq_exit(ipsq);
4143 
4144         return (0);
4145 }
4146 
4147 /*
4148  * This is called as part of close() for IP, UDP, ICMP, and RTS
4149  * in order to quiesce the conn.
4150  */
4151 void
4152 ip_quiesce_conn(conn_t *connp)
4153 {
4154         boolean_t       drain_cleanup_reqd = B_FALSE;
4155         boolean_t       conn_ioctl_cleanup_reqd = B_FALSE;
4156         boolean_t       ilg_cleanup_reqd = B_FALSE;
4157         ip_stack_t      *ipst;
4158 
4159         ASSERT(!IPCL_IS_TCP(connp));
4160         ipst = connp->conn_netstack->netstack_ip;
4161 
4162         /*
4163          * Mark the conn as closing, and this conn must not be
4164          * inserted in future into any list. Eg. conn_drain_insert(),
4165          * won't insert this conn into the conn_drain_list.
4166          *
4167          * conn_idl, and conn_ilg cannot get set henceforth.
4168          */
4169         mutex_enter(&connp->conn_lock);
4170         ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4171         connp->conn_state_flags |= CONN_CLOSING;
4172         if (connp->conn_idl != NULL)
4173                 drain_cleanup_reqd = B_TRUE;
4174         if (connp->conn_oper_pending_ill != NULL)
4175                 conn_ioctl_cleanup_reqd = B_TRUE;
4176         if (connp->conn_dhcpinit_ill != NULL) {
4177                 ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4178                 atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4179                 ill_set_inputfn(connp->conn_dhcpinit_ill);
4180                 connp->conn_dhcpinit_ill = NULL;
4181         }
4182         if (connp->conn_ilg != NULL)
4183                 ilg_cleanup_reqd = B_TRUE;
4184         mutex_exit(&connp->conn_lock);
4185 
4186         if (conn_ioctl_cleanup_reqd)
4187                 conn_ioctl_cleanup(connp);
4188 
4189         if (is_system_labeled() && connp->conn_anon_port) {
4190                 (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4191                     connp->conn_mlp_type, connp->conn_proto,
4192                     ntohs(connp->conn_lport), B_FALSE);
4193                 connp->conn_anon_port = 0;
4194         }
4195         connp->conn_mlp_type = mlptSingle;
4196 
4197         /*
4198          * Remove this conn from any fanout list it is on.
4199          * and then wait for any threads currently operating
4200          * on this endpoint to finish
4201          */
4202         ipcl_hash_remove(connp);
4203 
4204         /*
4205          * Remove this conn from the drain list, and do any other cleanup that
4206          * may be required.  (TCP conns are never flow controlled, and
4207          * conn_idl will be NULL.)
4208          */
4209         if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4210                 idl_t *idl = connp->conn_idl;
4211 
4212                 mutex_enter(&idl->idl_lock);
4213                 conn_drain(connp, B_TRUE);
4214                 mutex_exit(&idl->idl_lock);
4215         }
4216 
4217         if (connp == ipst->ips_ip_g_mrouter)
4218                 (void) ip_mrouter_done(ipst);
4219 
4220         if (ilg_cleanup_reqd)
4221                 ilg_delete_all(connp);
4222 
4223         /*
4224          * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4225          * callers from write side can't be there now because close
4226          * is in progress. The only other caller is ipcl_walk
4227          * which checks for the condemned flag.
4228          */
4229         mutex_enter(&connp->conn_lock);
4230         connp->conn_state_flags |= CONN_CONDEMNED;
4231         while (connp->conn_ref != 1)
4232                 cv_wait(&connp->conn_cv, &connp->conn_lock);
4233         connp->conn_state_flags |= CONN_QUIESCED;
4234         mutex_exit(&connp->conn_lock);
4235 }
4236 
4237 /* ARGSUSED */
4238 int
4239 ip_close(queue_t *q, int flags)
4240 {
4241         conn_t          *connp;
4242 
4243         /*
4244          * Call the appropriate delete routine depending on whether this is
4245          * a module or device.
4246          */
4247         if (WR(q)->q_next != NULL) {
4248                 /* This is a module close */
4249                 return (ip_modclose((ill_t *)q->q_ptr));
4250         }
4251 
4252         connp = q->q_ptr;
4253         ip_quiesce_conn(connp);
4254 
4255         qprocsoff(q);
4256 
4257         /*
4258          * Now we are truly single threaded on this stream, and can
4259          * delete the things hanging off the connp, and finally the connp.
4260          * We removed this connp from the fanout list, it cannot be
4261          * accessed thru the fanouts, and we already waited for the
4262          * conn_ref to drop to 0. We are already in close, so
4263          * there cannot be any other thread from the top. qprocsoff
4264          * has completed, and service has completed or won't run in
4265          * future.
4266          */
4267         ASSERT(connp->conn_ref == 1);
4268 
4269         inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4270 
4271         connp->conn_ref--;
4272         ipcl_conn_destroy(connp);
4273 
4274         q->q_ptr = WR(q)->q_ptr = NULL;
4275         return (0);
4276 }
4277 
4278 /*
4279  * Wapper around putnext() so that ip_rts_request can merely use
4280  * conn_recv.
4281  */
4282 /*ARGSUSED2*/
4283 static void
4284 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4285 {
4286         conn_t *connp = (conn_t *)arg1;
4287 
4288         putnext(connp->conn_rq, mp);
4289 }
4290 
4291 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4292 /* ARGSUSED */
4293 static void
4294 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4295 {
4296         freemsg(mp);
4297 }
4298 
4299 /*
4300  * Called when the module is about to be unloaded
4301  */
4302 void
4303 ip_ddi_destroy(void)
4304 {
4305         /* This needs to be called before destroying any transports. */
4306         mutex_enter(&cpu_lock);
4307         unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4308         mutex_exit(&cpu_lock);
4309 
4310         tnet_fini();
4311 
4312         icmp_ddi_g_destroy();
4313         rts_ddi_g_destroy();
4314         udp_ddi_g_destroy();
4315         sctp_ddi_g_destroy();
4316         tcp_ddi_g_destroy();
4317         ilb_ddi_g_destroy();
4318         dce_g_destroy();
4319         ipsec_policy_g_destroy();
4320         ipcl_g_destroy();
4321         ip_net_g_destroy();
4322         ip_ire_g_fini();
4323         inet_minor_destroy(ip_minor_arena_sa);
4324 #if defined(_LP64)
4325         inet_minor_destroy(ip_minor_arena_la);
4326 #endif
4327 
4328 #ifdef DEBUG
4329         list_destroy(&ip_thread_list);
4330         rw_destroy(&ip_thread_rwlock);
4331         tsd_destroy(&ip_thread_data);
4332 #endif
4333 
4334         netstack_unregister(NS_IP);
4335 }
4336 
4337 /*
4338  * First step in cleanup.
4339  */
4340 /* ARGSUSED */
4341 static void
4342 ip_stack_shutdown(netstackid_t stackid, void *arg)
4343 {
4344         ip_stack_t *ipst = (ip_stack_t *)arg;
4345         kt_did_t ktid;
4346 
4347 #ifdef NS_DEBUG
4348         printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4349 #endif
4350 
4351         /*
4352          * Perform cleanup for special interfaces (loopback and IPMP).
4353          */
4354         ip_interface_cleanup(ipst);
4355 
4356         /*
4357          * The *_hook_shutdown()s start the process of notifying any
4358          * consumers that things are going away.... nothing is destroyed.
4359          */
4360         ipv4_hook_shutdown(ipst);
4361         ipv6_hook_shutdown(ipst);
4362         arp_hook_shutdown(ipst);
4363 
4364         mutex_enter(&ipst->ips_capab_taskq_lock);
4365         ktid = ipst->ips_capab_taskq_thread->t_did;
4366         ipst->ips_capab_taskq_quit = B_TRUE;
4367         cv_signal(&ipst->ips_capab_taskq_cv);
4368         mutex_exit(&ipst->ips_capab_taskq_lock);
4369 
4370         /*
4371          * In rare occurrences, particularly on virtual hardware where CPUs can
4372          * be de-scheduled, the thread that we just signaled will not run until
4373          * after we have gotten through parts of ip_stack_fini. If that happens
4374          * then we'll try to grab the ips_capab_taskq_lock as part of returning
4375          * from cv_wait which no longer exists.
4376          */
4377         thread_join(ktid);
4378 }
4379 
4380 /*
4381  * Free the IP stack instance.
4382  */
4383 static void
4384 ip_stack_fini(netstackid_t stackid, void *arg)
4385 {
4386         ip_stack_t *ipst = (ip_stack_t *)arg;
4387         int ret;
4388 
4389 #ifdef NS_DEBUG
4390         printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4391 #endif
4392         /*
4393          * At this point, all of the notifications that the events and
4394          * protocols are going away have been run, meaning that we can
4395          * now set about starting to clean things up.
4396          */
4397         ipobs_fini(ipst);
4398         ipv4_hook_destroy(ipst);
4399         ipv6_hook_destroy(ipst);
4400         arp_hook_destroy(ipst);
4401         ip_net_destroy(ipst);
4402 
4403         ipmp_destroy(ipst);
4404 
4405         ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4406         ipst->ips_ip_mibkp = NULL;
4407         icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4408         ipst->ips_icmp_mibkp = NULL;
4409         ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4410         ipst->ips_ip_kstat = NULL;
4411         bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4412         ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4413         ipst->ips_ip6_kstat = NULL;
4414         bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4415 
4416         kmem_free(ipst->ips_propinfo_tbl,
4417             ip_propinfo_count * sizeof (mod_prop_info_t));
4418         ipst->ips_propinfo_tbl = NULL;
4419 
4420         dce_stack_destroy(ipst);
4421         ip_mrouter_stack_destroy(ipst);
4422 
4423         /*
4424          * Quiesce all of our timers. Note we set the quiesce flags before we
4425          * call untimeout. The slowtimers may actually kick off another instance
4426          * of the non-slow timers.
4427          */
4428         mutex_enter(&ipst->ips_igmp_timer_lock);
4429         ipst->ips_igmp_timer_quiesce = B_TRUE;
4430         mutex_exit(&ipst->ips_igmp_timer_lock);
4431 
4432         mutex_enter(&ipst->ips_mld_timer_lock);
4433         ipst->ips_mld_timer_quiesce = B_TRUE;
4434         mutex_exit(&ipst->ips_mld_timer_lock);
4435 
4436         mutex_enter(&ipst->ips_igmp_slowtimeout_lock);
4437         ipst->ips_igmp_slowtimeout_quiesce = B_TRUE;
4438         mutex_exit(&ipst->ips_igmp_slowtimeout_lock);
4439 
4440         mutex_enter(&ipst->ips_mld_slowtimeout_lock);
4441         ipst->ips_mld_slowtimeout_quiesce = B_TRUE;
4442         mutex_exit(&ipst->ips_mld_slowtimeout_lock);
4443 
4444         ret = untimeout(ipst->ips_igmp_timeout_id);
4445         if (ret == -1) {
4446                 ASSERT(ipst->ips_igmp_timeout_id == 0);
4447         } else {
4448                 ASSERT(ipst->ips_igmp_timeout_id != 0);
4449                 ipst->ips_igmp_timeout_id = 0;
4450         }
4451         ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4452         if (ret == -1) {
4453                 ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4454         } else {
4455                 ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4456                 ipst->ips_igmp_slowtimeout_id = 0;
4457         }
4458         ret = untimeout(ipst->ips_mld_timeout_id);
4459         if (ret == -1) {
4460                 ASSERT(ipst->ips_mld_timeout_id == 0);
4461         } else {
4462                 ASSERT(ipst->ips_mld_timeout_id != 0);
4463                 ipst->ips_mld_timeout_id = 0;
4464         }
4465         ret = untimeout(ipst->ips_mld_slowtimeout_id);
4466         if (ret == -1) {
4467                 ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4468         } else {
4469                 ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4470                 ipst->ips_mld_slowtimeout_id = 0;
4471         }
4472 
4473         ip_ire_fini(ipst);
4474         ip6_asp_free(ipst);
4475         conn_drain_fini(ipst);
4476         ipcl_destroy(ipst);
4477 
4478         mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4479         mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4480         kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4481         ipst->ips_ndp4 = NULL;
4482         kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4483         ipst->ips_ndp6 = NULL;
4484 
4485         if (ipst->ips_loopback_ksp != NULL) {
4486                 kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4487                 ipst->ips_loopback_ksp = NULL;
4488         }
4489 
4490         mutex_destroy(&ipst->ips_capab_taskq_lock);
4491         cv_destroy(&ipst->ips_capab_taskq_cv);
4492 
4493         rw_destroy(&ipst->ips_srcid_lock);
4494 
4495         mutex_destroy(&ipst->ips_ip_mi_lock);
4496         rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4497 
4498         mutex_destroy(&ipst->ips_igmp_timer_lock);
4499         mutex_destroy(&ipst->ips_mld_timer_lock);
4500         mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4501         mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4502         mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4503         rw_destroy(&ipst->ips_ill_g_lock);
4504 
4505         kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4506         ipst->ips_phyint_g_list = NULL;
4507         kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4508         ipst->ips_ill_g_heads = NULL;
4509 
4510         ldi_ident_release(ipst->ips_ldi_ident);
4511         kmem_free(ipst, sizeof (*ipst));
4512 }
4513 
4514 /*
4515  * This function is called from the TSD destructor, and is used to debug
4516  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4517  * details.
4518  */
4519 static void
4520 ip_thread_exit(void *phash)
4521 {
4522         th_hash_t *thh = phash;
4523 
4524         rw_enter(&ip_thread_rwlock, RW_WRITER);
4525         list_remove(&ip_thread_list, thh);
4526         rw_exit(&ip_thread_rwlock);
4527         mod_hash_destroy_hash(thh->thh_hash);
4528         kmem_free(thh, sizeof (*thh));
4529 }
4530 
4531 /*
4532  * Called when the IP kernel module is loaded into the kernel
4533  */
4534 void
4535 ip_ddi_init(void)
4536 {
4537         ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4538 
4539         /*
4540          * For IP and TCP the minor numbers should start from 2 since we have 4
4541          * initial devices: ip, ip6, tcp, tcp6.
4542          */
4543         /*
4544          * If this is a 64-bit kernel, then create two separate arenas -
4545          * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4546          * other for socket apps in the range 2^^18 through 2^^32-1.
4547          */
4548         ip_minor_arena_la = NULL;
4549         ip_minor_arena_sa = NULL;
4550 #if defined(_LP64)
4551         if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4552             INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4553                 cmn_err(CE_PANIC,
4554                     "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4555         }
4556         if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4557             MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4558                 cmn_err(CE_PANIC,
4559                     "ip_ddi_init: ip_minor_arena_la creation failed\n");
4560         }
4561 #else
4562         if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4563             INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4564                 cmn_err(CE_PANIC,
4565                     "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4566         }
4567 #endif
4568         ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4569 
4570         ipcl_g_init();
4571         ip_ire_g_init();
4572         ip_net_g_init();
4573 
4574 #ifdef DEBUG
4575         tsd_create(&ip_thread_data, ip_thread_exit);
4576         rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4577         list_create(&ip_thread_list, sizeof (th_hash_t),
4578             offsetof(th_hash_t, thh_link));
4579 #endif
4580         ipsec_policy_g_init();
4581         tcp_ddi_g_init();
4582         sctp_ddi_g_init();
4583         dce_g_init();
4584 
4585         /*
4586          * We want to be informed each time a stack is created or
4587          * destroyed in the kernel, so we can maintain the
4588          * set of udp_stack_t's.
4589          */
4590         netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4591             ip_stack_fini);
4592 
4593         tnet_init();
4594 
4595         udp_ddi_g_init();
4596         rts_ddi_g_init();
4597         icmp_ddi_g_init();
4598         ilb_ddi_g_init();
4599 
4600         /* This needs to be called after all transports are initialized. */
4601         mutex_enter(&cpu_lock);
4602         register_cpu_setup_func(ip_tp_cpu_update, NULL);
4603         mutex_exit(&cpu_lock);
4604 }
4605 
4606 /*
4607  * Initialize the IP stack instance.
4608  */
4609 static void *
4610 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4611 {
4612         ip_stack_t      *ipst;
4613         size_t          arrsz;
4614         major_t         major;
4615 
4616 #ifdef NS_DEBUG
4617         printf("ip_stack_init(stack %d)\n", stackid);
4618 #endif
4619 
4620         ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4621         ipst->ips_netstack = ns;
4622 
4623         ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4624             KM_SLEEP);
4625         ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4626             KM_SLEEP);
4627         ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4628         ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4629         mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4630         mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4631 
4632         mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4633         ipst->ips_igmp_deferred_next = INFINITY;
4634         mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4635         ipst->ips_mld_deferred_next = INFINITY;
4636         mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4637         mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4638         mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4639         mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4640         rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4641         rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4642 
4643         ipcl_init(ipst);
4644         ip_ire_init(ipst);
4645         ip6_asp_init(ipst);
4646         ipif_init(ipst);
4647         conn_drain_init(ipst);
4648         ip_mrouter_stack_init(ipst);
4649         dce_stack_init(ipst);
4650 
4651         ipst->ips_ip_multirt_log_interval = 1000;
4652 
4653         ipst->ips_ill_index = 1;
4654 
4655         ipst->ips_saved_ip_forwarding = -1;
4656         ipst->ips_reg_vif_num = ALL_VIFS;    /* Index to Register vif */
4657 
4658         arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4659         ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4660         bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4661 
4662         ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4663         ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4664         ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4665         ipst->ips_ip6_kstat =
4666             ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4667 
4668         ipst->ips_ip_src_id = 1;
4669         rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4670 
4671         ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4672 
4673         ip_net_init(ipst, ns);
4674         ipv4_hook_init(ipst);
4675         ipv6_hook_init(ipst);
4676         arp_hook_init(ipst);
4677         ipmp_init(ipst);
4678         ipobs_init(ipst);
4679 
4680         /*
4681          * Create the taskq dispatcher thread and initialize related stuff.
4682          */
4683         mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4684         cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4685         ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4686             ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4687 
4688         major = mod_name_to_major(INET_NAME);
4689         (void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4690         return (ipst);
4691 }
4692 
4693 /*
4694  * Allocate and initialize a DLPI template of the specified length.  (May be
4695  * called as writer.)
4696  */
4697 mblk_t *
4698 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4699 {
4700         mblk_t  *mp;
4701 
4702         mp = allocb(len, BPRI_MED);
4703         if (!mp)
4704                 return (NULL);
4705 
4706         /*
4707          * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4708          * of which we don't seem to use) are sent with M_PCPROTO, and
4709          * that other DLPI are M_PROTO.
4710          */
4711         if (prim == DL_INFO_REQ) {
4712                 mp->b_datap->db_type = M_PCPROTO;
4713         } else {
4714                 mp->b_datap->db_type = M_PROTO;
4715         }
4716 
4717         mp->b_wptr = mp->b_rptr + len;
4718         bzero(mp->b_rptr, len);
4719         ((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4720         return (mp);
4721 }
4722 
4723 /*
4724  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4725  */
4726 mblk_t *
4727 ip_dlnotify_alloc(uint_t notification, uint_t data)
4728 {
4729         dl_notify_ind_t *notifyp;
4730         mblk_t          *mp;
4731 
4732         if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4733                 return (NULL);
4734 
4735         notifyp = (dl_notify_ind_t *)mp->b_rptr;
4736         notifyp->dl_notification = notification;
4737         notifyp->dl_data = data;
4738         return (mp);
4739 }
4740 
4741 mblk_t *
4742 ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
4743 {
4744         dl_notify_ind_t *notifyp;
4745         mblk_t          *mp;
4746 
4747         if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4748                 return (NULL);
4749 
4750         notifyp = (dl_notify_ind_t *)mp->b_rptr;
4751         notifyp->dl_notification = notification;
4752         notifyp->dl_data1 = data1;
4753         notifyp->dl_data2 = data2;
4754         return (mp);
4755 }
4756 
4757 /*
4758  * Debug formatting routine.  Returns a character string representation of the
4759  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4760  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4761  *
4762  * Once the ndd table-printing interfaces are removed, this can be changed to
4763  * standard dotted-decimal form.
4764  */
4765 char *
4766 ip_dot_addr(ipaddr_t addr, char *buf)
4767 {
4768         uint8_t *ap = (uint8_t *)&addr;
4769 
4770         (void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4771             ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4772         return (buf);
4773 }
4774 
4775 /*
4776  * Write the given MAC address as a printable string in the usual colon-
4777  * separated format.
4778  */
4779 const char *
4780 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4781 {
4782         char *bp;
4783 
4784         if (alen == 0 || buflen < 4)
4785                 return ("?");
4786         bp = buf;
4787         for (;;) {
4788                 /*
4789                  * If there are more MAC address bytes available, but we won't
4790                  * have any room to print them, then add "..." to the string
4791                  * instead.  See below for the 'magic number' explanation.
4792                  */
4793                 if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4794                         (void) strcpy(bp, "...");
4795                         break;
4796                 }
4797                 (void) sprintf(bp, "%02x", *addr++);
4798                 bp += 2;
4799                 if (--alen == 0)
4800                         break;
4801                 *bp++ = ':';
4802                 buflen -= 3;
4803                 /*
4804                  * At this point, based on the first 'if' statement above,
4805                  * either alen == 1 and buflen >= 3, or alen > 1 and
4806                  * buflen >= 4.  The first case leaves room for the final "xx"
4807                  * number and trailing NUL byte.  The second leaves room for at
4808                  * least "...".  Thus the apparently 'magic' numbers chosen for
4809                  * that statement.
4810                  */
4811         }
4812         return (buf);
4813 }
4814 
4815 /*
4816  * Called when it is conceptually a ULP that would sent the packet
4817  * e.g., port unreachable and protocol unreachable. Check that the packet
4818  * would have passed the IPsec global policy before sending the error.
4819  *
4820  * Send an ICMP error after patching up the packet appropriately.
4821  * Uses ip_drop_input and bumps the appropriate MIB.
4822  */
4823 void
4824 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4825     ip_recv_attr_t *ira)
4826 {
4827         ipha_t          *ipha;
4828         boolean_t       secure;
4829         ill_t           *ill = ira->ira_ill;
4830         ip_stack_t      *ipst = ill->ill_ipst;
4831         netstack_t      *ns = ipst->ips_netstack;
4832         ipsec_stack_t   *ipss = ns->netstack_ipsec;
4833 
4834         secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4835 
4836         /*
4837          * We are generating an icmp error for some inbound packet.
4838          * Called from all ip_fanout_(udp, tcp, proto) functions.
4839          * Before we generate an error, check with global policy
4840          * to see whether this is allowed to enter the system. As
4841          * there is no "conn", we are checking with global policy.
4842          */
4843         ipha = (ipha_t *)mp->b_rptr;
4844         if (secure || ipss->ipsec_inbound_v4_policy_present) {
4845                 mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4846                 if (mp == NULL)
4847                         return;
4848         }
4849 
4850         /* We never send errors for protocols that we do implement */
4851         if (ira->ira_protocol == IPPROTO_ICMP ||
4852             ira->ira_protocol == IPPROTO_IGMP) {
4853                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4854                 ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4855                 freemsg(mp);
4856                 return;
4857         }
4858         /*
4859          * Have to correct checksum since
4860          * the packet might have been
4861          * fragmented and the reassembly code in ip_rput
4862          * does not restore the IP checksum.
4863          */
4864         ipha->ipha_hdr_checksum = 0;
4865         ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4866 
4867         switch (icmp_type) {
4868         case ICMP_DEST_UNREACHABLE:
4869                 switch (icmp_code) {
4870                 case ICMP_PROTOCOL_UNREACHABLE:
4871                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4872                         ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4873                         break;
4874                 case ICMP_PORT_UNREACHABLE:
4875                         BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4876                         ip_drop_input("ipIfStatsNoPorts", mp, ill);
4877                         break;
4878                 }
4879 
4880                 icmp_unreachable(mp, icmp_code, ira);
4881                 break;
4882         default:
4883 #ifdef DEBUG
4884                 panic("ip_fanout_send_icmp_v4: wrong type");
4885                 /*NOTREACHED*/
4886 #else
4887                 freemsg(mp);
4888                 break;
4889 #endif
4890         }
4891 }
4892 
4893 /*
4894  * Used to send an ICMP error message when a packet is received for
4895  * a protocol that is not supported. The mblk passed as argument
4896  * is consumed by this function.
4897  */
4898 void
4899 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4900 {
4901         ipha_t          *ipha;
4902 
4903         ipha = (ipha_t *)mp->b_rptr;
4904         if (ira->ira_flags & IRAF_IS_IPV4) {
4905                 ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4906                 ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4907                     ICMP_PROTOCOL_UNREACHABLE, ira);
4908         } else {
4909                 ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4910                 ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4911                     ICMP6_PARAMPROB_NEXTHEADER, ira);
4912         }
4913 }
4914 
4915 /*
4916  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4917  * Handles IPv4 and IPv6.
4918  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4919  * Caller is responsible for dropping references to the conn.
4920  */
4921 void
4922 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4923     ip_recv_attr_t *ira)
4924 {
4925         ill_t           *ill = ira->ira_ill;
4926         ip_stack_t      *ipst = ill->ill_ipst;
4927         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
4928         boolean_t       secure;
4929         uint_t          protocol = ira->ira_protocol;
4930         iaflags_t       iraflags = ira->ira_flags;
4931         queue_t         *rq;
4932 
4933         secure = iraflags & IRAF_IPSEC_SECURE;
4934 
4935         rq = connp->conn_rq;
4936         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4937                 switch (protocol) {
4938                 case IPPROTO_ICMPV6:
4939                         BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4940                         break;
4941                 case IPPROTO_ICMP:
4942                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4943                         break;
4944                 default:
4945                         BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4946                         break;
4947                 }
4948                 freemsg(mp);
4949                 return;
4950         }
4951 
4952         ASSERT(!(IPCL_IS_IPTUN(connp)));
4953 
4954         if (((iraflags & IRAF_IS_IPV4) ?
4955             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4956             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4957             secure) {
4958                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
4959                     ip6h, ira);
4960                 if (mp == NULL) {
4961                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4962                         /* Note that mp is NULL */
4963                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
4964                         return;
4965                 }
4966         }
4967 
4968         if (iraflags & IRAF_ICMP_ERROR) {
4969                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
4970         } else {
4971                 ill_t *rill = ira->ira_rill;
4972 
4973                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4974                 ira->ira_ill = ira->ira_rill = NULL;
4975                 /* Send it upstream */
4976                 (connp->conn_recv)(connp, mp, NULL, ira);
4977                 ira->ira_ill = ill;
4978                 ira->ira_rill = rill;
4979         }
4980 }
4981 
4982 /*
4983  * Handle protocols with which IP is less intimate.  There
4984  * can be more than one stream bound to a particular
4985  * protocol.  When this is the case, normally each one gets a copy
4986  * of any incoming packets.
4987  *
4988  * IPsec NOTE :
4989  *
4990  * Don't allow a secure packet going up a non-secure connection.
4991  * We don't allow this because
4992  *
4993  * 1) Reply might go out in clear which will be dropped at
4994  *    the sending side.
4995  * 2) If the reply goes out in clear it will give the
4996  *    adversary enough information for getting the key in
4997  *    most of the cases.
4998  *
4999  * Moreover getting a secure packet when we expect clear
5000  * implies that SA's were added without checking for
5001  * policy on both ends. This should not happen once ISAKMP
5002  * is used to negotiate SAs as SAs will be added only after
5003  * verifying the policy.
5004  *
5005  * Zones notes:
5006  * Earlier in ip_input on a system with multiple shared-IP zones we
5007  * duplicate the multicast and broadcast packets and send them up
5008  * with each explicit zoneid that exists on that ill.
5009  * This means that here we can match the zoneid with SO_ALLZONES being special.
5010  */
5011 void
5012 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5013 {
5014         mblk_t          *mp1;
5015         ipaddr_t        laddr;
5016         conn_t          *connp, *first_connp, *next_connp;
5017         connf_t         *connfp;
5018         ill_t           *ill = ira->ira_ill;
5019         ip_stack_t      *ipst = ill->ill_ipst;
5020 
5021         laddr = ipha->ipha_dst;
5022 
5023         connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5024         mutex_enter(&connfp->connf_lock);
5025         connp = connfp->connf_head;
5026         for (connp = connfp->connf_head; connp != NULL;
5027             connp = connp->conn_next) {
5028                 /* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5029                 if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5030                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5031                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5032                         break;
5033                 }
5034         }
5035 
5036         if (connp == NULL) {
5037                 /*
5038                  * No one bound to these addresses.  Is
5039                  * there a client that wants all
5040                  * unclaimed datagrams?
5041                  */
5042                 mutex_exit(&connfp->connf_lock);
5043                 ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5044                     ICMP_PROTOCOL_UNREACHABLE, ira);
5045                 return;
5046         }
5047 
5048         ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5049 
5050         CONN_INC_REF(connp);
5051         first_connp = connp;
5052         connp = connp->conn_next;
5053 
5054         for (;;) {
5055                 while (connp != NULL) {
5056                         /* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5057                         if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5058                             (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5059                             tsol_receive_local(mp, &laddr, IPV4_VERSION,
5060                             ira, connp)))
5061                                 break;
5062                         connp = connp->conn_next;
5063                 }
5064 
5065                 if (connp == NULL) {
5066                         /* No more interested clients */
5067                         connp = first_connp;
5068                         break;
5069                 }
5070                 if (((mp1 = dupmsg(mp)) == NULL) &&
5071                     ((mp1 = copymsg(mp)) == NULL)) {
5072                         /* Memory allocation failed */
5073                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5074                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
5075                         connp = first_connp;
5076                         break;
5077                 }
5078 
5079                 CONN_INC_REF(connp);
5080                 mutex_exit(&connfp->connf_lock);
5081 
5082                 ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5083                     ira);
5084 
5085                 mutex_enter(&connfp->connf_lock);
5086                 /* Follow the next pointer before releasing the conn. */
5087                 next_connp = connp->conn_next;
5088                 CONN_DEC_REF(connp);
5089                 connp = next_connp;
5090         }
5091 
5092         /* Last one.  Send it upstream. */
5093         mutex_exit(&connfp->connf_lock);
5094 
5095         ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5096 
5097         CONN_DEC_REF(connp);
5098 }
5099 
5100 /*
5101  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5102  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5103  * is not consumed.
5104  *
5105  * One of three things can happen, all of which affect the passed-in mblk:
5106  *
5107  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5108  *
5109  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5110  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5111  *
5112  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5113  */
5114 mblk_t *
5115 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5116 {
5117         int shift, plen, iph_len;
5118         ipha_t *ipha;
5119         udpha_t *udpha;
5120         uint32_t *spi;
5121         uint32_t esp_ports;
5122         uint8_t *orptr;
5123         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
5124         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
5125 
5126         ipha = (ipha_t *)mp->b_rptr;
5127         iph_len = ira->ira_ip_hdr_length;
5128         plen = ira->ira_pktlen;
5129 
5130         if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5131                 /*
5132                  * Most likely a keepalive for the benefit of an intervening
5133                  * NAT.  These aren't for us, per se, so drop it.
5134                  *
5135                  * RFC 3947/8 doesn't say for sure what to do for 2-3
5136                  * byte packets (keepalives are 1-byte), but we'll drop them
5137                  * also.
5138                  */
5139                 ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5140                     DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5141                 return (NULL);
5142         }
5143 
5144         if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5145                 /* might as well pull it all up - it might be ESP. */
5146                 if (!pullupmsg(mp, -1)) {
5147                         ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5148                             DROPPER(ipss, ipds_esp_nomem),
5149                             &ipss->ipsec_dropper);
5150                         return (NULL);
5151                 }
5152 
5153                 ipha = (ipha_t *)mp->b_rptr;
5154         }
5155         spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5156         if (*spi == 0) {
5157                 /* UDP packet - remove 0-spi. */
5158                 shift = sizeof (uint32_t);
5159         } else {
5160                 /* ESP-in-UDP packet - reduce to ESP. */
5161                 ipha->ipha_protocol = IPPROTO_ESP;
5162                 shift = sizeof (udpha_t);
5163         }
5164 
5165         /* Fix IP header */
5166         ira->ira_pktlen = (plen - shift);
5167         ipha->ipha_length = htons(ira->ira_pktlen);
5168         ipha->ipha_hdr_checksum = 0;
5169 
5170         orptr = mp->b_rptr;
5171         mp->b_rptr += shift;
5172 
5173         udpha = (udpha_t *)(orptr + iph_len);
5174         if (*spi == 0) {
5175                 ASSERT((uint8_t *)ipha == orptr);
5176                 udpha->uha_length = htons(plen - shift - iph_len);
5177                 iph_len += sizeof (udpha_t);    /* For the call to ovbcopy(). */
5178                 esp_ports = 0;
5179         } else {
5180                 esp_ports = *((uint32_t *)udpha);
5181                 ASSERT(esp_ports != 0);
5182         }
5183         ovbcopy(orptr, orptr + shift, iph_len);
5184         if (esp_ports != 0) /* Punt up for ESP processing. */ {
5185                 ipha = (ipha_t *)(orptr + shift);
5186 
5187                 ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5188                 ira->ira_esp_udp_ports = esp_ports;
5189                 ip_fanout_v4(mp, ipha, ira);
5190                 return (NULL);
5191         }
5192         return (mp);
5193 }
5194 
5195 /*
5196  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5197  * Handles IPv4 and IPv6.
5198  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5199  * Caller is responsible for dropping references to the conn.
5200  */
5201 void
5202 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5203     ip_recv_attr_t *ira)
5204 {
5205         ill_t           *ill = ira->ira_ill;
5206         ip_stack_t      *ipst = ill->ill_ipst;
5207         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
5208         boolean_t       secure;
5209         iaflags_t       iraflags = ira->ira_flags;
5210 
5211         secure = iraflags & IRAF_IPSEC_SECURE;
5212 
5213         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5214             !canputnext(connp->conn_rq)) {
5215                 BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5216                 freemsg(mp);
5217                 return;
5218         }
5219 
5220         if (((iraflags & IRAF_IS_IPV4) ?
5221             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5222             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5223             secure) {
5224                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
5225                     ip6h, ira);
5226                 if (mp == NULL) {
5227                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5228                         /* Note that mp is NULL */
5229                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
5230                         return;
5231                 }
5232         }
5233 
5234         /*
5235          * Since this code is not used for UDP unicast we don't need a NAT_T
5236          * check. Only ip_fanout_v4 has that check.
5237          */
5238         if (ira->ira_flags & IRAF_ICMP_ERROR) {
5239                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
5240         } else {
5241                 ill_t *rill = ira->ira_rill;
5242 
5243                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5244                 ira->ira_ill = ira->ira_rill = NULL;
5245                 /* Send it upstream */
5246                 (connp->conn_recv)(connp, mp, NULL, ira);
5247                 ira->ira_ill = ill;
5248                 ira->ira_rill = rill;
5249         }
5250 }
5251 
5252 /*
5253  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5254  * (Unicast fanout is handled in ip_input_v4.)
5255  *
5256  * If SO_REUSEADDR is set all multicast and broadcast packets
5257  * will be delivered to all conns bound to the same port.
5258  *
5259  * If there is at least one matching AF_INET receiver, then we will
5260  * ignore any AF_INET6 receivers.
5261  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5262  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5263  * packets.
5264  *
5265  * Zones notes:
5266  * Earlier in ip_input on a system with multiple shared-IP zones we
5267  * duplicate the multicast and broadcast packets and send them up
5268  * with each explicit zoneid that exists on that ill.
5269  * This means that here we can match the zoneid with SO_ALLZONES being special.
5270  */
5271 void
5272 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5273     ip_recv_attr_t *ira)
5274 {
5275         ipaddr_t        laddr;
5276         in6_addr_t      v6faddr;
5277         conn_t          *connp;
5278         connf_t         *connfp;
5279         ipaddr_t        faddr;
5280         ill_t           *ill = ira->ira_ill;
5281         ip_stack_t      *ipst = ill->ill_ipst;
5282 
5283         ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5284 
5285         laddr = ipha->ipha_dst;
5286         faddr = ipha->ipha_src;
5287 
5288         connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5289         mutex_enter(&connfp->connf_lock);
5290         connp = connfp->connf_head;
5291 
5292         /*
5293          * If SO_REUSEADDR has been set on the first we send the
5294          * packet to all clients that have joined the group and
5295          * match the port.
5296          */
5297         while (connp != NULL) {
5298                 if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5299                     conn_wantpacket(connp, ira, ipha) &&
5300                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5301                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5302                         break;
5303                 connp = connp->conn_next;
5304         }
5305 
5306         if (connp == NULL)
5307                 goto notfound;
5308 
5309         CONN_INC_REF(connp);
5310 
5311         if (connp->conn_reuseaddr) {
5312                 conn_t          *first_connp = connp;
5313                 conn_t          *next_connp;
5314                 mblk_t          *mp1;
5315 
5316                 connp = connp->conn_next;
5317                 for (;;) {
5318                         while (connp != NULL) {
5319                                 if (IPCL_UDP_MATCH(connp, lport, laddr,
5320                                     fport, faddr) &&
5321                                     conn_wantpacket(connp, ira, ipha) &&
5322                                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5323                                     tsol_receive_local(mp, &laddr, IPV4_VERSION,
5324                                     ira, connp)))
5325                                         break;
5326                                 connp = connp->conn_next;
5327                         }
5328                         if (connp == NULL) {
5329                                 /* No more interested clients */
5330                                 connp = first_connp;
5331                                 break;
5332                         }
5333                         if (((mp1 = dupmsg(mp)) == NULL) &&
5334                             ((mp1 = copymsg(mp)) == NULL)) {
5335                                 /* Memory allocation failed */
5336                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5337                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
5338                                 connp = first_connp;
5339                                 break;
5340                         }
5341                         CONN_INC_REF(connp);
5342                         mutex_exit(&connfp->connf_lock);
5343 
5344                         IP_STAT(ipst, ip_udp_fanmb);
5345                         ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5346                             NULL, ira);
5347                         mutex_enter(&connfp->connf_lock);
5348                         /* Follow the next pointer before releasing the conn */
5349                         next_connp = connp->conn_next;
5350                         CONN_DEC_REF(connp);
5351                         connp = next_connp;
5352                 }
5353         }
5354 
5355         /* Last one.  Send it upstream. */
5356         mutex_exit(&connfp->connf_lock);
5357         IP_STAT(ipst, ip_udp_fanmb);
5358         ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5359         CONN_DEC_REF(connp);
5360         return;
5361 
5362 notfound:
5363         mutex_exit(&connfp->connf_lock);
5364         /*
5365          * IPv6 endpoints bound to multicast IPv4-mapped addresses
5366          * have already been matched above, since they live in the IPv4
5367          * fanout tables. This implies we only need to
5368          * check for IPv6 in6addr_any endpoints here.
5369          * Thus we compare using ipv6_all_zeros instead of the destination
5370          * address, except for the multicast group membership lookup which
5371          * uses the IPv4 destination.
5372          */
5373         IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5374         connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5375         mutex_enter(&connfp->connf_lock);
5376         connp = connfp->connf_head;
5377         /*
5378          * IPv4 multicast packet being delivered to an AF_INET6
5379          * in6addr_any endpoint.
5380          * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5381          * and not conn_wantpacket_v6() since any multicast membership is
5382          * for an IPv4-mapped multicast address.
5383          */
5384         while (connp != NULL) {
5385                 if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5386                     fport, v6faddr) &&
5387                     conn_wantpacket(connp, ira, ipha) &&
5388                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5389                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5390                         break;
5391                 connp = connp->conn_next;
5392         }
5393 
5394         if (connp == NULL) {
5395                 /*
5396                  * No one bound to this port.  Is
5397                  * there a client that wants all
5398                  * unclaimed datagrams?
5399                  */
5400                 mutex_exit(&connfp->connf_lock);
5401 
5402                 if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5403                     NULL) {
5404                         ASSERT(ira->ira_protocol == IPPROTO_UDP);
5405                         ip_fanout_proto_v4(mp, ipha, ira);
5406                 } else {
5407                         /*
5408                          * We used to attempt to send an icmp error here, but
5409                          * since this is known to be a multicast packet
5410                          * and we don't send icmp errors in response to
5411                          * multicast, just drop the packet and give up sooner.
5412                          */
5413                         BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5414                         freemsg(mp);
5415                 }
5416                 return;
5417         }
5418         CONN_INC_REF(connp);
5419         ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5420 
5421         /*
5422          * If SO_REUSEADDR has been set on the first we send the
5423          * packet to all clients that have joined the group and
5424          * match the port.
5425          */
5426         if (connp->conn_reuseaddr) {
5427                 conn_t          *first_connp = connp;
5428                 conn_t          *next_connp;
5429                 mblk_t          *mp1;
5430 
5431                 connp = connp->conn_next;
5432                 for (;;) {
5433                         while (connp != NULL) {
5434                                 if (IPCL_UDP_MATCH_V6(connp, lport,
5435                                     ipv6_all_zeros, fport, v6faddr) &&
5436                                     conn_wantpacket(connp, ira, ipha) &&
5437                                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5438                                     tsol_receive_local(mp, &laddr, IPV4_VERSION,
5439                                     ira, connp)))
5440                                         break;
5441                                 connp = connp->conn_next;
5442                         }
5443                         if (connp == NULL) {
5444                                 /* No more interested clients */
5445                                 connp = first_connp;
5446                                 break;
5447                         }
5448                         if (((mp1 = dupmsg(mp)) == NULL) &&
5449                             ((mp1 = copymsg(mp)) == NULL)) {
5450                                 /* Memory allocation failed */
5451                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5452                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
5453                                 connp = first_connp;
5454                                 break;
5455                         }
5456                         CONN_INC_REF(connp);
5457                         mutex_exit(&connfp->connf_lock);
5458 
5459                         IP_STAT(ipst, ip_udp_fanmb);
5460                         ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5461                             NULL, ira);
5462                         mutex_enter(&connfp->connf_lock);
5463                         /* Follow the next pointer before releasing the conn */
5464                         next_connp = connp->conn_next;
5465                         CONN_DEC_REF(connp);
5466                         connp = next_connp;
5467                 }
5468         }
5469 
5470         /* Last one.  Send it upstream. */
5471         mutex_exit(&connfp->connf_lock);
5472         IP_STAT(ipst, ip_udp_fanmb);
5473         ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5474         CONN_DEC_REF(connp);
5475 }
5476 
5477 /*
5478  * Split an incoming packet's IPv4 options into the label and the other options.
5479  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5480  * clearing out any leftover label or options.
5481  * Otherwise it just makes ipp point into the packet.
5482  *
5483  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5484  */
5485 int
5486 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5487 {
5488         uchar_t         *opt;
5489         uint32_t        totallen;
5490         uint32_t        optval;
5491         uint32_t        optlen;
5492 
5493         ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5494         ipp->ipp_hoplimit = ipha->ipha_ttl;
5495         ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5496         IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5497 
5498         /*
5499          * Get length (in 4 byte octets) of IP header options.
5500          */
5501         totallen = ipha->ipha_version_and_hdr_length -
5502             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5503 
5504         if (totallen == 0) {
5505                 if (!allocate)
5506                         return (0);
5507 
5508                 /* Clear out anything from a previous packet */
5509                 if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5510                         kmem_free(ipp->ipp_ipv4_options,
5511                             ipp->ipp_ipv4_options_len);
5512                         ipp->ipp_ipv4_options = NULL;
5513                         ipp->ipp_ipv4_options_len = 0;
5514                         ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5515                 }
5516                 if (ipp->ipp_fields & IPPF_LABEL_V4) {
5517                         kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5518                         ipp->ipp_label_v4 = NULL;
5519                         ipp->ipp_label_len_v4 = 0;
5520                         ipp->ipp_fields &= ~IPPF_LABEL_V4;
5521                 }
5522                 return (0);
5523         }
5524 
5525         totallen <<= 2;
5526         opt = (uchar_t *)&ipha[1];
5527         if (!is_system_labeled()) {
5528 
5529         copyall:
5530                 if (!allocate) {
5531                         if (totallen != 0) {
5532                                 ipp->ipp_ipv4_options = opt;
5533                                 ipp->ipp_ipv4_options_len = totallen;
5534                                 ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5535                         }
5536                         return (0);
5537                 }
5538                 /* Just copy all of options */
5539                 if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5540                         if (totallen == ipp->ipp_ipv4_options_len) {
5541                                 bcopy(opt, ipp->ipp_ipv4_options, totallen);
5542                                 return (0);
5543                         }
5544                         kmem_free(ipp->ipp_ipv4_options,
5545                             ipp->ipp_ipv4_options_len);
5546                         ipp->ipp_ipv4_options = NULL;
5547                         ipp->ipp_ipv4_options_len = 0;
5548                         ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5549                 }
5550                 if (totallen == 0)
5551                         return (0);
5552 
5553                 ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5554                 if (ipp->ipp_ipv4_options == NULL)
5555                         return (ENOMEM);
5556                 ipp->ipp_ipv4_options_len = totallen;
5557                 ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5558                 bcopy(opt, ipp->ipp_ipv4_options, totallen);
5559                 return (0);
5560         }
5561 
5562         if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5563                 kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5564                 ipp->ipp_label_v4 = NULL;
5565                 ipp->ipp_label_len_v4 = 0;
5566                 ipp->ipp_fields &= ~IPPF_LABEL_V4;
5567         }
5568 
5569         /*
5570          * Search for CIPSO option.
5571          * We assume CIPSO is first in options if it is present.
5572          * If it isn't, then ipp_opt_ipv4_options will not include the options
5573          * prior to the CIPSO option.
5574          */
5575         while (totallen != 0) {
5576                 switch (optval = opt[IPOPT_OPTVAL]) {
5577                 case IPOPT_EOL:
5578                         return (0);
5579                 case IPOPT_NOP:
5580                         optlen = 1;
5581                         break;
5582                 default:
5583                         if (totallen <= IPOPT_OLEN)
5584                                 return (EINVAL);
5585                         optlen = opt[IPOPT_OLEN];
5586                         if (optlen < 2)
5587                                 return (EINVAL);
5588                 }
5589                 if (optlen > totallen)
5590                         return (EINVAL);
5591 
5592                 switch (optval) {
5593                 case IPOPT_COMSEC:
5594                         if (!allocate) {
5595                                 ipp->ipp_label_v4 = opt;
5596                                 ipp->ipp_label_len_v4 = optlen;
5597                                 ipp->ipp_fields |= IPPF_LABEL_V4;
5598                         } else {
5599                                 ipp->ipp_label_v4 = kmem_alloc(optlen,
5600                                     KM_NOSLEEP);
5601                                 if (ipp->ipp_label_v4 == NULL)
5602                                         return (ENOMEM);
5603                                 ipp->ipp_label_len_v4 = optlen;
5604                                 ipp->ipp_fields |= IPPF_LABEL_V4;
5605                                 bcopy(opt, ipp->ipp_label_v4, optlen);
5606                         }
5607                         totallen -= optlen;
5608                         opt += optlen;
5609 
5610                         /* Skip padding bytes until we get to a multiple of 4 */
5611                         while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5612                                 totallen--;
5613                                 opt++;
5614                         }
5615                         /* Remaining as ipp_ipv4_options */
5616                         goto copyall;
5617                 }
5618                 totallen -= optlen;
5619                 opt += optlen;
5620         }
5621         /* No CIPSO found; return everything as ipp_ipv4_options */
5622         totallen = ipha->ipha_version_and_hdr_length -
5623             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5624         totallen <<= 2;
5625         opt = (uchar_t *)&ipha[1];
5626         goto copyall;
5627 }
5628 
5629 /*
5630  * Efficient versions of lookup for an IRE when we only
5631  * match the address.
5632  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5633  * Does not handle multicast addresses.
5634  */
5635 uint_t
5636 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5637 {
5638         ire_t *ire;
5639         uint_t result;
5640 
5641         ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5642         ASSERT(ire != NULL);
5643         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5644                 result = IRE_NOROUTE;
5645         else
5646                 result = ire->ire_type;
5647         ire_refrele(ire);
5648         return (result);
5649 }
5650 
5651 /*
5652  * Efficient versions of lookup for an IRE when we only
5653  * match the address.
5654  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5655  * Does not handle multicast addresses.
5656  */
5657 uint_t
5658 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5659 {
5660         ire_t *ire;
5661         uint_t result;
5662 
5663         ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5664         ASSERT(ire != NULL);
5665         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5666                 result = IRE_NOROUTE;
5667         else
5668                 result = ire->ire_type;
5669         ire_refrele(ire);
5670         return (result);
5671 }
5672 
5673 /*
5674  * Nobody should be sending
5675  * packets up this stream
5676  */
5677 static void
5678 ip_lrput(queue_t *q, mblk_t *mp)
5679 {
5680         switch (mp->b_datap->db_type) {
5681         case M_FLUSH:
5682                 /* Turn around */
5683                 if (*mp->b_rptr & FLUSHW) {
5684                         *mp->b_rptr &= ~FLUSHR;
5685                         qreply(q, mp);
5686                         return;
5687                 }
5688                 break;
5689         }
5690         freemsg(mp);
5691 }
5692 
5693 /* Nobody should be sending packets down this stream */
5694 /* ARGSUSED */
5695 void
5696 ip_lwput(queue_t *q, mblk_t *mp)
5697 {
5698         freemsg(mp);
5699 }
5700 
5701 /*
5702  * Move the first hop in any source route to ipha_dst and remove that part of
5703  * the source route.  Called by other protocols.  Errors in option formatting
5704  * are ignored - will be handled by ip_output_options. Return the final
5705  * destination (either ipha_dst or the last entry in a source route.)
5706  */
5707 ipaddr_t
5708 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5709 {
5710         ipoptp_t        opts;
5711         uchar_t         *opt;
5712         uint8_t         optval;
5713         uint8_t         optlen;
5714         ipaddr_t        dst;
5715         int             i;
5716         ip_stack_t      *ipst = ns->netstack_ip;
5717 
5718         ip2dbg(("ip_massage_options\n"));
5719         dst = ipha->ipha_dst;
5720         for (optval = ipoptp_first(&opts, ipha);
5721             optval != IPOPT_EOL;
5722             optval = ipoptp_next(&opts)) {
5723                 opt = opts.ipoptp_cur;
5724                 switch (optval) {
5725                         uint8_t off;
5726                 case IPOPT_SSRR:
5727                 case IPOPT_LSRR:
5728                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5729                                 ip1dbg(("ip_massage_options: bad src route\n"));
5730                                 break;
5731                         }
5732                         optlen = opts.ipoptp_len;
5733                         off = opt[IPOPT_OFFSET];
5734                         off--;
5735                 redo_srr:
5736                         if (optlen < IP_ADDR_LEN ||
5737                             off > optlen - IP_ADDR_LEN) {
5738                                 /* End of source route */
5739                                 ip1dbg(("ip_massage_options: end of SR\n"));
5740                                 break;
5741                         }
5742                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5743                         ip1dbg(("ip_massage_options: next hop 0x%x\n",
5744                             ntohl(dst)));
5745                         /*
5746                          * Check if our address is present more than
5747                          * once as consecutive hops in source route.
5748                          * XXX verify per-interface ip_forwarding
5749                          * for source route?
5750                          */
5751                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5752                                 off += IP_ADDR_LEN;
5753                                 goto redo_srr;
5754                         }
5755                         if (dst == htonl(INADDR_LOOPBACK)) {
5756                                 ip1dbg(("ip_massage_options: loopback addr in "
5757                                     "source route!\n"));
5758                                 break;
5759                         }
5760                         /*
5761                          * Update ipha_dst to be the first hop and remove the
5762                          * first hop from the source route (by overwriting
5763                          * part of the option with NOP options).
5764                          */
5765                         ipha->ipha_dst = dst;
5766                         /* Put the last entry in dst */
5767                         off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5768                             3;
5769                         bcopy(&opt[off], &dst, IP_ADDR_LEN);
5770 
5771                         ip1dbg(("ip_massage_options: last hop 0x%x\n",
5772                             ntohl(dst)));
5773                         /* Move down and overwrite */
5774                         opt[IP_ADDR_LEN] = opt[0];
5775                         opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5776                         opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5777                         for (i = 0; i < IP_ADDR_LEN; i++)
5778                                 opt[i] = IPOPT_NOP;
5779                         break;
5780                 }
5781         }
5782         return (dst);
5783 }
5784 
5785 /*
5786  * Return the network mask
5787  * associated with the specified address.
5788  */
5789 ipaddr_t
5790 ip_net_mask(ipaddr_t addr)
5791 {
5792         uchar_t *up = (uchar_t *)&addr;
5793         ipaddr_t mask = 0;
5794         uchar_t *maskp = (uchar_t *)&mask;
5795 
5796 #if defined(__i386) || defined(__amd64)
5797 #define TOTALLY_BRAIN_DAMAGED_C_COMPILER
5798 #endif
5799 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5800         maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5801 #endif
5802         if (CLASSD(addr)) {
5803                 maskp[0] = 0xF0;
5804                 return (mask);
5805         }
5806 
5807         /* We assume Class E default netmask to be 32 */
5808         if (CLASSE(addr))
5809                 return (0xffffffffU);
5810 
5811         if (addr == 0)
5812                 return (0);
5813         maskp[0] = 0xFF;
5814         if ((up[0] & 0x80) == 0)
5815                 return (mask);
5816 
5817         maskp[1] = 0xFF;
5818         if ((up[0] & 0xC0) == 0x80)
5819                 return (mask);
5820 
5821         maskp[2] = 0xFF;
5822         if ((up[0] & 0xE0) == 0xC0)
5823                 return (mask);
5824 
5825         /* Otherwise return no mask */
5826         return ((ipaddr_t)0);
5827 }
5828 
5829 /* Name/Value Table Lookup Routine */
5830 char *
5831 ip_nv_lookup(nv_t *nv, int value)
5832 {
5833         if (!nv)
5834                 return (NULL);
5835         for (; nv->nv_name; nv++) {
5836                 if (nv->nv_value == value)
5837                         return (nv->nv_name);
5838         }
5839         return ("unknown");
5840 }
5841 
5842 static int
5843 ip_wait_for_info_ack(ill_t *ill)
5844 {
5845         int err;
5846 
5847         mutex_enter(&ill->ill_lock);
5848         while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5849                 /*
5850                  * Return value of 0 indicates a pending signal.
5851                  */
5852                 err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5853                 if (err == 0) {
5854                         mutex_exit(&ill->ill_lock);
5855                         return (EINTR);
5856                 }
5857         }
5858         mutex_exit(&ill->ill_lock);
5859         /*
5860          * ip_rput_other could have set an error  in ill_error on
5861          * receipt of M_ERROR.
5862          */
5863         return (ill->ill_error);
5864 }
5865 
5866 /*
5867  * This is a module open, i.e. this is a control stream for access
5868  * to a DLPI device.  We allocate an ill_t as the instance data in
5869  * this case.
5870  */
5871 static int
5872 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5873 {
5874         ill_t   *ill;
5875         int     err;
5876         zoneid_t zoneid;
5877         netstack_t *ns;
5878         ip_stack_t *ipst;
5879 
5880         /*
5881          * Prevent unprivileged processes from pushing IP so that
5882          * they can't send raw IP.
5883          */
5884         if (secpolicy_net_rawaccess(credp) != 0)
5885                 return (EPERM);
5886 
5887         ns = netstack_find_by_cred(credp);
5888         ASSERT(ns != NULL);
5889         ipst = ns->netstack_ip;
5890         ASSERT(ipst != NULL);
5891 
5892         /*
5893          * For exclusive stacks we set the zoneid to zero
5894          * to make IP operate as if in the global zone.
5895          */
5896         if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5897                 zoneid = GLOBAL_ZONEID;
5898         else
5899                 zoneid = crgetzoneid(credp);
5900 
5901         ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5902         q->q_ptr = WR(q)->q_ptr = ill;
5903         ill->ill_ipst = ipst;
5904         ill->ill_zoneid = zoneid;
5905 
5906         /*
5907          * ill_init initializes the ill fields and then sends down
5908          * down a DL_INFO_REQ after calling qprocson.
5909          */
5910         err = ill_init(q, ill);
5911 
5912         if (err != 0) {
5913                 mi_free(ill);
5914                 netstack_rele(ipst->ips_netstack);
5915                 q->q_ptr = NULL;
5916                 WR(q)->q_ptr = NULL;
5917                 return (err);
5918         }
5919 
5920         /*
5921          * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5922          *
5923          * ill_init initializes the ipsq marking this thread as
5924          * writer
5925          */
5926         ipsq_exit(ill->ill_phyint->phyint_ipsq);
5927         err = ip_wait_for_info_ack(ill);
5928         if (err == 0)
5929                 ill->ill_credp = credp;
5930         else
5931                 goto fail;
5932 
5933         crhold(credp);
5934 
5935         mutex_enter(&ipst->ips_ip_mi_lock);
5936         err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5937             sflag, credp);
5938         mutex_exit(&ipst->ips_ip_mi_lock);
5939 fail:
5940         if (err) {
5941                 (void) ip_close(q, 0);
5942                 return (err);
5943         }
5944         return (0);
5945 }
5946 
5947 /* For /dev/ip aka AF_INET open */
5948 int
5949 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5950 {
5951         return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5952 }
5953 
5954 /* For /dev/ip6 aka AF_INET6 open */
5955 int
5956 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5957 {
5958         return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5959 }
5960 
5961 /* IP open routine. */
5962 int
5963 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5964     boolean_t isv6)
5965 {
5966         conn_t          *connp;
5967         major_t         maj;
5968         zoneid_t        zoneid;
5969         netstack_t      *ns;
5970         ip_stack_t      *ipst;
5971 
5972         /* Allow reopen. */
5973         if (q->q_ptr != NULL)
5974                 return (0);
5975 
5976         if (sflag & MODOPEN) {
5977                 /* This is a module open */
5978                 return (ip_modopen(q, devp, flag, sflag, credp));
5979         }
5980 
5981         if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5982                 /*
5983                  * Non streams based socket looking for a stream
5984                  * to access IP
5985                  */
5986                 return (ip_helper_stream_setup(q, devp, flag, sflag,
5987                     credp, isv6));
5988         }
5989 
5990         ns = netstack_find_by_cred(credp);
5991         ASSERT(ns != NULL);
5992         ipst = ns->netstack_ip;
5993         ASSERT(ipst != NULL);
5994 
5995         /*
5996          * For exclusive stacks we set the zoneid to zero
5997          * to make IP operate as if in the global zone.
5998          */
5999         if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6000                 zoneid = GLOBAL_ZONEID;
6001         else
6002                 zoneid = crgetzoneid(credp);
6003 
6004         /*
6005          * We are opening as a device. This is an IP client stream, and we
6006          * allocate an conn_t as the instance data.
6007          */
6008         connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6009 
6010         /*
6011          * ipcl_conn_create did a netstack_hold. Undo the hold that was
6012          * done by netstack_find_by_cred()
6013          */
6014         netstack_rele(ipst->ips_netstack);
6015 
6016         connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6017         /* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6018         connp->conn_ixa->ixa_zoneid = zoneid;
6019         connp->conn_zoneid = zoneid;
6020 
6021         connp->conn_rq = q;
6022         q->q_ptr = WR(q)->q_ptr = connp;
6023 
6024         /* Minor tells us which /dev entry was opened */
6025         if (isv6) {
6026                 connp->conn_family = AF_INET6;
6027                 connp->conn_ipversion = IPV6_VERSION;
6028                 connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6029                 connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6030         } else {
6031                 connp->conn_family = AF_INET;
6032                 connp->conn_ipversion = IPV4_VERSION;
6033                 connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6034         }
6035 
6036         if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6037             ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6038                 connp->conn_minor_arena = ip_minor_arena_la;
6039         } else {
6040                 /*
6041                  * Either minor numbers in the large arena were exhausted
6042                  * or a non socket application is doing the open.
6043                  * Try to allocate from the small arena.
6044                  */
6045                 if ((connp->conn_dev =
6046                     inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6047                         /* CONN_DEC_REF takes care of netstack_rele() */
6048                         q->q_ptr = WR(q)->q_ptr = NULL;
6049                         CONN_DEC_REF(connp);
6050                         return (EBUSY);
6051                 }
6052                 connp->conn_minor_arena = ip_minor_arena_sa;
6053         }
6054 
6055         maj = getemajor(*devp);
6056         *devp = makedevice(maj, (minor_t)connp->conn_dev);
6057 
6058         /*
6059          * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6060          */
6061         connp->conn_cred = credp;
6062         connp->conn_cpid = curproc->p_pid;
6063         /* Cache things in ixa without an extra refhold */
6064         ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6065         connp->conn_ixa->ixa_cred = connp->conn_cred;
6066         connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6067         if (is_system_labeled())
6068                 connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6069 
6070         /*
6071          * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6072          */
6073         connp->conn_recv = ip_conn_input;
6074         connp->conn_recvicmp = ip_conn_input_icmp;
6075 
6076         crhold(connp->conn_cred);
6077 
6078         /*
6079          * If the caller has the process-wide flag set, then default to MAC
6080          * exempt mode.  This allows read-down to unlabeled hosts.
6081          */
6082         if (getpflags(NET_MAC_AWARE, credp) != 0)
6083                 connp->conn_mac_mode = CONN_MAC_AWARE;
6084 
6085         connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6086 
6087         connp->conn_rq = q;
6088         connp->conn_wq = WR(q);
6089 
6090         /* Non-zero default values */
6091         connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6092 
6093         /*
6094          * Make the conn globally visible to walkers
6095          */
6096         ASSERT(connp->conn_ref == 1);
6097         mutex_enter(&connp->conn_lock);
6098         connp->conn_state_flags &= ~CONN_INCIPIENT;
6099         mutex_exit(&connp->conn_lock);
6100 
6101         qprocson(q);
6102 
6103         return (0);
6104 }
6105 
6106 /*
6107  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6108  * all of them are copied to the conn_t. If the req is "zero", the policy is
6109  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6110  * fields.
6111  * We keep only the latest setting of the policy and thus policy setting
6112  * is not incremental/cumulative.
6113  *
6114  * Requests to set policies with multiple alternative actions will
6115  * go through a different API.
6116  */
6117 int
6118 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6119 {
6120         uint_t ah_req = 0;
6121         uint_t esp_req = 0;
6122         uint_t se_req = 0;
6123         ipsec_act_t *actp = NULL;
6124         uint_t nact;
6125         ipsec_policy_head_t *ph;
6126         boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6127         int error = 0;
6128         netstack_t      *ns = connp->conn_netstack;
6129         ip_stack_t      *ipst = ns->netstack_ip;
6130         ipsec_stack_t   *ipss = ns->netstack_ipsec;
6131 
6132 #define REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6133 
6134         /*
6135          * The IP_SEC_OPT option does not allow variable length parameters,
6136          * hence a request cannot be NULL.
6137          */
6138         if (req == NULL)
6139                 return (EINVAL);
6140 
6141         ah_req = req->ipsr_ah_req;
6142         esp_req = req->ipsr_esp_req;
6143         se_req = req->ipsr_self_encap_req;
6144 
6145         /* Don't allow setting self-encap without one or more of AH/ESP. */
6146         if (se_req != 0 && esp_req == 0 && ah_req == 0)
6147                 return (EINVAL);
6148 
6149         /*
6150          * Are we dealing with a request to reset the policy (i.e.
6151          * zero requests).
6152          */
6153         is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6154             (esp_req & REQ_MASK) == 0 &&
6155             (se_req & REQ_MASK) == 0);
6156 
6157         if (!is_pol_reset) {
6158                 /*
6159                  * If we couldn't load IPsec, fail with "protocol
6160                  * not supported".
6161                  * IPsec may not have been loaded for a request with zero
6162                  * policies, so we don't fail in this case.
6163                  */
6164                 mutex_enter(&ipss->ipsec_loader_lock);
6165                 if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6166                         mutex_exit(&ipss->ipsec_loader_lock);
6167                         return (EPROTONOSUPPORT);
6168                 }
6169                 mutex_exit(&ipss->ipsec_loader_lock);
6170 
6171                 /*
6172                  * Test for valid requests. Invalid algorithms
6173                  * need to be tested by IPsec code because new
6174                  * algorithms can be added dynamically.
6175                  */
6176                 if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6177                     (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6178                     (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6179                         return (EINVAL);
6180                 }
6181 
6182                 /*
6183                  * Only privileged users can issue these
6184                  * requests.
6185                  */
6186                 if (((ah_req & IPSEC_PREF_NEVER) ||
6187                     (esp_req & IPSEC_PREF_NEVER) ||
6188                     (se_req & IPSEC_PREF_NEVER)) &&
6189                     secpolicy_ip_config(cr, B_FALSE) != 0) {
6190                         return (EPERM);
6191                 }
6192 
6193                 /*
6194                  * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6195                  * are mutually exclusive.
6196                  */
6197                 if (((ah_req & REQ_MASK) == REQ_MASK) ||
6198                     ((esp_req & REQ_MASK) == REQ_MASK) ||
6199                     ((se_req & REQ_MASK) == REQ_MASK)) {
6200                         /* Both of them are set */
6201                         return (EINVAL);
6202                 }
6203         }
6204 
6205         ASSERT(MUTEX_HELD(&connp->conn_lock));
6206 
6207         /*
6208          * If we have already cached policies in conn_connect(), don't
6209          * let them change now. We cache policies for connections
6210          * whose src,dst [addr, port] is known.
6211          */
6212         if (connp->conn_policy_cached) {
6213                 return (EINVAL);
6214         }
6215 
6216         /*
6217          * We have a zero policies, reset the connection policy if already
6218          * set. This will cause the connection to inherit the
6219          * global policy, if any.
6220          */
6221         if (is_pol_reset) {
6222                 if (connp->conn_policy != NULL) {
6223                         IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6224                         connp->conn_policy = NULL;
6225                 }
6226                 connp->conn_in_enforce_policy = B_FALSE;
6227                 connp->conn_out_enforce_policy = B_FALSE;
6228                 return (0);
6229         }
6230 
6231         ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6232             ipst->ips_netstack);
6233         if (ph == NULL)
6234                 goto enomem;
6235 
6236         ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6237         if (actp == NULL)
6238                 goto enomem;
6239 
6240         /*
6241          * Always insert IPv4 policy entries, since they can also apply to
6242          * ipv6 sockets being used in ipv4-compat mode.
6243          */
6244         if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6245             IPSEC_TYPE_INBOUND, ns))
6246                 goto enomem;
6247         is_pol_inserted = B_TRUE;
6248         if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6249             IPSEC_TYPE_OUTBOUND, ns))
6250                 goto enomem;
6251 
6252         /*
6253          * We're looking at a v6 socket, also insert the v6-specific
6254          * entries.
6255          */
6256         if (connp->conn_family == AF_INET6) {
6257                 if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6258                     IPSEC_TYPE_INBOUND, ns))
6259                         goto enomem;
6260                 if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6261                     IPSEC_TYPE_OUTBOUND, ns))
6262                         goto enomem;
6263         }
6264 
6265         ipsec_actvec_free(actp, nact);
6266 
6267         /*
6268          * If the requests need security, set enforce_policy.
6269          * If the requests are IPSEC_PREF_NEVER, one should
6270          * still set conn_out_enforce_policy so that ip_set_destination
6271          * marks the ip_xmit_attr_t appropriatly. This is needed so that
6272          * for connections that we don't cache policy in at connect time,
6273          * if global policy matches in ip_output_attach_policy, we
6274          * don't wrongly inherit global policy. Similarly, we need
6275          * to set conn_in_enforce_policy also so that we don't verify
6276          * policy wrongly.
6277          */
6278         if ((ah_req & REQ_MASK) != 0 ||
6279             (esp_req & REQ_MASK) != 0 ||
6280             (se_req & REQ_MASK) != 0) {
6281                 connp->conn_in_enforce_policy = B_TRUE;
6282                 connp->conn_out_enforce_policy = B_TRUE;
6283         }
6284 
6285         return (error);
6286 #undef REQ_MASK
6287 
6288         /*
6289          * Common memory-allocation-failure exit path.
6290          */
6291 enomem:
6292         if (actp != NULL)
6293                 ipsec_actvec_free(actp, nact);
6294         if (is_pol_inserted)
6295                 ipsec_polhead_flush(ph, ns);
6296         return (ENOMEM);
6297 }
6298 
6299 /*
6300  * Set socket options for joining and leaving multicast groups.
6301  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6302  * The caller has already check that the option name is consistent with
6303  * the address family of the socket.
6304  */
6305 int
6306 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6307     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6308 {
6309         int             *i1 = (int *)invalp;
6310         int             error = 0;
6311         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
6312         struct ip_mreq  *v4_mreqp;
6313         struct ipv6_mreq *v6_mreqp;
6314         struct group_req *greqp;
6315         ire_t *ire;
6316         boolean_t done = B_FALSE;
6317         ipaddr_t ifaddr;
6318         in6_addr_t v6group;
6319         uint_t ifindex;
6320         boolean_t mcast_opt = B_TRUE;
6321         mcast_record_t fmode;
6322         int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6323             ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6324 
6325         switch (name) {
6326         case IP_ADD_MEMBERSHIP:
6327         case IPV6_JOIN_GROUP:
6328                 mcast_opt = B_FALSE;
6329                 /* FALLTHRU */
6330         case MCAST_JOIN_GROUP:
6331                 fmode = MODE_IS_EXCLUDE;
6332                 optfn = ip_opt_add_group;
6333                 break;
6334 
6335         case IP_DROP_MEMBERSHIP:
6336         case IPV6_LEAVE_GROUP:
6337                 mcast_opt = B_FALSE;
6338                 /* FALLTHRU */
6339         case MCAST_LEAVE_GROUP:
6340                 fmode = MODE_IS_INCLUDE;
6341                 optfn = ip_opt_delete_group;
6342                 break;
6343         default:
6344                 ASSERT(0);
6345         }
6346 
6347         if (mcast_opt) {
6348                 struct sockaddr_in *sin;
6349                 struct sockaddr_in6 *sin6;
6350 
6351                 greqp = (struct group_req *)i1;
6352                 if (greqp->gr_group.ss_family == AF_INET) {
6353                         sin = (struct sockaddr_in *)&(greqp->gr_group);
6354                         IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6355                 } else {
6356                         if (!inet6)
6357                                 return (EINVAL);        /* Not on INET socket */
6358 
6359                         sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6360                         v6group = sin6->sin6_addr;
6361                 }
6362                 ifaddr = INADDR_ANY;
6363                 ifindex = greqp->gr_interface;
6364         } else if (inet6) {
6365                 v6_mreqp = (struct ipv6_mreq *)i1;
6366                 v6group = v6_mreqp->ipv6mr_multiaddr;
6367                 ifaddr = INADDR_ANY;
6368                 ifindex = v6_mreqp->ipv6mr_interface;
6369         } else {
6370                 v4_mreqp = (struct ip_mreq *)i1;
6371                 IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6372                 ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6373                 ifindex = 0;
6374         }
6375 
6376         /*
6377          * In the multirouting case, we need to replicate
6378          * the request on all interfaces that will take part
6379          * in replication.  We do so because multirouting is
6380          * reflective, thus we will probably receive multi-
6381          * casts on those interfaces.
6382          * The ip_multirt_apply_membership() succeeds if
6383          * the operation succeeds on at least one interface.
6384          */
6385         if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6386                 ipaddr_t group;
6387 
6388                 IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6389 
6390                 ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6391                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6392                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6393         } else {
6394                 ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6395                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6396                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6397         }
6398         if (ire != NULL) {
6399                 if (ire->ire_flags & RTF_MULTIRT) {
6400                         error = ip_multirt_apply_membership(optfn, ire, connp,
6401                             checkonly, &v6group, fmode, &ipv6_all_zeros);
6402                         done = B_TRUE;
6403                 }
6404                 ire_refrele(ire);
6405         }
6406 
6407         if (!done) {
6408                 error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6409                     fmode, &ipv6_all_zeros);
6410         }
6411         return (error);
6412 }
6413 
6414 /*
6415  * Set socket options for joining and leaving multicast groups
6416  * for specific sources.
6417  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6418  * The caller has already check that the option name is consistent with
6419  * the address family of the socket.
6420  */
6421 int
6422 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6423     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6424 {
6425         int             *i1 = (int *)invalp;
6426         int             error = 0;
6427         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
6428         struct ip_mreq_source *imreqp;
6429         struct group_source_req *gsreqp;
6430         in6_addr_t v6group, v6src;
6431         uint32_t ifindex;
6432         ipaddr_t ifaddr;
6433         boolean_t mcast_opt = B_TRUE;
6434         mcast_record_t fmode;
6435         ire_t *ire;
6436         boolean_t done = B_FALSE;
6437         int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6438             ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6439 
6440         switch (name) {
6441         case IP_BLOCK_SOURCE:
6442                 mcast_opt = B_FALSE;
6443                 /* FALLTHRU */
6444         case MCAST_BLOCK_SOURCE:
6445                 fmode = MODE_IS_EXCLUDE;
6446                 optfn = ip_opt_add_group;
6447                 break;
6448 
6449         case IP_UNBLOCK_SOURCE:
6450                 mcast_opt = B_FALSE;
6451                 /* FALLTHRU */
6452         case MCAST_UNBLOCK_SOURCE:
6453                 fmode = MODE_IS_EXCLUDE;
6454                 optfn = ip_opt_delete_group;
6455                 break;
6456 
6457         case IP_ADD_SOURCE_MEMBERSHIP:
6458                 mcast_opt = B_FALSE;
6459                 /* FALLTHRU */
6460         case MCAST_JOIN_SOURCE_GROUP:
6461                 fmode = MODE_IS_INCLUDE;
6462                 optfn = ip_opt_add_group;
6463                 break;
6464 
6465         case IP_DROP_SOURCE_MEMBERSHIP:
6466                 mcast_opt = B_FALSE;
6467                 /* FALLTHRU */
6468         case MCAST_LEAVE_SOURCE_GROUP:
6469                 fmode = MODE_IS_INCLUDE;
6470                 optfn = ip_opt_delete_group;
6471                 break;
6472         default:
6473                 ASSERT(0);
6474         }
6475 
6476         if (mcast_opt) {
6477                 gsreqp = (struct group_source_req *)i1;
6478                 ifindex = gsreqp->gsr_interface;
6479                 if (gsreqp->gsr_group.ss_family == AF_INET) {
6480                         struct sockaddr_in *s;
6481                         s = (struct sockaddr_in *)&gsreqp->gsr_group;
6482                         IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6483                         s = (struct sockaddr_in *)&gsreqp->gsr_source;
6484                         IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6485                 } else {
6486                         struct sockaddr_in6 *s6;
6487 
6488                         if (!inet6)
6489                                 return (EINVAL);        /* Not on INET socket */
6490 
6491                         s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6492                         v6group = s6->sin6_addr;
6493                         s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6494                         v6src = s6->sin6_addr;
6495                 }
6496                 ifaddr = INADDR_ANY;
6497         } else {
6498                 imreqp = (struct ip_mreq_source *)i1;
6499                 IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6500                 IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6501                 ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6502                 ifindex = 0;
6503         }
6504 
6505         /*
6506          * Handle src being mapped INADDR_ANY by changing it to unspecified.
6507          */
6508         if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6509                 v6src = ipv6_all_zeros;
6510 
6511         /*
6512          * In the multirouting case, we need to replicate
6513          * the request as noted in the mcast cases above.
6514          */
6515         if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6516                 ipaddr_t group;
6517 
6518                 IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6519 
6520                 ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6521                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6522                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6523         } else {
6524                 ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6525                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6526                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6527         }
6528         if (ire != NULL) {
6529                 if (ire->ire_flags & RTF_MULTIRT) {
6530                         error = ip_multirt_apply_membership(optfn, ire, connp,
6531                             checkonly, &v6group, fmode, &v6src);
6532                         done = B_TRUE;
6533                 }
6534                 ire_refrele(ire);
6535         }
6536         if (!done) {
6537                 error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6538                     fmode, &v6src);
6539         }
6540         return (error);
6541 }
6542 
6543 /*
6544  * Given a destination address and a pointer to where to put the information
6545  * this routine fills in the mtuinfo.
6546  * The socket must be connected.
6547  * For sctp conn_faddr is the primary address.
6548  */
6549 int
6550 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6551 {
6552         uint32_t        pmtu = IP_MAXPACKET;
6553         uint_t          scopeid;
6554 
6555         if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6556                 return (-1);
6557 
6558         /* In case we never sent or called ip_set_destination_v4/v6 */
6559         if (ixa->ixa_ire != NULL)
6560                 pmtu = ip_get_pmtu(ixa);
6561 
6562         if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6563                 scopeid = ixa->ixa_scopeid;
6564         else
6565                 scopeid = 0;
6566 
6567         bzero(mtuinfo, sizeof (*mtuinfo));
6568         mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6569         mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6570         mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6571         mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6572         mtuinfo->ip6m_mtu = pmtu;
6573 
6574         return (sizeof (struct ip6_mtuinfo));
6575 }
6576 
6577 /*
6578  * When the src multihoming is changed from weak to [strong, preferred]
6579  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6580  * and identify routes that were created by user-applications in the
6581  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6582  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6583  * is selected by finding an interface route for the gateway.
6584  */
6585 /* ARGSUSED */
6586 void
6587 ip_ire_rebind_walker(ire_t *ire, void *notused)
6588 {
6589         if (!ire->ire_unbound || ire->ire_ill != NULL)
6590                 return;
6591         ire_rebind(ire);
6592         ire_delete(ire);
6593 }
6594 
6595 /*
6596  * When the src multihoming is changed from  [strong, preferred] to weak,
6597  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6598  * set any entries that were created by user-applications in the unbound state
6599  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6600  */
6601 /* ARGSUSED */
6602 void
6603 ip_ire_unbind_walker(ire_t *ire, void *notused)
6604 {
6605         ire_t *new_ire;
6606 
6607         if (!ire->ire_unbound || ire->ire_ill == NULL)
6608                 return;
6609         if (ire->ire_ipversion == IPV6_VERSION) {
6610                 new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6611                     &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6612                     ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6613         } else {
6614                 new_ire = ire_create((uchar_t *)&ire->ire_addr,
6615                     (uchar_t *)&ire->ire_mask,
6616                     (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6617                     ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6618         }
6619         if (new_ire == NULL)
6620                 return;
6621         new_ire->ire_unbound = B_TRUE;
6622         /*
6623          * The bound ire must first be deleted so that we don't return
6624          * the existing one on the attempt to add the unbound new_ire.
6625          */
6626         ire_delete(ire);
6627         new_ire = ire_add(new_ire);
6628         if (new_ire != NULL)
6629                 ire_refrele(new_ire);
6630 }
6631 
6632 /*
6633  * When the settings of ip*_strict_src_multihoming tunables are changed,
6634  * all cached routes need to be recomputed. This recomputation needs to be
6635  * done when going from weaker to stronger modes so that the cached ire
6636  * for the connection does not violate the current ip*_strict_src_multihoming
6637  * setting. It also needs to be done when going from stronger to weaker modes,
6638  * so that we fall back to matching on the longest-matching-route (as opposed
6639  * to a shorter match that may have been selected in the strong mode
6640  * to satisfy src_multihoming settings).
6641  *
6642  * The cached ixa_ire entires for all conn_t entries are marked as
6643  * "verify" so that they will be recomputed for the next packet.
6644  */
6645 void
6646 conn_ire_revalidate(conn_t *connp, void *arg)
6647 {
6648         boolean_t isv6 = (boolean_t)arg;
6649 
6650         if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6651             (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6652                 return;
6653         connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6654 }
6655 
6656 /*
6657  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6658  * When an ipf is passed here for the first time, if
6659  * we already have in-order fragments on the queue, we convert from the fast-
6660  * path reassembly scheme to the hard-case scheme.  From then on, additional
6661  * fragments are reassembled here.  We keep track of the start and end offsets
6662  * of each piece, and the number of holes in the chain.  When the hole count
6663  * goes to zero, we are done!
6664  *
6665  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6666  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6667  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6668  * after the call to ip_reassemble().
6669  */
6670 int
6671 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6672     size_t msg_len)
6673 {
6674         uint_t  end;
6675         mblk_t  *next_mp;
6676         mblk_t  *mp1;
6677         uint_t  offset;
6678         boolean_t incr_dups = B_TRUE;
6679         boolean_t offset_zero_seen = B_FALSE;
6680         boolean_t pkt_boundary_checked = B_FALSE;
6681 
6682         /* If start == 0 then ipf_nf_hdr_len has to be set. */
6683         ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6684 
6685         /* Add in byte count */
6686         ipf->ipf_count += msg_len;
6687         if (ipf->ipf_end) {
6688                 /*
6689                  * We were part way through in-order reassembly, but now there
6690                  * is a hole.  We walk through messages already queued, and
6691                  * mark them for hard case reassembly.  We know that up till
6692                  * now they were in order starting from offset zero.
6693                  */
6694                 offset = 0;
6695                 for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6696                         IP_REASS_SET_START(mp1, offset);
6697                         if (offset == 0) {
6698                                 ASSERT(ipf->ipf_nf_hdr_len != 0);
6699                                 offset = -ipf->ipf_nf_hdr_len;
6700                         }
6701                         offset += mp1->b_wptr - mp1->b_rptr;
6702                         IP_REASS_SET_END(mp1, offset);
6703                 }
6704                 /* One hole at the end. */
6705                 ipf->ipf_hole_cnt = 1;
6706                 /* Brand it as a hard case, forever. */
6707                 ipf->ipf_end = 0;
6708         }
6709         /* Walk through all the new pieces. */
6710         do {
6711                 end = start + (mp->b_wptr - mp->b_rptr);
6712                 /*
6713                  * If start is 0, decrease 'end' only for the first mblk of
6714                  * the fragment. Otherwise 'end' can get wrong value in the
6715                  * second pass of the loop if first mblk is exactly the
6716                  * size of ipf_nf_hdr_len.
6717                  */
6718                 if (start == 0 && !offset_zero_seen) {
6719                         /* First segment */
6720                         ASSERT(ipf->ipf_nf_hdr_len != 0);
6721                         end -= ipf->ipf_nf_hdr_len;
6722                         offset_zero_seen = B_TRUE;
6723                 }
6724                 next_mp = mp->b_cont;
6725                 /*
6726                  * We are checking to see if there is any interesing data
6727                  * to process.  If there isn't and the mblk isn't the
6728                  * one which carries the unfragmentable header then we
6729                  * drop it.  It's possible to have just the unfragmentable
6730                  * header come through without any data.  That needs to be
6731                  * saved.
6732                  *
6733                  * If the assert at the top of this function holds then the
6734                  * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6735                  * is infrequently traveled enough that the test is left in
6736                  * to protect against future code changes which break that
6737                  * invariant.
6738                  */
6739                 if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6740                         /* Empty.  Blast it. */
6741                         IP_REASS_SET_START(mp, 0);
6742                         IP_REASS_SET_END(mp, 0);
6743                         /*
6744                          * If the ipf points to the mblk we are about to free,
6745                          * update ipf to point to the next mblk (or NULL
6746                          * if none).
6747                          */
6748                         if (ipf->ipf_mp->b_cont == mp)
6749                                 ipf->ipf_mp->b_cont = next_mp;
6750                         freeb(mp);
6751                         continue;
6752                 }
6753                 mp->b_cont = NULL;
6754                 IP_REASS_SET_START(mp, start);
6755                 IP_REASS_SET_END(mp, end);
6756                 if (!ipf->ipf_tail_mp) {
6757                         ipf->ipf_tail_mp = mp;
6758                         ipf->ipf_mp->b_cont = mp;
6759                         if (start == 0 || !more) {
6760                                 ipf->ipf_hole_cnt = 1;
6761                                 /*
6762                                  * if the first fragment comes in more than one
6763                                  * mblk, this loop will be executed for each
6764                                  * mblk. Need to adjust hole count so exiting
6765                                  * this routine will leave hole count at 1.
6766                                  */
6767                                 if (next_mp)
6768                                         ipf->ipf_hole_cnt++;
6769                         } else
6770                                 ipf->ipf_hole_cnt = 2;
6771                         continue;
6772                 } else if (ipf->ipf_last_frag_seen && !more &&
6773                     !pkt_boundary_checked) {
6774                         /*
6775                          * We check datagram boundary only if this fragment
6776                          * claims to be the last fragment and we have seen a
6777                          * last fragment in the past too. We do this only
6778                          * once for a given fragment.
6779                          *
6780                          * start cannot be 0 here as fragments with start=0
6781                          * and MF=0 gets handled as a complete packet. These
6782                          * fragments should not reach here.
6783                          */
6784 
6785                         if (start + msgdsize(mp) !=
6786                             IP_REASS_END(ipf->ipf_tail_mp)) {
6787                                 /*
6788                                  * We have two fragments both of which claim
6789                                  * to be the last fragment but gives conflicting
6790                                  * information about the whole datagram size.
6791                                  * Something fishy is going on. Drop the
6792                                  * fragment and free up the reassembly list.
6793                                  */
6794                                 return (IP_REASS_FAILED);
6795                         }
6796 
6797                         /*
6798                          * We shouldn't come to this code block again for this
6799                          * particular fragment.
6800                          */
6801                         pkt_boundary_checked = B_TRUE;
6802                 }
6803 
6804                 /* New stuff at or beyond tail? */
6805                 offset = IP_REASS_END(ipf->ipf_tail_mp);
6806                 if (start >= offset) {
6807                         if (ipf->ipf_last_frag_seen) {
6808                                 /* current fragment is beyond last fragment */
6809                                 return (IP_REASS_FAILED);
6810                         }
6811                         /* Link it on end. */
6812                         ipf->ipf_tail_mp->b_cont = mp;
6813                         ipf->ipf_tail_mp = mp;
6814                         if (more) {
6815                                 if (start != offset)
6816                                         ipf->ipf_hole_cnt++;
6817                         } else if (start == offset && next_mp == NULL)
6818                                         ipf->ipf_hole_cnt--;
6819                         continue;
6820                 }
6821                 mp1 = ipf->ipf_mp->b_cont;
6822                 offset = IP_REASS_START(mp1);
6823                 /* New stuff at the front? */
6824                 if (start < offset) {
6825                         if (start == 0) {
6826                                 if (end >= offset) {
6827                                         /* Nailed the hole at the begining. */
6828                                         ipf->ipf_hole_cnt--;
6829                                 }
6830                         } else if (end < offset) {
6831                                 /*
6832                                  * A hole, stuff, and a hole where there used
6833                                  * to be just a hole.
6834                                  */
6835                                 ipf->ipf_hole_cnt++;
6836                         }
6837                         mp->b_cont = mp1;
6838                         /* Check for overlap. */
6839                         while (end > offset) {
6840                                 if (end < IP_REASS_END(mp1)) {
6841                                         mp->b_wptr -= end - offset;
6842                                         IP_REASS_SET_END(mp, offset);
6843                                         BUMP_MIB(ill->ill_ip_mib,
6844                                             ipIfStatsReasmPartDups);
6845                                         break;
6846                                 }
6847                                 /* Did we cover another hole? */
6848                                 if ((mp1->b_cont &&
6849                                     IP_REASS_END(mp1) !=
6850                                     IP_REASS_START(mp1->b_cont) &&
6851                                     end >= IP_REASS_START(mp1->b_cont)) ||
6852                                     (!ipf->ipf_last_frag_seen && !more)) {
6853                                         ipf->ipf_hole_cnt--;
6854                                 }
6855                                 /* Clip out mp1. */
6856                                 if ((mp->b_cont = mp1->b_cont) == NULL) {
6857                                         /*
6858                                          * After clipping out mp1, this guy
6859                                          * is now hanging off the end.
6860                                          */
6861                                         ipf->ipf_tail_mp = mp;
6862                                 }
6863                                 IP_REASS_SET_START(mp1, 0);
6864                                 IP_REASS_SET_END(mp1, 0);
6865                                 /* Subtract byte count */
6866                                 ipf->ipf_count -= mp1->b_datap->db_lim -
6867                                     mp1->b_datap->db_base;
6868                                 freeb(mp1);
6869                                 BUMP_MIB(ill->ill_ip_mib,
6870                                     ipIfStatsReasmPartDups);
6871                                 mp1 = mp->b_cont;
6872                                 if (!mp1)
6873                                         break;
6874                                 offset = IP_REASS_START(mp1);
6875                         }
6876                         ipf->ipf_mp->b_cont = mp;
6877                         continue;
6878                 }
6879                 /*
6880                  * The new piece starts somewhere between the start of the head
6881                  * and before the end of the tail.
6882                  */
6883                 for (; mp1; mp1 = mp1->b_cont) {
6884                         offset = IP_REASS_END(mp1);
6885                         if (start < offset) {
6886                                 if (end <= offset) {
6887                                         /* Nothing new. */
6888                                         IP_REASS_SET_START(mp, 0);
6889                                         IP_REASS_SET_END(mp, 0);
6890                                         /* Subtract byte count */
6891                                         ipf->ipf_count -= mp->b_datap->db_lim -
6892                                             mp->b_datap->db_base;
6893                                         if (incr_dups) {
6894                                                 ipf->ipf_num_dups++;
6895                                                 incr_dups = B_FALSE;
6896                                         }
6897                                         freeb(mp);
6898                                         BUMP_MIB(ill->ill_ip_mib,
6899                                             ipIfStatsReasmDuplicates);
6900                                         break;
6901                                 }
6902                                 /*
6903                                  * Trim redundant stuff off beginning of new
6904                                  * piece.
6905                                  */
6906                                 IP_REASS_SET_START(mp, offset);
6907                                 mp->b_rptr += offset - start;
6908                                 BUMP_MIB(ill->ill_ip_mib,
6909                                     ipIfStatsReasmPartDups);
6910                                 start = offset;
6911                                 if (!mp1->b_cont) {
6912                                         /*
6913                                          * After trimming, this guy is now
6914                                          * hanging off the end.
6915                                          */
6916                                         mp1->b_cont = mp;
6917                                         ipf->ipf_tail_mp = mp;
6918                                         if (!more) {
6919                                                 ipf->ipf_hole_cnt--;
6920                                         }
6921                                         break;
6922                                 }
6923                         }
6924                         if (start >= IP_REASS_START(mp1->b_cont))
6925                                 continue;
6926                         /* Fill a hole */
6927                         if (start > offset)
6928                                 ipf->ipf_hole_cnt++;
6929                         mp->b_cont = mp1->b_cont;
6930                         mp1->b_cont = mp;
6931                         mp1 = mp->b_cont;
6932                         offset = IP_REASS_START(mp1);
6933                         if (end >= offset) {
6934                                 ipf->ipf_hole_cnt--;
6935                                 /* Check for overlap. */
6936                                 while (end > offset) {
6937                                         if (end < IP_REASS_END(mp1)) {
6938                                                 mp->b_wptr -= end - offset;
6939                                                 IP_REASS_SET_END(mp, offset);
6940                                                 /*
6941                                                  * TODO we might bump
6942                                                  * this up twice if there is
6943                                                  * overlap at both ends.
6944                                                  */
6945                                                 BUMP_MIB(ill->ill_ip_mib,
6946                                                     ipIfStatsReasmPartDups);
6947                                                 break;
6948                                         }
6949                                         /* Did we cover another hole? */
6950                                         if ((mp1->b_cont &&
6951                                             IP_REASS_END(mp1)
6952                                             != IP_REASS_START(mp1->b_cont) &&
6953                                             end >=
6954                                             IP_REASS_START(mp1->b_cont)) ||
6955                                             (!ipf->ipf_last_frag_seen &&
6956                                             !more)) {
6957                                                 ipf->ipf_hole_cnt--;
6958                                         }
6959                                         /* Clip out mp1. */
6960                                         if ((mp->b_cont = mp1->b_cont) ==
6961                                             NULL) {
6962                                                 /*
6963                                                  * After clipping out mp1,
6964                                                  * this guy is now hanging
6965                                                  * off the end.
6966                                                  */
6967                                                 ipf->ipf_tail_mp = mp;
6968                                         }
6969                                         IP_REASS_SET_START(mp1, 0);
6970                                         IP_REASS_SET_END(mp1, 0);
6971                                         /* Subtract byte count */
6972                                         ipf->ipf_count -=
6973                                             mp1->b_datap->db_lim -
6974                                             mp1->b_datap->db_base;
6975                                         freeb(mp1);
6976                                         BUMP_MIB(ill->ill_ip_mib,
6977                                             ipIfStatsReasmPartDups);
6978                                         mp1 = mp->b_cont;
6979                                         if (!mp1)
6980                                                 break;
6981                                         offset = IP_REASS_START(mp1);
6982                                 }
6983                         }
6984                         break;
6985                 }
6986         } while (start = end, mp = next_mp);
6987 
6988         /* Fragment just processed could be the last one. Remember this fact */
6989         if (!more)
6990                 ipf->ipf_last_frag_seen = B_TRUE;
6991 
6992         /* Still got holes? */
6993         if (ipf->ipf_hole_cnt)
6994                 return (IP_REASS_PARTIAL);
6995         /* Clean up overloaded fields to avoid upstream disasters. */
6996         for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6997                 IP_REASS_SET_START(mp1, 0);
6998                 IP_REASS_SET_END(mp1, 0);
6999         }
7000         return (IP_REASS_COMPLETE);
7001 }
7002 
7003 /*
7004  * Fragmentation reassembly.  Each ILL has a hash table for
7005  * queuing packets undergoing reassembly for all IPIFs
7006  * associated with the ILL.  The hash is based on the packet
7007  * IP ident field.  The ILL frag hash table was allocated
7008  * as a timer block at the time the ILL was created.  Whenever
7009  * there is anything on the reassembly queue, the timer will
7010  * be running.  Returns the reassembled packet if reassembly completes.
7011  */
7012 mblk_t *
7013 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7014 {
7015         uint32_t        frag_offset_flags;
7016         mblk_t          *t_mp;
7017         ipaddr_t        dst;
7018         uint8_t         proto = ipha->ipha_protocol;
7019         uint32_t        sum_val;
7020         uint16_t        sum_flags;
7021         ipf_t           *ipf;
7022         ipf_t           **ipfp;
7023         ipfb_t          *ipfb;
7024         uint16_t        ident;
7025         uint32_t        offset;
7026         ipaddr_t        src;
7027         uint_t          hdr_length;
7028         uint32_t        end;
7029         mblk_t          *mp1;
7030         mblk_t          *tail_mp;
7031         size_t          count;
7032         size_t          msg_len;
7033         uint8_t         ecn_info = 0;
7034         uint32_t        packet_size;
7035         boolean_t       pruned = B_FALSE;
7036         ill_t           *ill = ira->ira_ill;
7037         ip_stack_t      *ipst = ill->ill_ipst;
7038 
7039         /*
7040          * Drop the fragmented as early as possible, if
7041          * we don't have resource(s) to re-assemble.
7042          */
7043         if (ipst->ips_ip_reass_queue_bytes == 0) {
7044                 freemsg(mp);
7045                 return (NULL);
7046         }
7047 
7048         /* Check for fragmentation offset; return if there's none */
7049         if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7050             (IPH_MF | IPH_OFFSET)) == 0)
7051                 return (mp);
7052 
7053         /*
7054          * We utilize hardware computed checksum info only for UDP since
7055          * IP fragmentation is a normal occurrence for the protocol.  In
7056          * addition, checksum offload support for IP fragments carrying
7057          * UDP payload is commonly implemented across network adapters.
7058          */
7059         ASSERT(ira->ira_rill != NULL);
7060         if (proto == IPPROTO_UDP && dohwcksum &&
7061             ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7062             (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7063                 mblk_t *mp1 = mp->b_cont;
7064                 int32_t len;
7065 
7066                 /* Record checksum information from the packet */
7067                 sum_val = (uint32_t)DB_CKSUM16(mp);
7068                 sum_flags = DB_CKSUMFLAGS(mp);
7069 
7070                 /* IP payload offset from beginning of mblk */
7071                 offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7072 
7073                 if ((sum_flags & HCK_PARTIALCKSUM) &&
7074                     (mp1 == NULL || mp1->b_cont == NULL) &&
7075                     offset >= DB_CKSUMSTART(mp) &&
7076                     ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7077                         uint32_t adj;
7078                         /*
7079                          * Partial checksum has been calculated by hardware
7080                          * and attached to the packet; in addition, any
7081                          * prepended extraneous data is even byte aligned.
7082                          * If any such data exists, we adjust the checksum;
7083                          * this would also handle any postpended data.
7084                          */
7085                         IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7086                             mp, mp1, len, adj);
7087 
7088                         /* One's complement subtract extraneous checksum */
7089                         if (adj >= sum_val)
7090                                 sum_val = ~(adj - sum_val) & 0xFFFF;
7091                         else
7092                                 sum_val -= adj;
7093                 }
7094         } else {
7095                 sum_val = 0;
7096                 sum_flags = 0;
7097         }
7098 
7099         /* Clear hardware checksumming flag */
7100         DB_CKSUMFLAGS(mp) = 0;
7101 
7102         ident = ipha->ipha_ident;
7103         offset = (frag_offset_flags << 3) & 0xFFFF;
7104         src = ipha->ipha_src;
7105         dst = ipha->ipha_dst;
7106         hdr_length = IPH_HDR_LENGTH(ipha);
7107         end = ntohs(ipha->ipha_length) - hdr_length;
7108 
7109         /* If end == 0 then we have a packet with no data, so just free it */
7110         if (end == 0) {
7111                 freemsg(mp);
7112                 return (NULL);
7113         }
7114 
7115         /* Record the ECN field info. */
7116         ecn_info = (ipha->ipha_type_of_service & 0x3);
7117         if (offset != 0) {
7118                 /*
7119                  * If this isn't the first piece, strip the header, and
7120                  * add the offset to the end value.
7121                  */
7122                 mp->b_rptr += hdr_length;
7123                 end += offset;
7124         }
7125 
7126         /* Handle vnic loopback of fragments */
7127         if (mp->b_datap->db_ref > 2)
7128                 msg_len = 0;
7129         else
7130                 msg_len = MBLKSIZE(mp);
7131 
7132         tail_mp = mp;
7133         while (tail_mp->b_cont != NULL) {
7134                 tail_mp = tail_mp->b_cont;
7135                 if (tail_mp->b_datap->db_ref <= 2)
7136                         msg_len += MBLKSIZE(tail_mp);
7137         }
7138 
7139         /* If the reassembly list for this ILL will get too big, prune it */
7140         if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7141             ipst->ips_ip_reass_queue_bytes) {
7142                 DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7143                     uint_t, ill->ill_frag_count,
7144                     uint_t, ipst->ips_ip_reass_queue_bytes);
7145                 ill_frag_prune(ill,
7146                     (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7147                     (ipst->ips_ip_reass_queue_bytes - msg_len));
7148                 pruned = B_TRUE;
7149         }
7150 
7151         ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7152         mutex_enter(&ipfb->ipfb_lock);
7153 
7154         ipfp = &ipfb->ipfb_ipf;
7155         /* Try to find an existing fragment queue for this packet. */
7156         for (;;) {
7157                 ipf = ipfp[0];
7158                 if (ipf != NULL) {
7159                         /*
7160                          * It has to match on ident and src/dst address.
7161                          */
7162                         if (ipf->ipf_ident == ident &&
7163                             ipf->ipf_src == src &&
7164                             ipf->ipf_dst == dst &&
7165                             ipf->ipf_protocol == proto) {
7166                                 /*
7167                                  * If we have received too many
7168                                  * duplicate fragments for this packet
7169                                  * free it.
7170                                  */
7171                                 if (ipf->ipf_num_dups > ip_max_frag_dups) {
7172                                         ill_frag_free_pkts(ill, ipfb, ipf, 1);
7173                                         freemsg(mp);
7174                                         mutex_exit(&ipfb->ipfb_lock);
7175                                         return (NULL);
7176                                 }
7177                                 /* Found it. */
7178                                 break;
7179                         }
7180                         ipfp = &ipf->ipf_hash_next;
7181                         continue;
7182                 }
7183 
7184                 /*
7185                  * If we pruned the list, do we want to store this new
7186                  * fragment?. We apply an optimization here based on the
7187                  * fact that most fragments will be received in order.
7188                  * So if the offset of this incoming fragment is zero,
7189                  * it is the first fragment of a new packet. We will
7190                  * keep it.  Otherwise drop the fragment, as we have
7191                  * probably pruned the packet already (since the
7192                  * packet cannot be found).
7193                  */
7194                 if (pruned && offset != 0) {
7195                         mutex_exit(&ipfb->ipfb_lock);
7196                         freemsg(mp);
7197                         return (NULL);
7198                 }
7199 
7200                 if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7201                         /*
7202                          * Too many fragmented packets in this hash
7203                          * bucket. Free the oldest.
7204                          */
7205                         ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7206                 }
7207 
7208                 /* New guy.  Allocate a frag message. */
7209                 mp1 = allocb(sizeof (*ipf), BPRI_MED);
7210                 if (mp1 == NULL) {
7211                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7212                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7213                         freemsg(mp);
7214 reass_done:
7215                         mutex_exit(&ipfb->ipfb_lock);
7216                         return (NULL);
7217                 }
7218 
7219                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7220                 mp1->b_cont = mp;
7221 
7222                 /* Initialize the fragment header. */
7223                 ipf = (ipf_t *)mp1->b_rptr;
7224                 ipf->ipf_mp = mp1;
7225                 ipf->ipf_ptphn = ipfp;
7226                 ipfp[0] = ipf;
7227                 ipf->ipf_hash_next = NULL;
7228                 ipf->ipf_ident = ident;
7229                 ipf->ipf_protocol = proto;
7230                 ipf->ipf_src = src;
7231                 ipf->ipf_dst = dst;
7232                 ipf->ipf_nf_hdr_len = 0;
7233                 /* Record reassembly start time. */
7234                 ipf->ipf_timestamp = gethrestime_sec();
7235                 /* Record ipf generation and account for frag header */
7236                 ipf->ipf_gen = ill->ill_ipf_gen++;
7237                 ipf->ipf_count = MBLKSIZE(mp1);
7238                 ipf->ipf_last_frag_seen = B_FALSE;
7239                 ipf->ipf_ecn = ecn_info;
7240                 ipf->ipf_num_dups = 0;
7241                 ipfb->ipfb_frag_pkts++;
7242                 ipf->ipf_checksum = 0;
7243                 ipf->ipf_checksum_flags = 0;
7244 
7245                 /* Store checksum value in fragment header */
7246                 if (sum_flags != 0) {
7247                         sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7248                         sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7249                         ipf->ipf_checksum = sum_val;
7250                         ipf->ipf_checksum_flags = sum_flags;
7251                 }
7252 
7253                 /*
7254                  * We handle reassembly two ways.  In the easy case,
7255                  * where all the fragments show up in order, we do
7256                  * minimal bookkeeping, and just clip new pieces on
7257                  * the end.  If we ever see a hole, then we go off
7258                  * to ip_reassemble which has to mark the pieces and
7259                  * keep track of the number of holes, etc.  Obviously,
7260                  * the point of having both mechanisms is so we can
7261                  * handle the easy case as efficiently as possible.
7262                  */
7263                 if (offset == 0) {
7264                         /* Easy case, in-order reassembly so far. */
7265                         ipf->ipf_count += msg_len;
7266                         ipf->ipf_tail_mp = tail_mp;
7267                         /*
7268                          * Keep track of next expected offset in
7269                          * ipf_end.
7270                          */
7271                         ipf->ipf_end = end;
7272                         ipf->ipf_nf_hdr_len = hdr_length;
7273                 } else {
7274                         /* Hard case, hole at the beginning. */
7275                         ipf->ipf_tail_mp = NULL;
7276                         /*
7277                          * ipf_end == 0 means that we have given up
7278                          * on easy reassembly.
7279                          */
7280                         ipf->ipf_end = 0;
7281 
7282                         /* Forget checksum offload from now on */
7283                         ipf->ipf_checksum_flags = 0;
7284 
7285                         /*
7286                          * ipf_hole_cnt is set by ip_reassemble.
7287                          * ipf_count is updated by ip_reassemble.
7288                          * No need to check for return value here
7289                          * as we don't expect reassembly to complete
7290                          * or fail for the first fragment itself.
7291                          */
7292                         (void) ip_reassemble(mp, ipf,
7293                             (frag_offset_flags & IPH_OFFSET) << 3,
7294                             (frag_offset_flags & IPH_MF), ill, msg_len);
7295                 }
7296                 /* Update per ipfb and ill byte counts */
7297                 ipfb->ipfb_count += ipf->ipf_count;
7298                 ASSERT(ipfb->ipfb_count > 0);     /* Wraparound */
7299                 atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7300                 /* If the frag timer wasn't already going, start it. */
7301                 mutex_enter(&ill->ill_lock);
7302                 ill_frag_timer_start(ill);
7303                 mutex_exit(&ill->ill_lock);
7304                 goto reass_done;
7305         }
7306 
7307         /*
7308          * If the packet's flag has changed (it could be coming up
7309          * from an interface different than the previous, therefore
7310          * possibly different checksum capability), then forget about
7311          * any stored checksum states.  Otherwise add the value to
7312          * the existing one stored in the fragment header.
7313          */
7314         if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7315                 sum_val += ipf->ipf_checksum;
7316                 sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7317                 sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7318                 ipf->ipf_checksum = sum_val;
7319         } else if (ipf->ipf_checksum_flags != 0) {
7320                 /* Forget checksum offload from now on */
7321                 ipf->ipf_checksum_flags = 0;
7322         }
7323 
7324         /*
7325          * We have a new piece of a datagram which is already being
7326          * reassembled.  Update the ECN info if all IP fragments
7327          * are ECN capable.  If there is one which is not, clear
7328          * all the info.  If there is at least one which has CE
7329          * code point, IP needs to report that up to transport.
7330          */
7331         if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7332                 if (ecn_info == IPH_ECN_CE)
7333                         ipf->ipf_ecn = IPH_ECN_CE;
7334         } else {
7335                 ipf->ipf_ecn = IPH_ECN_NECT;
7336         }
7337         if (offset && ipf->ipf_end == offset) {
7338                 /* The new fragment fits at the end */
7339                 ipf->ipf_tail_mp->b_cont = mp;
7340                 /* Update the byte count */
7341                 ipf->ipf_count += msg_len;
7342                 /* Update per ipfb and ill byte counts */
7343                 ipfb->ipfb_count += msg_len;
7344                 ASSERT(ipfb->ipfb_count > 0);     /* Wraparound */
7345                 atomic_add_32(&ill->ill_frag_count, msg_len);
7346                 if (frag_offset_flags & IPH_MF) {
7347                         /* More to come. */
7348                         ipf->ipf_end = end;
7349                         ipf->ipf_tail_mp = tail_mp;
7350                         goto reass_done;
7351                 }
7352         } else {
7353                 /* Go do the hard cases. */
7354                 int ret;
7355 
7356                 if (offset == 0)
7357                         ipf->ipf_nf_hdr_len = hdr_length;
7358 
7359                 /* Save current byte count */
7360                 count = ipf->ipf_count;
7361                 ret = ip_reassemble(mp, ipf,
7362                     (frag_offset_flags & IPH_OFFSET) << 3,
7363                     (frag_offset_flags & IPH_MF), ill, msg_len);
7364                 /* Count of bytes added and subtracted (freeb()ed) */
7365                 count = ipf->ipf_count - count;
7366                 if (count) {
7367                         /* Update per ipfb and ill byte counts */
7368                         ipfb->ipfb_count += count;
7369                         ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7370                         atomic_add_32(&ill->ill_frag_count, count);
7371                 }
7372                 if (ret == IP_REASS_PARTIAL) {
7373                         goto reass_done;
7374                 } else if (ret == IP_REASS_FAILED) {
7375                         /* Reassembly failed. Free up all resources */
7376                         ill_frag_free_pkts(ill, ipfb, ipf, 1);
7377                         for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7378                                 IP_REASS_SET_START(t_mp, 0);
7379                                 IP_REASS_SET_END(t_mp, 0);
7380                         }
7381                         freemsg(mp);
7382                         goto reass_done;
7383                 }
7384                 /* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7385         }
7386         /*
7387          * We have completed reassembly.  Unhook the frag header from
7388          * the reassembly list.
7389          *
7390          * Before we free the frag header, record the ECN info
7391          * to report back to the transport.
7392          */
7393         ecn_info = ipf->ipf_ecn;
7394         BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7395         ipfp = ipf->ipf_ptphn;
7396 
7397         /* We need to supply these to caller */
7398         if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7399                 sum_val = ipf->ipf_checksum;
7400         else
7401                 sum_val = 0;
7402 
7403         mp1 = ipf->ipf_mp;
7404         count = ipf->ipf_count;
7405         ipf = ipf->ipf_hash_next;
7406         if (ipf != NULL)
7407                 ipf->ipf_ptphn = ipfp;
7408         ipfp[0] = ipf;
7409         atomic_add_32(&ill->ill_frag_count, -count);
7410         ASSERT(ipfb->ipfb_count >= count);
7411         ipfb->ipfb_count -= count;
7412         ipfb->ipfb_frag_pkts--;
7413         mutex_exit(&ipfb->ipfb_lock);
7414         /* Ditch the frag header. */
7415         mp = mp1->b_cont;
7416 
7417         freeb(mp1);
7418 
7419         /* Restore original IP length in header. */
7420         packet_size = (uint32_t)msgdsize(mp);
7421         if (packet_size > IP_MAXPACKET) {
7422                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7423                 ip_drop_input("Reassembled packet too large", mp, ill);
7424                 freemsg(mp);
7425                 return (NULL);
7426         }
7427 
7428         if (DB_REF(mp) > 1) {
7429                 mblk_t *mp2 = copymsg(mp);
7430 
7431                 if (mp2 == NULL) {
7432                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7433                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7434                         freemsg(mp);
7435                         return (NULL);
7436                 }
7437                 freemsg(mp);
7438                 mp = mp2;
7439         }
7440         ipha = (ipha_t *)mp->b_rptr;
7441 
7442         ipha->ipha_length = htons((uint16_t)packet_size);
7443         /* We're now complete, zip the frag state */
7444         ipha->ipha_fragment_offset_and_flags = 0;
7445         /* Record the ECN info. */
7446         ipha->ipha_type_of_service &= 0xFC;
7447         ipha->ipha_type_of_service |= ecn_info;
7448 
7449         /* Update the receive attributes */
7450         ira->ira_pktlen = packet_size;
7451         ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7452 
7453         /* Reassembly is successful; set checksum information in packet */
7454         DB_CKSUM16(mp) = (uint16_t)sum_val;
7455         DB_CKSUMFLAGS(mp) = sum_flags;
7456         DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7457 
7458         return (mp);
7459 }
7460 
7461 /*
7462  * Pullup function that should be used for IP input in order to
7463  * ensure we do not loose the L2 source address; we need the l2 source
7464  * address for IP_RECVSLLA and for ndp_input.
7465  *
7466  * We return either NULL or b_rptr.
7467  */
7468 void *
7469 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7470 {
7471         ill_t           *ill = ira->ira_ill;
7472 
7473         if (ip_rput_pullups++ == 0) {
7474                 (void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7475                     "ip_pullup: %s forced us to "
7476                     " pullup pkt, hdr len %ld, hdr addr %p",
7477                     ill->ill_name, len, (void *)mp->b_rptr);
7478         }
7479         if (!(ira->ira_flags & IRAF_L2SRC_SET))
7480                 ip_setl2src(mp, ira, ira->ira_rill);
7481         ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7482         if (!pullupmsg(mp, len))
7483                 return (NULL);
7484         else
7485                 return (mp->b_rptr);
7486 }
7487 
7488 /*
7489  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7490  * When called from the ULP ira_rill will be NULL hence the caller has to
7491  * pass in the ill.
7492  */
7493 /* ARGSUSED */
7494 void
7495 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7496 {
7497         const uchar_t *addr;
7498         int alen;
7499 
7500         if (ira->ira_flags & IRAF_L2SRC_SET)
7501                 return;
7502 
7503         ASSERT(ill != NULL);
7504         alen = ill->ill_phys_addr_length;
7505         ASSERT(alen <= sizeof (ira->ira_l2src));
7506         if (ira->ira_mhip != NULL &&
7507             (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7508                 bcopy(addr, ira->ira_l2src, alen);
7509         } else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7510             (addr = ill->ill_phys_addr) != NULL) {
7511                 bcopy(addr, ira->ira_l2src, alen);
7512         } else {
7513                 bzero(ira->ira_l2src, alen);
7514         }
7515         ira->ira_flags |= IRAF_L2SRC_SET;
7516 }
7517 
7518 /*
7519  * check ip header length and align it.
7520  */
7521 mblk_t *
7522 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7523 {
7524         ill_t   *ill = ira->ira_ill;
7525         ssize_t len;
7526 
7527         len = MBLKL(mp);
7528 
7529         if (!OK_32PTR(mp->b_rptr))
7530                 IP_STAT(ill->ill_ipst, ip_notaligned);
7531         else
7532                 IP_STAT(ill->ill_ipst, ip_recv_pullup);
7533 
7534         /* Guard against bogus device drivers */
7535         if (len < 0) {
7536                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7537                 ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7538                 freemsg(mp);
7539                 return (NULL);
7540         }
7541 
7542         if (len == 0) {
7543                 /* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7544                 mblk_t *mp1 = mp->b_cont;
7545 
7546                 if (!(ira->ira_flags & IRAF_L2SRC_SET))
7547                         ip_setl2src(mp, ira, ira->ira_rill);
7548                 ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7549 
7550                 freeb(mp);
7551                 mp = mp1;
7552                 if (mp == NULL)
7553                         return (NULL);
7554 
7555                 if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7556                         return (mp);
7557         }
7558         if (ip_pullup(mp, min_size, ira) == NULL) {
7559                 if (msgdsize(mp) < min_size) {
7560                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7561                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7562                 } else {
7563                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7564                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7565                 }
7566                 freemsg(mp);
7567                 return (NULL);
7568         }
7569         return (mp);
7570 }
7571 
7572 /*
7573  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7574  */
7575 mblk_t *
7576 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len, uint_t pkt_len,
7577     uint_t min_size, ip_recv_attr_t *ira)
7578 {
7579         ill_t   *ill = ira->ira_ill;
7580 
7581         /*
7582          * Make sure we have data length consistent
7583          * with the IP header.
7584          */
7585         if (mp->b_cont == NULL) {
7586                 /* pkt_len is based on ipha_len, not the mblk length */
7587                 if (pkt_len < min_size) {
7588                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7589                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7590                         freemsg(mp);
7591                         return (NULL);
7592                 }
7593                 if (len < 0) {
7594                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7595                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7596                         freemsg(mp);
7597                         return (NULL);
7598                 }
7599                 /* Drop any pad */
7600                 mp->b_wptr = rptr + pkt_len;
7601         } else if ((len += msgdsize(mp->b_cont)) != 0) {
7602                 ASSERT(pkt_len >= min_size);
7603                 if (pkt_len < min_size) {
7604                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7605                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7606                         freemsg(mp);
7607                         return (NULL);
7608                 }
7609                 if (len < 0) {
7610                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7611                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7612                         freemsg(mp);
7613                         return (NULL);
7614                 }
7615                 /* Drop any pad */
7616                 (void) adjmsg(mp, -len);
7617                 /*
7618                  * adjmsg may have freed an mblk from the chain, hence
7619                  * invalidate any hw checksum here. This will force IP to
7620                  * calculate the checksum in sw, but only for this packet.
7621                  */
7622                 DB_CKSUMFLAGS(mp) = 0;
7623                 IP_STAT(ill->ill_ipst, ip_multimblk);
7624         }
7625         return (mp);
7626 }
7627 
7628 /*
7629  * Check that the IPv4 opt_len is consistent with the packet and pullup
7630  * the options.
7631  */
7632 mblk_t *
7633 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7634     ip_recv_attr_t *ira)
7635 {
7636         ill_t   *ill = ira->ira_ill;
7637         ssize_t len;
7638 
7639         /* Assume no IPv6 packets arrive over the IPv4 queue */
7640         if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7641                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7642                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7643                 ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7644                 freemsg(mp);
7645                 return (NULL);
7646         }
7647 
7648         if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7649                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7650                 ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7651                 freemsg(mp);
7652                 return (NULL);
7653         }
7654         /*
7655          * Recompute complete header length and make sure we
7656          * have access to all of it.
7657          */
7658         len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7659         if (len > (mp->b_wptr - mp->b_rptr)) {
7660                 if (len > pkt_len) {
7661                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7662                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7663                         freemsg(mp);
7664                         return (NULL);
7665                 }
7666                 if (ip_pullup(mp, len, ira) == NULL) {
7667                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7668                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7669                         freemsg(mp);
7670                         return (NULL);
7671                 }
7672         }
7673         return (mp);
7674 }
7675 
7676 /*
7677  * Returns a new ire, or the same ire, or NULL.
7678  * If a different IRE is returned, then it is held; the caller
7679  * needs to release it.
7680  * In no case is there any hold/release on the ire argument.
7681  */
7682 ire_t *
7683 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7684 {
7685         ire_t           *new_ire;
7686         ill_t           *ire_ill;
7687         uint_t          ifindex;
7688         ip_stack_t      *ipst = ill->ill_ipst;
7689         boolean_t       strict_check = B_FALSE;
7690 
7691         /*
7692          * IPMP common case: if IRE and ILL are in the same group, there's no
7693          * issue (e.g. packet received on an underlying interface matched an
7694          * IRE_LOCAL on its associated group interface).
7695          */
7696         ASSERT(ire->ire_ill != NULL);
7697         if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7698                 return (ire);
7699 
7700         /*
7701          * Do another ire lookup here, using the ingress ill, to see if the
7702          * interface is in a usesrc group.
7703          * As long as the ills belong to the same group, we don't consider
7704          * them to be arriving on the wrong interface. Thus, if the switch
7705          * is doing inbound load spreading, we won't drop packets when the
7706          * ip*_strict_dst_multihoming switch is on.
7707          * We also need to check for IPIF_UNNUMBERED point2point interfaces
7708          * where the local address may not be unique. In this case we were
7709          * at the mercy of the initial ire lookup and the IRE_LOCAL it
7710          * actually returned. The new lookup, which is more specific, should
7711          * only find the IRE_LOCAL associated with the ingress ill if one
7712          * exists.
7713          */
7714         if (ire->ire_ipversion == IPV4_VERSION) {
7715                 if (ipst->ips_ip_strict_dst_multihoming)
7716                         strict_check = B_TRUE;
7717                 new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7718                     IRE_LOCAL, ill, ALL_ZONES, NULL,
7719                     (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7720         } else {
7721                 ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7722                 if (ipst->ips_ipv6_strict_dst_multihoming)
7723                         strict_check = B_TRUE;
7724                 new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7725                     IRE_LOCAL, ill, ALL_ZONES, NULL,
7726                     (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7727         }
7728         /*
7729          * If the same ire that was returned in ip_input() is found then this
7730          * is an indication that usesrc groups are in use. The packet
7731          * arrived on a different ill in the group than the one associated with
7732          * the destination address.  If a different ire was found then the same
7733          * IP address must be hosted on multiple ills. This is possible with
7734          * unnumbered point2point interfaces. We switch to use this new ire in
7735          * order to have accurate interface statistics.
7736          */
7737         if (new_ire != NULL) {
7738                 /* Note: held in one case but not the other? Caller handles */
7739                 if (new_ire != ire)
7740                         return (new_ire);
7741                 /* Unchanged */
7742                 ire_refrele(new_ire);
7743                 return (ire);
7744         }
7745 
7746         /*
7747          * Chase pointers once and store locally.
7748          */
7749         ASSERT(ire->ire_ill != NULL);
7750         ire_ill = ire->ire_ill;
7751         ifindex = ill->ill_usesrc_ifindex;
7752 
7753         /*
7754          * Check if it's a legal address on the 'usesrc' interface.
7755          * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7756          * can just check phyint_ifindex.
7757          */
7758         if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7759                 return (ire);
7760         }
7761 
7762         /*
7763          * If the ip*_strict_dst_multihoming switch is on then we can
7764          * only accept this packet if the interface is marked as routing.
7765          */
7766         if (!(strict_check))
7767                 return (ire);
7768 
7769         if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7770                 return (ire);
7771         }
7772         return (NULL);
7773 }
7774 
7775 /*
7776  * This function is used to construct a mac_header_info_s from a
7777  * DL_UNITDATA_IND message.
7778  * The address fields in the mhi structure points into the message,
7779  * thus the caller can't use those fields after freeing the message.
7780  *
7781  * We determine whether the packet received is a non-unicast packet
7782  * and in doing so, determine whether or not it is broadcast vs multicast.
7783  * For it to be a broadcast packet, we must have the appropriate mblk_t
7784  * hanging off the ill_t.  If this is either not present or doesn't match
7785  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7786  * to be multicast.  Thus NICs that have no broadcast address (or no
7787  * capability for one, such as point to point links) cannot return as
7788  * the packet being broadcast.
7789  */
7790 void
7791 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7792 {
7793         dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7794         mblk_t *bmp;
7795         uint_t extra_offset;
7796 
7797         bzero(mhip, sizeof (struct mac_header_info_s));
7798 
7799         mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7800 
7801         if (ill->ill_sap_length < 0)
7802                 extra_offset = 0;
7803         else
7804                 extra_offset = ill->ill_sap_length;
7805 
7806         mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7807             extra_offset;
7808         mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7809             extra_offset;
7810 
7811         if (!ind->dl_group_address)
7812                 return;
7813 
7814         /* Multicast or broadcast */
7815         mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7816 
7817         if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7818             ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7819             (bmp = ill->ill_bcast_mp) != NULL) {
7820                 dl_unitdata_req_t *dlur;
7821                 uint8_t *bphys_addr;
7822 
7823                 dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7824                 bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7825                     extra_offset;
7826 
7827                 if (bcmp(mhip->mhi_daddr, bphys_addr,
7828                     ind->dl_dest_addr_length) == 0)
7829                         mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7830         }
7831 }
7832 
7833 /*
7834  * This function is used to construct a mac_header_info_s from a
7835  * M_DATA fastpath message from a DLPI driver.
7836  * The address fields in the mhi structure points into the message,
7837  * thus the caller can't use those fields after freeing the message.
7838  *
7839  * We determine whether the packet received is a non-unicast packet
7840  * and in doing so, determine whether or not it is broadcast vs multicast.
7841  * For it to be a broadcast packet, we must have the appropriate mblk_t
7842  * hanging off the ill_t.  If this is either not present or doesn't match
7843  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7844  * to be multicast.  Thus NICs that have no broadcast address (or no
7845  * capability for one, such as point to point links) cannot return as
7846  * the packet being broadcast.
7847  */
7848 void
7849 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7850 {
7851         mblk_t *bmp;
7852         struct ether_header *pether;
7853 
7854         bzero(mhip, sizeof (struct mac_header_info_s));
7855 
7856         mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7857 
7858         pether = (struct ether_header *)((char *)mp->b_rptr
7859             - sizeof (struct ether_header));
7860 
7861         /*
7862          * Make sure the interface is an ethernet type, since we don't
7863          * know the header format for anything but Ethernet. Also make
7864          * sure we are pointing correctly above db_base.
7865          */
7866         if (ill->ill_type != IFT_ETHER)
7867                 return;
7868 
7869 retry:
7870         if ((uchar_t *)pether < mp->b_datap->db_base)
7871                 return;
7872 
7873         /* Is there a VLAN tag? */
7874         if (ill->ill_isv6) {
7875                 if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7876                         pether = (struct ether_header *)((char *)pether - 4);
7877                         goto retry;
7878                 }
7879         } else {
7880                 if (pether->ether_type != htons(ETHERTYPE_IP)) {
7881                         pether = (struct ether_header *)((char *)pether - 4);
7882                         goto retry;
7883                 }
7884         }
7885         mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7886         mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7887 
7888         if (!(mhip->mhi_daddr[0] & 0x01))
7889                 return;
7890 
7891         /* Multicast or broadcast */
7892         mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7893 
7894         if ((bmp = ill->ill_bcast_mp) != NULL) {
7895                 dl_unitdata_req_t *dlur;
7896                 uint8_t *bphys_addr;
7897                 uint_t  addrlen;
7898 
7899                 dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7900                 addrlen = dlur->dl_dest_addr_length;
7901                 if (ill->ill_sap_length < 0) {
7902                         bphys_addr = (uchar_t *)dlur +
7903                             dlur->dl_dest_addr_offset;
7904                         addrlen += ill->ill_sap_length;
7905                 } else {
7906                         bphys_addr = (uchar_t *)dlur +
7907                             dlur->dl_dest_addr_offset +
7908                             ill->ill_sap_length;
7909                         addrlen -= ill->ill_sap_length;
7910                 }
7911                 if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7912                         mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7913         }
7914 }
7915 
7916 /*
7917  * Handle anything but M_DATA messages
7918  * We see the DL_UNITDATA_IND which are part
7919  * of the data path, and also the other messages from the driver.
7920  */
7921 void
7922 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7923 {
7924         mblk_t          *first_mp;
7925         struct iocblk   *iocp;
7926         struct mac_header_info_s mhi;
7927 
7928         switch (DB_TYPE(mp)) {
7929         case M_PROTO:
7930         case M_PCPROTO: {
7931                 if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7932                     DL_UNITDATA_IND) {
7933                         /* Go handle anything other than data elsewhere. */
7934                         ip_rput_dlpi(ill, mp);
7935                         return;
7936                 }
7937 
7938                 first_mp = mp;
7939                 mp = first_mp->b_cont;
7940                 first_mp->b_cont = NULL;
7941 
7942                 if (mp == NULL) {
7943                         freeb(first_mp);
7944                         return;
7945                 }
7946                 ip_dlur_to_mhi(ill, first_mp, &mhi);
7947                 if (ill->ill_isv6)
7948                         ip_input_v6(ill, NULL, mp, &mhi);
7949                 else
7950                         ip_input(ill, NULL, mp, &mhi);
7951 
7952                 /* Ditch the DLPI header. */
7953                 freeb(first_mp);
7954                 return;
7955         }
7956         case M_IOCACK:
7957                 iocp = (struct iocblk *)mp->b_rptr;
7958                 switch (iocp->ioc_cmd) {
7959                 case DL_IOC_HDR_INFO:
7960                         ill_fastpath_ack(ill, mp);
7961                         return;
7962                 default:
7963                         putnext(ill->ill_rq, mp);
7964                         return;
7965                 }
7966                 /* FALLTHRU */
7967         case M_ERROR:
7968         case M_HANGUP:
7969                 mutex_enter(&ill->ill_lock);
7970                 if (ill->ill_state_flags & ILL_CONDEMNED) {
7971                         mutex_exit(&ill->ill_lock);
7972                         freemsg(mp);
7973                         return;
7974                 }
7975                 ill_refhold_locked(ill);
7976                 mutex_exit(&ill->ill_lock);
7977                 qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7978                     B_FALSE);
7979                 return;
7980         case M_CTL:
7981                 putnext(ill->ill_rq, mp);
7982                 return;
7983         case M_IOCNAK:
7984                 ip1dbg(("got iocnak "));
7985                 iocp = (struct iocblk *)mp->b_rptr;
7986                 switch (iocp->ioc_cmd) {
7987                 case DL_IOC_HDR_INFO:
7988                         ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7989                         return;
7990                 default:
7991                         break;
7992                 }
7993                 /* FALLTHRU */
7994         default:
7995                 putnext(ill->ill_rq, mp);
7996                 return;
7997         }
7998 }
7999 
8000 /* Read side put procedure.  Packets coming from the wire arrive here. */
8001 void
8002 ip_rput(queue_t *q, mblk_t *mp)
8003 {
8004         ill_t   *ill;
8005         union DL_primitives *dl;
8006 
8007         ill = (ill_t *)q->q_ptr;
8008 
8009         if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8010                 /*
8011                  * If things are opening or closing, only accept high-priority
8012                  * DLPI messages.  (On open ill->ill_ipif has not yet been
8013                  * created; on close, things hanging off the ill may have been
8014                  * freed already.)
8015                  */
8016                 dl = (union DL_primitives *)mp->b_rptr;
8017                 if (DB_TYPE(mp) != M_PCPROTO ||
8018                     dl->dl_primitive == DL_UNITDATA_IND) {
8019                         inet_freemsg(mp);
8020                         return;
8021                 }
8022         }
8023         if (DB_TYPE(mp) == M_DATA) {
8024                 struct mac_header_info_s mhi;
8025 
8026                 ip_mdata_to_mhi(ill, mp, &mhi);
8027                 ip_input(ill, NULL, mp, &mhi);
8028         } else {
8029                 ip_rput_notdata(ill, mp);
8030         }
8031 }
8032 
8033 /*
8034  * Move the information to a copy.
8035  */
8036 mblk_t *
8037 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8038 {
8039         mblk_t          *mp1;
8040         ill_t           *ill = ira->ira_ill;
8041         ip_stack_t      *ipst = ill->ill_ipst;
8042 
8043         IP_STAT(ipst, ip_db_ref);
8044 
8045         /* Make sure we have ira_l2src before we loose the original mblk */
8046         if (!(ira->ira_flags & IRAF_L2SRC_SET))
8047                 ip_setl2src(mp, ira, ira->ira_rill);
8048 
8049         mp1 = copymsg(mp);
8050         if (mp1 == NULL) {
8051                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8052                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
8053                 freemsg(mp);
8054                 return (NULL);
8055         }
8056         /* preserve the hardware checksum flags and data, if present */
8057         if (DB_CKSUMFLAGS(mp) != 0) {
8058                 DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8059                 DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8060                 DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8061                 DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8062                 DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8063         }
8064         freemsg(mp);
8065         return (mp1);
8066 }
8067 
8068 static void
8069 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8070     t_uscalar_t err)
8071 {
8072         if (dl_err == DL_SYSERR) {
8073                 (void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8074                     "%s: %s failed: DL_SYSERR (errno %u)\n",
8075                     ill->ill_name, dl_primstr(prim), err);
8076                 return;
8077         }
8078 
8079         (void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8080             "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8081             dl_errstr(dl_err));
8082 }
8083 
8084 /*
8085  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8086  * than DL_UNITDATA_IND messages. If we need to process this message
8087  * exclusively, we call qwriter_ip, in which case we also need to call
8088  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8089  */
8090 void
8091 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8092 {
8093         dl_ok_ack_t     *dloa = (dl_ok_ack_t *)mp->b_rptr;
8094         dl_error_ack_t  *dlea = (dl_error_ack_t *)dloa;
8095         queue_t         *q = ill->ill_rq;
8096         t_uscalar_t     prim = dloa->dl_primitive;
8097         t_uscalar_t     reqprim = DL_PRIM_INVAL;
8098 
8099         DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8100             char *, dl_primstr(prim), ill_t *, ill);
8101         ip1dbg(("ip_rput_dlpi"));
8102 
8103         /*
8104          * If we received an ACK but didn't send a request for it, then it
8105          * can't be part of any pending operation; discard up-front.
8106          */
8107         switch (prim) {
8108         case DL_ERROR_ACK:
8109                 reqprim = dlea->dl_error_primitive;
8110                 ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8111                     "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8112                     reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8113                     dlea->dl_unix_errno));
8114                 break;
8115         case DL_OK_ACK:
8116                 reqprim = dloa->dl_correct_primitive;
8117                 break;
8118         case DL_INFO_ACK:
8119                 reqprim = DL_INFO_REQ;
8120                 break;
8121         case DL_BIND_ACK:
8122                 reqprim = DL_BIND_REQ;
8123                 break;
8124         case DL_PHYS_ADDR_ACK:
8125                 reqprim = DL_PHYS_ADDR_REQ;
8126                 break;
8127         case DL_NOTIFY_ACK:
8128                 reqprim = DL_NOTIFY_REQ;
8129                 break;
8130         case DL_CAPABILITY_ACK:
8131                 reqprim = DL_CAPABILITY_REQ;
8132                 break;
8133         }
8134 
8135         if (prim != DL_NOTIFY_IND) {
8136                 if (reqprim == DL_PRIM_INVAL ||
8137                     !ill_dlpi_pending(ill, reqprim)) {
8138                         /* Not a DLPI message we support or expected */
8139                         freemsg(mp);
8140                         return;
8141                 }
8142                 ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8143                     dl_primstr(reqprim)));
8144         }
8145 
8146         switch (reqprim) {
8147         case DL_UNBIND_REQ:
8148                 /*
8149                  * NOTE: we mark the unbind as complete even if we got a
8150                  * DL_ERROR_ACK, since there's not much else we can do.
8151                  */
8152                 mutex_enter(&ill->ill_lock);
8153                 ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8154                 cv_signal(&ill->ill_cv);
8155                 mutex_exit(&ill->ill_lock);
8156                 break;
8157 
8158         case DL_ENABMULTI_REQ:
8159                 if (prim == DL_OK_ACK) {
8160                         if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8161                                 ill->ill_dlpi_multicast_state = IDS_OK;
8162                 }
8163                 break;
8164         }
8165 
8166         /*
8167          * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8168          * need to become writer to continue to process it.  Because an
8169          * exclusive operation doesn't complete until replies to all queued
8170          * DLPI messages have been received, we know we're in the middle of an
8171          * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8172          *
8173          * As required by qwriter_ip(), we refhold the ill; it will refrele.
8174          * Since this is on the ill stream we unconditionally bump up the
8175          * refcount without doing ILL_CAN_LOOKUP().
8176          */
8177         ill_refhold(ill);
8178         if (prim == DL_NOTIFY_IND)
8179                 qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8180         else
8181                 qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8182 }
8183 
8184 /*
8185  * Handling of DLPI messages that require exclusive access to the ipsq.
8186  *
8187  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8188  * happen here. (along with mi_copy_done)
8189  */
8190 /* ARGSUSED */
8191 static void
8192 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8193 {
8194         dl_ok_ack_t     *dloa = (dl_ok_ack_t *)mp->b_rptr;
8195         dl_error_ack_t  *dlea = (dl_error_ack_t *)dloa;
8196         int             err = 0;
8197         ill_t           *ill = (ill_t *)q->q_ptr;
8198         ipif_t          *ipif = NULL;
8199         mblk_t          *mp1 = NULL;
8200         conn_t          *connp = NULL;
8201         t_uscalar_t     paddrreq;
8202         mblk_t          *mp_hw;
8203         boolean_t       success;
8204         boolean_t       ioctl_aborted = B_FALSE;
8205         boolean_t       log = B_TRUE;
8206 
8207         DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8208             char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8209 
8210         ip1dbg(("ip_rput_dlpi_writer .."));
8211         ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8212         ASSERT(IAM_WRITER_ILL(ill));
8213 
8214         ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8215         /*
8216          * The current ioctl could have been aborted by the user and a new
8217          * ioctl to bring up another ill could have started. We could still
8218          * get a response from the driver later.
8219          */
8220         if (ipif != NULL && ipif->ipif_ill != ill)
8221                 ioctl_aborted = B_TRUE;
8222 
8223         switch (dloa->dl_primitive) {
8224         case DL_ERROR_ACK:
8225                 ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8226                     dl_primstr(dlea->dl_error_primitive)));
8227 
8228                 DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8229                     char *, dl_primstr(dlea->dl_error_primitive),
8230                     ill_t *, ill);
8231 
8232                 switch (dlea->dl_error_primitive) {
8233                 case DL_DISABMULTI_REQ:
8234                         ill_dlpi_done(ill, dlea->dl_error_primitive);
8235                         break;
8236                 case DL_PROMISCON_REQ:
8237                 case DL_PROMISCOFF_REQ:
8238                 case DL_UNBIND_REQ:
8239                 case DL_ATTACH_REQ:
8240                 case DL_INFO_REQ:
8241                         ill_dlpi_done(ill, dlea->dl_error_primitive);
8242                         break;
8243                 case DL_NOTIFY_REQ:
8244                         ill_dlpi_done(ill, DL_NOTIFY_REQ);
8245                         log = B_FALSE;
8246                         break;
8247                 case DL_PHYS_ADDR_REQ:
8248                         /*
8249                          * For IPv6 only, there are two additional
8250                          * phys_addr_req's sent to the driver to get the
8251                          * IPv6 token and lla. This allows IP to acquire
8252                          * the hardware address format for a given interface
8253                          * without having built in knowledge of the hardware
8254                          * address. ill_phys_addr_pend keeps track of the last
8255                          * DL_PAR sent so we know which response we are
8256                          * dealing with. ill_dlpi_done will update
8257                          * ill_phys_addr_pend when it sends the next req.
8258                          * We don't complete the IOCTL until all three DL_PARs
8259                          * have been attempted, so set *_len to 0 and break.
8260                          */
8261                         paddrreq = ill->ill_phys_addr_pend;
8262                         ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8263                         if (paddrreq == DL_IPV6_TOKEN) {
8264                                 ill->ill_token_length = 0;
8265                                 log = B_FALSE;
8266                                 break;
8267                         } else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8268                                 ill->ill_nd_lla_len = 0;
8269                                 log = B_FALSE;
8270                                 break;
8271                         }
8272                         /*
8273                          * Something went wrong with the DL_PHYS_ADDR_REQ.
8274                          * We presumably have an IOCTL hanging out waiting
8275                          * for completion. Find it and complete the IOCTL
8276                          * with the error noted.
8277                          * However, ill_dl_phys was called on an ill queue
8278                          * (from SIOCSLIFNAME), thus conn_pending_ill is not
8279                          * set. But the ioctl is known to be pending on ill_wq.
8280                          */
8281                         if (!ill->ill_ifname_pending)
8282                                 break;
8283                         ill->ill_ifname_pending = 0;
8284                         if (!ioctl_aborted)
8285                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8286                         if (mp1 != NULL) {
8287                                 /*
8288                                  * This operation (SIOCSLIFNAME) must have
8289                                  * happened on the ill. Assert there is no conn
8290                                  */
8291                                 ASSERT(connp == NULL);
8292                                 q = ill->ill_wq;
8293                         }
8294                         break;
8295                 case DL_BIND_REQ:
8296                         ill_dlpi_done(ill, DL_BIND_REQ);
8297                         if (ill->ill_ifname_pending)
8298                                 break;
8299                         mutex_enter(&ill->ill_lock);
8300                         ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8301                         mutex_exit(&ill->ill_lock);
8302                         /*
8303                          * Something went wrong with the bind.  We presumably
8304                          * have an IOCTL hanging out waiting for completion.
8305                          * Find it, take down the interface that was coming
8306                          * up, and complete the IOCTL with the error noted.
8307                          */
8308                         if (!ioctl_aborted)
8309                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8310                         if (mp1 != NULL) {
8311                                 /*
8312                                  * This might be a result of a DL_NOTE_REPLUMB
8313                                  * notification. In that case, connp is NULL.
8314                                  */
8315                                 if (connp != NULL)
8316                                         q = CONNP_TO_WQ(connp);
8317 
8318                                 (void) ipif_down(ipif, NULL, NULL);
8319                                 /* error is set below the switch */
8320                         }
8321                         break;
8322                 case DL_ENABMULTI_REQ:
8323                         ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8324 
8325                         if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8326                                 ill->ill_dlpi_multicast_state = IDS_FAILED;
8327                         if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8328 
8329                                 printf("ip: joining multicasts failed (%d)"
8330                                     " on %s - will use link layer "
8331                                     "broadcasts for multicast\n",
8332                                     dlea->dl_errno, ill->ill_name);
8333 
8334                                 /*
8335                                  * Set up for multi_bcast; We are the
8336                                  * writer, so ok to access ill->ill_ipif
8337                                  * without any lock.
8338                                  */
8339                                 mutex_enter(&ill->ill_phyint->phyint_lock);
8340                                 ill->ill_phyint->phyint_flags |=
8341                                     PHYI_MULTI_BCAST;
8342                                 mutex_exit(&ill->ill_phyint->phyint_lock);
8343 
8344                         }
8345                         freemsg(mp);    /* Don't want to pass this up */
8346                         return;
8347                 case DL_CAPABILITY_REQ:
8348                         ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8349                             "DL_CAPABILITY REQ\n"));
8350                         if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8351                                 ill->ill_dlpi_capab_state = IDCS_FAILED;
8352                         ill_capability_done(ill);
8353                         freemsg(mp);
8354                         return;
8355                 }
8356                 /*
8357                  * Note the error for IOCTL completion (mp1 is set when
8358                  * ready to complete ioctl). If ill_ifname_pending_err is
8359                  * set, an error occured during plumbing (ill_ifname_pending),
8360                  * so we want to report that error.
8361                  *
8362                  * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8363                  * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8364                  * expected to get errack'd if the driver doesn't support
8365                  * these flags (e.g. ethernet). log will be set to B_FALSE
8366                  * if these error conditions are encountered.
8367                  */
8368                 if (mp1 != NULL) {
8369                         if (ill->ill_ifname_pending_err != 0)  {
8370                                 err = ill->ill_ifname_pending_err;
8371                                 ill->ill_ifname_pending_err = 0;
8372                         } else {
8373                                 err = dlea->dl_unix_errno ?
8374                                     dlea->dl_unix_errno : ENXIO;
8375                         }
8376                 /*
8377                  * If we're plumbing an interface and an error hasn't already
8378                  * been saved, set ill_ifname_pending_err to the error passed
8379                  * up. Ignore the error if log is B_FALSE (see comment above).
8380                  */
8381                 } else if (log && ill->ill_ifname_pending &&
8382                     ill->ill_ifname_pending_err == 0) {
8383                         ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8384                             dlea->dl_unix_errno : ENXIO;
8385                 }
8386 
8387                 if (log)
8388                         ip_dlpi_error(ill, dlea->dl_error_primitive,
8389                             dlea->dl_errno, dlea->dl_unix_errno);
8390                 break;
8391         case DL_CAPABILITY_ACK:
8392                 ill_capability_ack(ill, mp);
8393                 /*
8394                  * The message has been handed off to ill_capability_ack
8395                  * and must not be freed below
8396                  */
8397                 mp = NULL;
8398                 break;
8399 
8400         case DL_INFO_ACK:
8401                 /* Call a routine to handle this one. */
8402                 ill_dlpi_done(ill, DL_INFO_REQ);
8403                 ip_ll_subnet_defaults(ill, mp);
8404                 ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8405                 return;
8406         case DL_BIND_ACK:
8407                 /*
8408                  * We should have an IOCTL waiting on this unless
8409                  * sent by ill_dl_phys, in which case just return
8410                  */
8411                 ill_dlpi_done(ill, DL_BIND_REQ);
8412 
8413                 if (ill->ill_ifname_pending) {
8414                         DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8415                             ill_t *, ill, mblk_t *, mp);
8416                         break;
8417                 }
8418                 mutex_enter(&ill->ill_lock);
8419                 ill->ill_dl_up = 1;
8420                 ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8421                 mutex_exit(&ill->ill_lock);
8422 
8423                 if (!ioctl_aborted)
8424                         mp1 = ipsq_pending_mp_get(ipsq, &connp);
8425                 if (mp1 == NULL) {
8426                         DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8427                         break;
8428                 }
8429                 /*
8430                  * mp1 was added by ill_dl_up(). if that is a result of
8431                  * a DL_NOTE_REPLUMB notification, connp could be NULL.
8432                  */
8433                 if (connp != NULL)
8434                         q = CONNP_TO_WQ(connp);
8435                 /*
8436                  * We are exclusive. So nothing can change even after
8437                  * we get the pending mp.
8438                  */
8439                 ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8440                 DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8441                 ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8442 
8443                 /*
8444                  * Now bring up the resolver; when that is complete, we'll
8445                  * create IREs.  Note that we intentionally mirror what
8446                  * ipif_up() would have done, because we got here by way of
8447                  * ill_dl_up(), which stopped ipif_up()'s processing.
8448                  */
8449                 if (ill->ill_isv6) {
8450                         /*
8451                          * v6 interfaces.
8452                          * Unlike ARP which has to do another bind
8453                          * and attach, once we get here we are
8454                          * done with NDP
8455                          */
8456                         (void) ipif_resolver_up(ipif, Res_act_initial);
8457                         if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8458                                 err = ipif_up_done_v6(ipif);
8459                 } else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8460                         /*
8461                          * ARP and other v4 external resolvers.
8462                          * Leave the pending mblk intact so that
8463                          * the ioctl completes in ip_rput().
8464                          */
8465                         if (connp != NULL)
8466                                 mutex_enter(&connp->conn_lock);
8467                         mutex_enter(&ill->ill_lock);
8468                         success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8469                         mutex_exit(&ill->ill_lock);
8470                         if (connp != NULL)
8471                                 mutex_exit(&connp->conn_lock);
8472                         if (success) {
8473                                 err = ipif_resolver_up(ipif, Res_act_initial);
8474                                 if (err == EINPROGRESS) {
8475                                         freemsg(mp);
8476                                         return;
8477                                 }
8478                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8479                         } else {
8480                                 /* The conn has started closing */
8481                                 err = EINTR;
8482                         }
8483                 } else {
8484                         /*
8485                          * This one is complete. Reply to pending ioctl.
8486                          */
8487                         (void) ipif_resolver_up(ipif, Res_act_initial);
8488                         err = ipif_up_done(ipif);
8489                 }
8490 
8491                 if ((err == 0) && (ill->ill_up_ipifs)) {
8492                         err = ill_up_ipifs(ill, q, mp1);
8493                         if (err == EINPROGRESS) {
8494                                 freemsg(mp);
8495                                 return;
8496                         }
8497                 }
8498 
8499                 /*
8500                  * If we have a moved ipif to bring up, and everything has
8501                  * succeeded to this point, bring it up on the IPMP ill.
8502                  * Otherwise, leave it down -- the admin can try to bring it
8503                  * up by hand if need be.
8504                  */
8505                 if (ill->ill_move_ipif != NULL) {
8506                         if (err != 0) {
8507                                 ill->ill_move_ipif = NULL;
8508                         } else {
8509                                 ipif = ill->ill_move_ipif;
8510                                 ill->ill_move_ipif = NULL;
8511                                 err = ipif_up(ipif, q, mp1);
8512                                 if (err == EINPROGRESS) {
8513                                         freemsg(mp);
8514                                         return;
8515                                 }
8516                         }
8517                 }
8518                 break;
8519 
8520         case DL_NOTIFY_IND: {
8521                 dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8522                 uint_t orig_mtu, orig_mc_mtu;
8523 
8524                 switch (notify->dl_notification) {
8525                 case DL_NOTE_PHYS_ADDR:
8526                         err = ill_set_phys_addr(ill, mp);
8527                         break;
8528 
8529                 case DL_NOTE_REPLUMB:
8530                         /*
8531                          * Directly return after calling ill_replumb().
8532                          * Note that we should not free mp as it is reused
8533                          * in the ill_replumb() function.
8534                          */
8535                         err = ill_replumb(ill, mp);
8536                         return;
8537 
8538                 case DL_NOTE_FASTPATH_FLUSH:
8539                         nce_flush(ill, B_FALSE);
8540                         break;
8541 
8542                 case DL_NOTE_SDU_SIZE:
8543                 case DL_NOTE_SDU_SIZE2:
8544                         /*
8545                          * The dce and fragmentation code can cope with
8546                          * this changing while packets are being sent.
8547                          * When packets are sent ip_output will discover
8548                          * a change.
8549                          *
8550                          * Change the MTU size of the interface.
8551                          */
8552                         mutex_enter(&ill->ill_lock);
8553                         orig_mtu = ill->ill_mtu;
8554                         orig_mc_mtu = ill->ill_mc_mtu;
8555                         switch (notify->dl_notification) {
8556                         case DL_NOTE_SDU_SIZE:
8557                                 ill->ill_current_frag =
8558                                     (uint_t)notify->dl_data;
8559                                 ill->ill_mc_mtu = (uint_t)notify->dl_data;
8560                                 break;
8561                         case DL_NOTE_SDU_SIZE2:
8562                                 ill->ill_current_frag =
8563                                     (uint_t)notify->dl_data1;
8564                                 ill->ill_mc_mtu = (uint_t)notify->dl_data2;
8565                                 break;
8566                         }
8567                         if (ill->ill_current_frag > ill->ill_max_frag)
8568                                 ill->ill_max_frag = ill->ill_current_frag;
8569 
8570                         if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8571                                 ill->ill_mtu = ill->ill_current_frag;
8572 
8573                                 /*
8574                                  * If ill_user_mtu was set (via
8575                                  * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8576                                  */
8577                                 if (ill->ill_user_mtu != 0 &&
8578                                     ill->ill_user_mtu < ill->ill_mtu)
8579                                         ill->ill_mtu = ill->ill_user_mtu;
8580 
8581                                 if (ill->ill_user_mtu != 0 &&
8582                                     ill->ill_user_mtu < ill->ill_mc_mtu)
8583                                         ill->ill_mc_mtu = ill->ill_user_mtu;
8584 
8585                                 if (ill->ill_isv6) {
8586                                         if (ill->ill_mtu < IPV6_MIN_MTU)
8587                                                 ill->ill_mtu = IPV6_MIN_MTU;
8588                                         if (ill->ill_mc_mtu < IPV6_MIN_MTU)
8589                                                 ill->ill_mc_mtu = IPV6_MIN_MTU;
8590                                 } else {
8591                                         if (ill->ill_mtu < IP_MIN_MTU)
8592                                                 ill->ill_mtu = IP_MIN_MTU;
8593                                         if (ill->ill_mc_mtu < IP_MIN_MTU)
8594                                                 ill->ill_mc_mtu = IP_MIN_MTU;
8595                                 }
8596                         } else if (ill->ill_mc_mtu > ill->ill_mtu) {
8597                                 ill->ill_mc_mtu = ill->ill_mtu;
8598                         }
8599 
8600                         mutex_exit(&ill->ill_lock);
8601                         /*
8602                          * Make sure all dce_generation checks find out
8603                          * that ill_mtu/ill_mc_mtu has changed.
8604                          */
8605                         if (orig_mtu != ill->ill_mtu ||
8606                             orig_mc_mtu != ill->ill_mc_mtu) {
8607                                 dce_increment_all_generations(ill->ill_isv6,
8608                                     ill->ill_ipst);
8609                         }
8610 
8611                         /*
8612                          * Refresh IPMP meta-interface MTU if necessary.
8613                          */
8614                         if (IS_UNDER_IPMP(ill))
8615                                 ipmp_illgrp_refresh_mtu(ill->ill_grp);
8616                         break;
8617 
8618                 case DL_NOTE_LINK_UP:
8619                 case DL_NOTE_LINK_DOWN: {
8620                         /*
8621                          * We are writer. ill / phyint / ipsq assocs stable.
8622                          * The RUNNING flag reflects the state of the link.
8623                          */
8624                         phyint_t *phyint = ill->ill_phyint;
8625                         uint64_t new_phyint_flags;
8626                         boolean_t changed = B_FALSE;
8627                         boolean_t went_up;
8628 
8629                         went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8630                         mutex_enter(&phyint->phyint_lock);
8631 
8632                         new_phyint_flags = went_up ?
8633                             phyint->phyint_flags | PHYI_RUNNING :
8634                             phyint->phyint_flags & ~PHYI_RUNNING;
8635 
8636                         if (IS_IPMP(ill)) {
8637                                 new_phyint_flags = went_up ?
8638                                     new_phyint_flags & ~PHYI_FAILED :
8639                                     new_phyint_flags | PHYI_FAILED;
8640                         }
8641 
8642                         if (new_phyint_flags != phyint->phyint_flags) {
8643                                 phyint->phyint_flags = new_phyint_flags;
8644                                 changed = B_TRUE;
8645                         }
8646                         mutex_exit(&phyint->phyint_lock);
8647                         /*
8648                          * ill_restart_dad handles the DAD restart and routing
8649                          * socket notification logic.
8650                          */
8651                         if (changed) {
8652                                 ill_restart_dad(phyint->phyint_illv4, went_up);
8653                                 ill_restart_dad(phyint->phyint_illv6, went_up);
8654                         }
8655                         break;
8656                 }
8657                 case DL_NOTE_PROMISC_ON_PHYS: {
8658                         phyint_t *phyint = ill->ill_phyint;
8659 
8660                         mutex_enter(&phyint->phyint_lock);
8661                         phyint->phyint_flags |= PHYI_PROMISC;
8662                         mutex_exit(&phyint->phyint_lock);
8663                         break;
8664                 }
8665                 case DL_NOTE_PROMISC_OFF_PHYS: {
8666                         phyint_t *phyint = ill->ill_phyint;
8667 
8668                         mutex_enter(&phyint->phyint_lock);
8669                         phyint->phyint_flags &= ~PHYI_PROMISC;
8670                         mutex_exit(&phyint->phyint_lock);
8671                         break;
8672                 }
8673                 case DL_NOTE_CAPAB_RENEG:
8674                         /*
8675                          * Something changed on the driver side.
8676                          * It wants us to renegotiate the capabilities
8677                          * on this ill. One possible cause is the aggregation
8678                          * interface under us where a port got added or
8679                          * went away.
8680                          *
8681                          * If the capability negotiation is already done
8682                          * or is in progress, reset the capabilities and
8683                          * mark the ill's ill_capab_reneg to be B_TRUE,
8684                          * so that when the ack comes back, we can start
8685                          * the renegotiation process.
8686                          *
8687                          * Note that if ill_capab_reneg is already B_TRUE
8688                          * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8689                          * the capability resetting request has been sent
8690                          * and the renegotiation has not been started yet;
8691                          * nothing needs to be done in this case.
8692                          */
8693                         ipsq_current_start(ipsq, ill->ill_ipif, 0);
8694                         ill_capability_reset(ill, B_TRUE);
8695                         ipsq_current_finish(ipsq);
8696                         break;
8697 
8698                 case DL_NOTE_ALLOWED_IPS:
8699                         ill_set_allowed_ips(ill, mp);
8700                         break;
8701                 default:
8702                         ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8703                             "type 0x%x for DL_NOTIFY_IND\n",
8704                             notify->dl_notification));
8705                         break;
8706                 }
8707 
8708                 /*
8709                  * As this is an asynchronous operation, we
8710                  * should not call ill_dlpi_done
8711                  */
8712                 break;
8713         }
8714         case DL_NOTIFY_ACK: {
8715                 dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8716 
8717                 if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8718                         ill->ill_note_link = 1;
8719                 ill_dlpi_done(ill, DL_NOTIFY_REQ);
8720                 break;
8721         }
8722         case DL_PHYS_ADDR_ACK: {
8723                 /*
8724                  * As part of plumbing the interface via SIOCSLIFNAME,
8725                  * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8726                  * whose answers we receive here.  As each answer is received,
8727                  * we call ill_dlpi_done() to dispatch the next request as
8728                  * we're processing the current one.  Once all answers have
8729                  * been received, we use ipsq_pending_mp_get() to dequeue the
8730                  * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8731                  * is invoked from an ill queue, conn_oper_pending_ill is not
8732                  * available, but we know the ioctl is pending on ill_wq.)
8733                  */
8734                 uint_t  paddrlen, paddroff;
8735                 uint8_t *addr;
8736 
8737                 paddrreq = ill->ill_phys_addr_pend;
8738                 paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8739                 paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8740                 addr = mp->b_rptr + paddroff;
8741 
8742                 ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8743                 if (paddrreq == DL_IPV6_TOKEN) {
8744                         /*
8745                          * bcopy to low-order bits of ill_token
8746                          *
8747                          * XXX Temporary hack - currently, all known tokens
8748                          * are 64 bits, so I'll cheat for the moment.
8749                          */
8750                         bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8751                         ill->ill_token_length = paddrlen;
8752                         break;
8753                 } else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8754                         ASSERT(ill->ill_nd_lla_mp == NULL);
8755                         ill_set_ndmp(ill, mp, paddroff, paddrlen);
8756                         mp = NULL;
8757                         break;
8758                 } else if (paddrreq == DL_CURR_DEST_ADDR) {
8759                         ASSERT(ill->ill_dest_addr_mp == NULL);
8760                         ill->ill_dest_addr_mp = mp;
8761                         ill->ill_dest_addr = addr;
8762                         mp = NULL;
8763                         if (ill->ill_isv6) {
8764                                 ill_setdesttoken(ill);
8765                                 ipif_setdestlinklocal(ill->ill_ipif);
8766                         }
8767                         break;
8768                 }
8769 
8770                 ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8771                 ASSERT(ill->ill_phys_addr_mp == NULL);
8772                 if (!ill->ill_ifname_pending)
8773                         break;
8774                 ill->ill_ifname_pending = 0;
8775                 if (!ioctl_aborted)
8776                         mp1 = ipsq_pending_mp_get(ipsq, &connp);
8777                 if (mp1 != NULL) {
8778                         ASSERT(connp == NULL);
8779                         q = ill->ill_wq;
8780                 }
8781                 /*
8782                  * If any error acks received during the plumbing sequence,
8783                  * ill_ifname_pending_err will be set. Break out and send up
8784                  * the error to the pending ioctl.
8785                  */
8786                 if (ill->ill_ifname_pending_err != 0) {
8787                         err = ill->ill_ifname_pending_err;
8788                         ill->ill_ifname_pending_err = 0;
8789                         break;
8790                 }
8791 
8792                 ill->ill_phys_addr_mp = mp;
8793                 ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8794                 mp = NULL;
8795 
8796                 /*
8797                  * If paddrlen or ill_phys_addr_length is zero, the DLPI
8798                  * provider doesn't support physical addresses.  We check both
8799                  * paddrlen and ill_phys_addr_length because sppp (PPP) does
8800                  * not have physical addresses, but historically adversises a
8801                  * physical address length of 0 in its DL_INFO_ACK, but 6 in
8802                  * its DL_PHYS_ADDR_ACK.
8803                  */
8804                 if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8805                         ill->ill_phys_addr = NULL;
8806                 } else if (paddrlen != ill->ill_phys_addr_length) {
8807                         ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8808                             paddrlen, ill->ill_phys_addr_length));
8809                         err = EINVAL;
8810                         break;
8811                 }
8812 
8813                 if (ill->ill_nd_lla_mp == NULL) {
8814                         if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8815                                 err = ENOMEM;
8816                                 break;
8817                         }
8818                         ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8819                 }
8820 
8821                 if (ill->ill_isv6) {
8822                         ill_setdefaulttoken(ill);
8823                         ipif_setlinklocal(ill->ill_ipif);
8824                 }
8825                 break;
8826         }
8827         case DL_OK_ACK:
8828                 ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8829                     dl_primstr((int)dloa->dl_correct_primitive),
8830                     dloa->dl_correct_primitive));
8831                 DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8832                     char *, dl_primstr(dloa->dl_correct_primitive),
8833                     ill_t *, ill);
8834 
8835                 switch (dloa->dl_correct_primitive) {
8836                 case DL_ENABMULTI_REQ:
8837                 case DL_DISABMULTI_REQ:
8838                         ill_dlpi_done(ill, dloa->dl_correct_primitive);
8839                         break;
8840                 case DL_PROMISCON_REQ:
8841                 case DL_PROMISCOFF_REQ:
8842                 case DL_UNBIND_REQ:
8843                 case DL_ATTACH_REQ:
8844                         ill_dlpi_done(ill, dloa->dl_correct_primitive);
8845                         break;
8846                 }
8847                 break;
8848         default:
8849                 break;
8850         }
8851 
8852         freemsg(mp);
8853         if (mp1 == NULL)
8854                 return;
8855 
8856         /*
8857          * The operation must complete without EINPROGRESS since
8858          * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8859          * the operation will be stuck forever inside the IPSQ.
8860          */
8861         ASSERT(err != EINPROGRESS);
8862 
8863         DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8864             int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8865             ipif_t *, NULL);
8866 
8867         switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8868         case 0:
8869                 ipsq_current_finish(ipsq);
8870                 break;
8871 
8872         case SIOCSLIFNAME:
8873         case IF_UNITSEL: {
8874                 ill_t *ill_other = ILL_OTHER(ill);
8875 
8876                 /*
8877                  * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8878                  * ill has a peer which is in an IPMP group, then place ill
8879                  * into the same group.  One catch: although ifconfig plumbs
8880                  * the appropriate IPMP meta-interface prior to plumbing this
8881                  * ill, it is possible for multiple ifconfig applications to
8882                  * race (or for another application to adjust plumbing), in
8883                  * which case the IPMP meta-interface we need will be missing.
8884                  * If so, kick the phyint out of the group.
8885                  */
8886                 if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8887                         ipmp_grp_t      *grp = ill->ill_phyint->phyint_grp;
8888                         ipmp_illgrp_t   *illg;
8889 
8890                         illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8891                         if (illg == NULL)
8892                                 ipmp_phyint_leave_grp(ill->ill_phyint);
8893                         else
8894                                 ipmp_ill_join_illgrp(ill, illg);
8895                 }
8896 
8897                 if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8898                         ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8899                 else
8900                         ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8901                 break;
8902         }
8903         case SIOCLIFADDIF:
8904                 ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8905                 break;
8906 
8907         default:
8908                 ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8909                 break;
8910         }
8911 }
8912 
8913 /*
8914  * ip_rput_other is called by ip_rput to handle messages modifying the global
8915  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8916  */
8917 /* ARGSUSED */
8918 void
8919 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8920 {
8921         ill_t           *ill = q->q_ptr;
8922         struct iocblk   *iocp;
8923 
8924         ip1dbg(("ip_rput_other "));
8925         if (ipsq != NULL) {
8926                 ASSERT(IAM_WRITER_IPSQ(ipsq));
8927                 ASSERT(ipsq->ipsq_xop ==
8928                     ill->ill_phyint->phyint_ipsq->ipsq_xop);
8929         }
8930 
8931         switch (mp->b_datap->db_type) {
8932         case M_ERROR:
8933         case M_HANGUP:
8934                 /*
8935                  * The device has a problem.  We force the ILL down.  It can
8936                  * be brought up again manually using SIOCSIFFLAGS (via
8937                  * ifconfig or equivalent).
8938                  */
8939                 ASSERT(ipsq != NULL);
8940                 if (mp->b_rptr < mp->b_wptr)
8941                         ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8942                 if (ill->ill_error == 0)
8943                         ill->ill_error = ENXIO;
8944                 if (!ill_down_start(q, mp))
8945                         return;
8946                 ipif_all_down_tail(ipsq, q, mp, NULL);
8947                 break;
8948         case M_IOCNAK: {
8949                 iocp = (struct iocblk *)mp->b_rptr;
8950 
8951                 ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8952                 /*
8953                  * If this was the first attempt, turn off the fastpath
8954                  * probing.
8955                  */
8956                 mutex_enter(&ill->ill_lock);
8957                 if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8958                         ill->ill_dlpi_fastpath_state = IDS_FAILED;
8959                         mutex_exit(&ill->ill_lock);
8960                         /*
8961                          * don't flush the nce_t entries: we use them
8962                          * as an index to the ncec itself.
8963                          */
8964                         ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8965                             ill->ill_name));
8966                 } else {
8967                         mutex_exit(&ill->ill_lock);
8968                 }
8969                 freemsg(mp);
8970                 break;
8971         }
8972         default:
8973                 ASSERT(0);
8974                 break;
8975         }
8976 }
8977 
8978 /*
8979  * Update any source route, record route or timestamp options
8980  * When it fails it has consumed the message and BUMPed the MIB.
8981  */
8982 boolean_t
8983 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8984     ip_recv_attr_t *ira)
8985 {
8986         ipoptp_t        opts;
8987         uchar_t         *opt;
8988         uint8_t         optval;
8989         uint8_t         optlen;
8990         ipaddr_t        dst;
8991         ipaddr_t        ifaddr;
8992         uint32_t        ts;
8993         timestruc_t     now;
8994         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
8995 
8996         ip2dbg(("ip_forward_options\n"));
8997         dst = ipha->ipha_dst;
8998         for (optval = ipoptp_first(&opts, ipha);
8999             optval != IPOPT_EOL;
9000             optval = ipoptp_next(&opts)) {
9001                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9002                 opt = opts.ipoptp_cur;
9003                 optlen = opts.ipoptp_len;
9004                 ip2dbg(("ip_forward_options: opt %d, len %d\n",
9005                     optval, opts.ipoptp_len));
9006                 switch (optval) {
9007                         uint32_t off;
9008                 case IPOPT_SSRR:
9009                 case IPOPT_LSRR:
9010                         /* Check if adminstratively disabled */
9011                         if (!ipst->ips_ip_forward_src_routed) {
9012                                 BUMP_MIB(dst_ill->ill_ip_mib,
9013                                     ipIfStatsForwProhibits);
9014                                 ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9015                                     mp, dst_ill);
9016                                 icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9017                                     ira);
9018                                 return (B_FALSE);
9019                         }
9020                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9021                                 /*
9022                                  * Must be partial since ip_input_options
9023                                  * checked for strict.
9024                                  */
9025                                 break;
9026                         }
9027                         off = opt[IPOPT_OFFSET];
9028                         off--;
9029                 redo_srr:
9030                         if (optlen < IP_ADDR_LEN ||
9031                             off > optlen - IP_ADDR_LEN) {
9032                                 /* End of source route */
9033                                 ip1dbg((
9034                                     "ip_forward_options: end of SR\n"));
9035                                 break;
9036                         }
9037                         /* Pick a reasonable address on the outbound if */
9038                         ASSERT(dst_ill != NULL);
9039                         if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9040                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9041                             NULL) != 0) {
9042                                 /* No source! Shouldn't happen */
9043                                 ifaddr = INADDR_ANY;
9044                         }
9045                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9046                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9047                         ip1dbg(("ip_forward_options: next hop 0x%x\n",
9048                             ntohl(dst)));
9049 
9050                         /*
9051                          * Check if our address is present more than
9052                          * once as consecutive hops in source route.
9053                          */
9054                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9055                                 off += IP_ADDR_LEN;
9056                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9057                                 goto redo_srr;
9058                         }
9059                         ipha->ipha_dst = dst;
9060                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9061                         break;
9062                 case IPOPT_RR:
9063                         off = opt[IPOPT_OFFSET];
9064                         off--;
9065                         if (optlen < IP_ADDR_LEN ||
9066                             off > optlen - IP_ADDR_LEN) {
9067                                 /* No more room - ignore */
9068                                 ip1dbg((
9069                                     "ip_forward_options: end of RR\n"));
9070                                 break;
9071                         }
9072                         /* Pick a reasonable address on the outbound if */
9073                         ASSERT(dst_ill != NULL);
9074                         if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9075                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9076                             NULL) != 0) {
9077                                 /* No source! Shouldn't happen */
9078                                 ifaddr = INADDR_ANY;
9079                         }
9080                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9081                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9082                         break;
9083                 case IPOPT_TS:
9084                         /* Insert timestamp if there is room */
9085                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9086                         case IPOPT_TS_TSONLY:
9087                                 off = IPOPT_TS_TIMELEN;
9088                                 break;
9089                         case IPOPT_TS_PRESPEC:
9090                         case IPOPT_TS_PRESPEC_RFC791:
9091                                 /* Verify that the address matched */
9092                                 off = opt[IPOPT_OFFSET] - 1;
9093                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9094                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9095                                         /* Not for us */
9096                                         break;
9097                                 }
9098                                 /* FALLTHRU */
9099                         case IPOPT_TS_TSANDADDR:
9100                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9101                                 break;
9102                         default:
9103                                 /*
9104                                  * ip_*put_options should have already
9105                                  * dropped this packet.
9106                                  */
9107                                 cmn_err(CE_PANIC, "ip_forward_options: "
9108                                     "unknown IT - bug in ip_input_options?\n");
9109                                 return (B_TRUE);        /* Keep "lint" happy */
9110                         }
9111                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9112                                 /* Increase overflow counter */
9113                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9114                                 opt[IPOPT_POS_OV_FLG] =
9115                                     (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9116                                     (off << 4));
9117                                 break;
9118                         }
9119                         off = opt[IPOPT_OFFSET] - 1;
9120                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9121                         case IPOPT_TS_PRESPEC:
9122                         case IPOPT_TS_PRESPEC_RFC791:
9123                         case IPOPT_TS_TSANDADDR:
9124                                 /* Pick a reasonable addr on the outbound if */
9125                                 ASSERT(dst_ill != NULL);
9126                                 if (ip_select_source_v4(dst_ill, INADDR_ANY,
9127                                     dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9128                                     NULL, NULL) != 0) {
9129                                         /* No source! Shouldn't happen */
9130                                         ifaddr = INADDR_ANY;
9131                                 }
9132                                 bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9133                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9134                                 /* FALLTHRU */
9135                         case IPOPT_TS_TSONLY:
9136                                 off = opt[IPOPT_OFFSET] - 1;
9137                                 /* Compute # of milliseconds since midnight */
9138                                 gethrestime(&now);
9139                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9140                                     NSEC2MSEC(now.tv_nsec);
9141                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9142                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9143                                 break;
9144                         }
9145                         break;
9146                 }
9147         }
9148         return (B_TRUE);
9149 }
9150 
9151 /*
9152  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9153  * returns 'true' if there are still fragments left on the queue, in
9154  * which case we restart the timer.
9155  */
9156 void
9157 ill_frag_timer(void *arg)
9158 {
9159         ill_t   *ill = (ill_t *)arg;
9160         boolean_t frag_pending;
9161         ip_stack_t *ipst = ill->ill_ipst;
9162         time_t  timeout;
9163 
9164         mutex_enter(&ill->ill_lock);
9165         ASSERT(!ill->ill_fragtimer_executing);
9166         if (ill->ill_state_flags & ILL_CONDEMNED) {
9167                 ill->ill_frag_timer_id = 0;
9168                 mutex_exit(&ill->ill_lock);
9169                 return;
9170         }
9171         ill->ill_fragtimer_executing = 1;
9172         mutex_exit(&ill->ill_lock);
9173 
9174         timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9175             ipst->ips_ip_reassembly_timeout);
9176 
9177         frag_pending = ill_frag_timeout(ill, timeout);
9178 
9179         /*
9180          * Restart the timer, if we have fragments pending or if someone
9181          * wanted us to be scheduled again.
9182          */
9183         mutex_enter(&ill->ill_lock);
9184         ill->ill_fragtimer_executing = 0;
9185         ill->ill_frag_timer_id = 0;
9186         if (frag_pending || ill->ill_fragtimer_needrestart)
9187                 ill_frag_timer_start(ill);
9188         mutex_exit(&ill->ill_lock);
9189 }
9190 
9191 void
9192 ill_frag_timer_start(ill_t *ill)
9193 {
9194         ip_stack_t *ipst = ill->ill_ipst;
9195         clock_t timeo_ms;
9196 
9197         ASSERT(MUTEX_HELD(&ill->ill_lock));
9198 
9199         /* If the ill is closing or opening don't proceed */
9200         if (ill->ill_state_flags & ILL_CONDEMNED)
9201                 return;
9202 
9203         if (ill->ill_fragtimer_executing) {
9204                 /*
9205                  * ill_frag_timer is currently executing. Just record the
9206                  * the fact that we want the timer to be restarted.
9207                  * ill_frag_timer will post a timeout before it returns,
9208                  * ensuring it will be called again.
9209                  */
9210                 ill->ill_fragtimer_needrestart = 1;
9211                 return;
9212         }
9213 
9214         if (ill->ill_frag_timer_id == 0) {
9215                 timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9216                     ipst->ips_ip_reassembly_timeout) * SECONDS;
9217 
9218                 /*
9219                  * The timer is neither running nor is the timeout handler
9220                  * executing. Post a timeout so that ill_frag_timer will be
9221                  * called
9222                  */
9223                 ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9224                     MSEC_TO_TICK(timeo_ms >> 1));
9225                 ill->ill_fragtimer_needrestart = 0;
9226         }
9227 }
9228 
9229 /*
9230  * Update any source route, record route or timestamp options.
9231  * Check that we are at end of strict source route.
9232  * The options have already been checked for sanity in ip_input_options().
9233  */
9234 boolean_t
9235 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9236 {
9237         ipoptp_t        opts;
9238         uchar_t         *opt;
9239         uint8_t         optval;
9240         uint8_t         optlen;
9241         ipaddr_t        dst;
9242         ipaddr_t        ifaddr;
9243         uint32_t        ts;
9244         timestruc_t     now;
9245         ill_t           *ill = ira->ira_ill;
9246         ip_stack_t      *ipst = ill->ill_ipst;
9247 
9248         ip2dbg(("ip_input_local_options\n"));
9249 
9250         for (optval = ipoptp_first(&opts, ipha);
9251             optval != IPOPT_EOL;
9252             optval = ipoptp_next(&opts)) {
9253                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9254                 opt = opts.ipoptp_cur;
9255                 optlen = opts.ipoptp_len;
9256                 ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9257                     optval, optlen));
9258                 switch (optval) {
9259                         uint32_t off;
9260                 case IPOPT_SSRR:
9261                 case IPOPT_LSRR:
9262                         off = opt[IPOPT_OFFSET];
9263                         off--;
9264                         if (optlen < IP_ADDR_LEN ||
9265                             off > optlen - IP_ADDR_LEN) {
9266                                 /* End of source route */
9267                                 ip1dbg(("ip_input_local_options: end of SR\n"));
9268                                 break;
9269                         }
9270                         /*
9271                          * This will only happen if two consecutive entries
9272                          * in the source route contains our address or if
9273                          * it is a packet with a loose source route which
9274                          * reaches us before consuming the whole source route
9275                          */
9276                         ip1dbg(("ip_input_local_options: not end of SR\n"));
9277                         if (optval == IPOPT_SSRR) {
9278                                 goto bad_src_route;
9279                         }
9280                         /*
9281                          * Hack: instead of dropping the packet truncate the
9282                          * source route to what has been used by filling the
9283                          * rest with IPOPT_NOP.
9284                          */
9285                         opt[IPOPT_OLEN] = (uint8_t)off;
9286                         while (off < optlen) {
9287                                 opt[off++] = IPOPT_NOP;
9288                         }
9289                         break;
9290                 case IPOPT_RR:
9291                         off = opt[IPOPT_OFFSET];
9292                         off--;
9293                         if (optlen < IP_ADDR_LEN ||
9294                             off > optlen - IP_ADDR_LEN) {
9295                                 /* No more room - ignore */
9296                                 ip1dbg((
9297                                     "ip_input_local_options: end of RR\n"));
9298                                 break;
9299                         }
9300                         /* Pick a reasonable address on the outbound if */
9301                         if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9302                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9303                             NULL) != 0) {
9304                                 /* No source! Shouldn't happen */
9305                                 ifaddr = INADDR_ANY;
9306                         }
9307                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9308                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9309                         break;
9310                 case IPOPT_TS:
9311                         /* Insert timestamp if there is romm */
9312                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9313                         case IPOPT_TS_TSONLY:
9314                                 off = IPOPT_TS_TIMELEN;
9315                                 break;
9316                         case IPOPT_TS_PRESPEC:
9317                         case IPOPT_TS_PRESPEC_RFC791:
9318                                 /* Verify that the address matched */
9319                                 off = opt[IPOPT_OFFSET] - 1;
9320                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9321                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9322                                         /* Not for us */
9323                                         break;
9324                                 }
9325                                 /* FALLTHRU */
9326                         case IPOPT_TS_TSANDADDR:
9327                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9328                                 break;
9329                         default:
9330                                 /*
9331                                  * ip_*put_options should have already
9332                                  * dropped this packet.
9333                                  */
9334                                 cmn_err(CE_PANIC, "ip_input_local_options: "
9335                                     "unknown IT - bug in ip_input_options?\n");
9336                                 return (B_TRUE);        /* Keep "lint" happy */
9337                         }
9338                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9339                                 /* Increase overflow counter */
9340                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9341                                 opt[IPOPT_POS_OV_FLG] =
9342                                     (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9343                                     (off << 4));
9344                                 break;
9345                         }
9346                         off = opt[IPOPT_OFFSET] - 1;
9347                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9348                         case IPOPT_TS_PRESPEC:
9349                         case IPOPT_TS_PRESPEC_RFC791:
9350                         case IPOPT_TS_TSANDADDR:
9351                                 /* Pick a reasonable addr on the outbound if */
9352                                 if (ip_select_source_v4(ill, INADDR_ANY,
9353                                     ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9354                                     &ifaddr, NULL, NULL) != 0) {
9355                                         /* No source! Shouldn't happen */
9356                                         ifaddr = INADDR_ANY;
9357                                 }
9358                                 bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9359                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9360                                 /* FALLTHRU */
9361                         case IPOPT_TS_TSONLY:
9362                                 off = opt[IPOPT_OFFSET] - 1;
9363                                 /* Compute # of milliseconds since midnight */
9364                                 gethrestime(&now);
9365                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9366                                     NSEC2MSEC(now.tv_nsec);
9367                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9368                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9369                                 break;
9370                         }
9371                         break;
9372                 }
9373         }
9374         return (B_TRUE);
9375 
9376 bad_src_route:
9377         /* make sure we clear any indication of a hardware checksum */
9378         DB_CKSUMFLAGS(mp) = 0;
9379         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9380         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9381         return (B_FALSE);
9382 
9383 }
9384 
9385 /*
9386  * Process IP options in an inbound packet.  Always returns the nexthop.
9387  * Normally this is the passed in nexthop, but if there is an option
9388  * that effects the nexthop (such as a source route) that will be returned.
9389  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9390  * and mp freed.
9391  */
9392 ipaddr_t
9393 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9394     ip_recv_attr_t *ira, int *errorp)
9395 {
9396         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
9397         ipoptp_t        opts;
9398         uchar_t         *opt;
9399         uint8_t         optval;
9400         uint8_t         optlen;
9401         intptr_t        code = 0;
9402         ire_t           *ire;
9403 
9404         ip2dbg(("ip_input_options\n"));
9405         *errorp = 0;
9406         for (optval = ipoptp_first(&opts, ipha);
9407             optval != IPOPT_EOL;
9408             optval = ipoptp_next(&opts)) {
9409                 opt = opts.ipoptp_cur;
9410                 optlen = opts.ipoptp_len;
9411                 ip2dbg(("ip_input_options: opt %d, len %d\n",
9412                     optval, optlen));
9413                 /*
9414                  * Note: we need to verify the checksum before we
9415                  * modify anything thus this routine only extracts the next
9416                  * hop dst from any source route.
9417                  */
9418                 switch (optval) {
9419                         uint32_t off;
9420                 case IPOPT_SSRR:
9421                 case IPOPT_LSRR:
9422                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9423                                 if (optval == IPOPT_SSRR) {
9424                                         ip1dbg(("ip_input_options: not next"
9425                                             " strict source route 0x%x\n",
9426                                             ntohl(dst)));
9427                                         code = (char *)&ipha->ipha_dst -
9428                                             (char *)ipha;
9429                                         goto param_prob; /* RouterReq's */
9430                                 }
9431                                 ip2dbg(("ip_input_options: "
9432                                     "not next source route 0x%x\n",
9433                                     ntohl(dst)));
9434                                 break;
9435                         }
9436 
9437                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9438                                 ip1dbg((
9439                                     "ip_input_options: bad option offset\n"));
9440                                 code = (char *)&opt[IPOPT_OLEN] -
9441                                     (char *)ipha;
9442                                 goto param_prob;
9443                         }
9444                         off = opt[IPOPT_OFFSET];
9445                         off--;
9446                 redo_srr:
9447                         if (optlen < IP_ADDR_LEN ||
9448                             off > optlen - IP_ADDR_LEN) {
9449                                 /* End of source route */
9450                                 ip1dbg(("ip_input_options: end of SR\n"));
9451                                 break;
9452                         }
9453                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9454                         ip1dbg(("ip_input_options: next hop 0x%x\n",
9455                             ntohl(dst)));
9456 
9457                         /*
9458                          * Check if our address is present more than
9459                          * once as consecutive hops in source route.
9460                          * XXX verify per-interface ip_forwarding
9461                          * for source route?
9462                          */
9463                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9464                                 off += IP_ADDR_LEN;
9465                                 goto redo_srr;
9466                         }
9467 
9468                         if (dst == htonl(INADDR_LOOPBACK)) {
9469                                 ip1dbg(("ip_input_options: loopback addr in "
9470                                     "source route!\n"));
9471                                 goto bad_src_route;
9472                         }
9473                         /*
9474                          * For strict: verify that dst is directly
9475                          * reachable.
9476                          */
9477                         if (optval == IPOPT_SSRR) {
9478                                 ire = ire_ftable_lookup_v4(dst, 0, 0,
9479                                     IRE_INTERFACE, NULL, ALL_ZONES,
9480                                     ira->ira_tsl,
9481                                     MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9482                                     NULL);
9483                                 if (ire == NULL) {
9484                                         ip1dbg(("ip_input_options: SSRR not "
9485                                             "directly reachable: 0x%x\n",
9486                                             ntohl(dst)));
9487                                         goto bad_src_route;
9488                                 }
9489                                 ire_refrele(ire);
9490                         }
9491                         /*
9492                          * Defer update of the offset and the record route
9493                          * until the packet is forwarded.
9494                          */
9495                         break;
9496                 case IPOPT_RR:
9497                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9498                                 ip1dbg((
9499                                     "ip_input_options: bad option offset\n"));
9500                                 code = (char *)&opt[IPOPT_OLEN] -
9501                                     (char *)ipha;
9502                                 goto param_prob;
9503                         }
9504                         break;
9505                 case IPOPT_TS:
9506                         /*
9507                          * Verify that length >= 5 and that there is either
9508                          * room for another timestamp or that the overflow
9509                          * counter is not maxed out.
9510                          */
9511                         code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9512                         if (optlen < IPOPT_MINLEN_IT) {
9513                                 goto param_prob;
9514                         }
9515                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9516                                 ip1dbg((
9517                                     "ip_input_options: bad option offset\n"));
9518                                 code = (char *)&opt[IPOPT_OFFSET] -
9519                                     (char *)ipha;
9520                                 goto param_prob;
9521                         }
9522                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9523                         case IPOPT_TS_TSONLY:
9524                                 off = IPOPT_TS_TIMELEN;
9525                                 break;
9526                         case IPOPT_TS_TSANDADDR:
9527                         case IPOPT_TS_PRESPEC:
9528                         case IPOPT_TS_PRESPEC_RFC791:
9529                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9530                                 break;
9531                         default:
9532                                 code = (char *)&opt[IPOPT_POS_OV_FLG] -
9533                                     (char *)ipha;
9534                                 goto param_prob;
9535                         }
9536                         if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9537                             (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9538                                 /*
9539                                  * No room and the overflow counter is 15
9540                                  * already.
9541                                  */
9542                                 goto param_prob;
9543                         }
9544                         break;
9545                 }
9546         }
9547 
9548         if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9549                 return (dst);
9550         }
9551 
9552         ip1dbg(("ip_input_options: error processing IP options."));
9553         code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9554 
9555 param_prob:
9556         /* make sure we clear any indication of a hardware checksum */
9557         DB_CKSUMFLAGS(mp) = 0;
9558         ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9559         icmp_param_problem(mp, (uint8_t)code, ira);
9560         *errorp = -1;
9561         return (dst);
9562 
9563 bad_src_route:
9564         /* make sure we clear any indication of a hardware checksum */
9565         DB_CKSUMFLAGS(mp) = 0;
9566         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9567         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9568         *errorp = -1;
9569         return (dst);
9570 }
9571 
9572 /*
9573  * IP & ICMP info in >=14 msg's ...
9574  *  - ip fixed part (mib2_ip_t)
9575  *  - icmp fixed part (mib2_icmp_t)
9576  *  - ipAddrEntryTable (ip 20)          all IPv4 ipifs
9577  *  - ipRouteEntryTable (ip 21)         all IPv4 IREs
9578  *  - ipNetToMediaEntryTable (ip 22)    all IPv4 Neighbor Cache entries
9579  *  - ipRouteAttributeTable (ip 102)    labeled routes
9580  *  - ip multicast membership (ip_member_t)
9581  *  - ip multicast source filtering (ip_grpsrc_t)
9582  *  - igmp fixed part (struct igmpstat)
9583  *  - multicast routing stats (struct mrtstat)
9584  *  - multicast routing vifs (array of struct vifctl)
9585  *  - multicast routing routes (array of struct mfcctl)
9586  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9587  *                                      One per ill plus one generic
9588  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9589  *                                      One per ill plus one generic
9590  *  - ipv6RouteEntry                    all IPv6 IREs
9591  *  - ipv6RouteAttributeTable (ip6 102) labeled routes
9592  *  - ipv6NetToMediaEntry               all IPv6 Neighbor Cache entries
9593  *  - ipv6AddrEntry                     all IPv6 ipifs
9594  *  - ipv6 multicast membership (ipv6_member_t)
9595  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9596  *
9597  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9598  * already filled in by the caller.
9599  * If legacy_req is true then MIB structures needs to be truncated to their
9600  * legacy sizes before being returned.
9601  * Return value of 0 indicates that no messages were sent and caller
9602  * should free mpctl.
9603  */
9604 int
9605 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9606 {
9607         ip_stack_t *ipst;
9608         sctp_stack_t *sctps;
9609 
9610         if (q->q_next != NULL) {
9611                 ipst = ILLQ_TO_IPST(q);
9612         } else {
9613                 ipst = CONNQ_TO_IPST(q);
9614         }
9615         ASSERT(ipst != NULL);
9616         sctps = ipst->ips_netstack->netstack_sctp;
9617 
9618         if (mpctl == NULL || mpctl->b_cont == NULL) {
9619                 return (0);
9620         }
9621 
9622         /*
9623          * For the purposes of the (broken) packet shell use
9624          * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9625          * to make TCP and UDP appear first in the list of mib items.
9626          * TBD: We could expand this and use it in netstat so that
9627          * the kernel doesn't have to produce large tables (connections,
9628          * routes, etc) when netstat only wants the statistics or a particular
9629          * table.
9630          */
9631         if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9632                 if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9633                         return (1);
9634                 }
9635         }
9636 
9637         if (level != MIB2_TCP) {
9638                 if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9639                         return (1);
9640                 }
9641         }
9642 
9643         if (level != MIB2_UDP) {
9644                 if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9645                         return (1);
9646                 }
9647         }
9648 
9649         if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9650             ipst, legacy_req)) == NULL) {
9651                 return (1);
9652         }
9653 
9654         if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9655             legacy_req)) == NULL) {
9656                 return (1);
9657         }
9658 
9659         if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9660                 return (1);
9661         }
9662 
9663         if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9664                 return (1);
9665         }
9666 
9667         if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9668                 return (1);
9669         }
9670 
9671         if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9672                 return (1);
9673         }
9674 
9675         if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9676             legacy_req)) == NULL) {
9677                 return (1);
9678         }
9679 
9680         if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9681             legacy_req)) == NULL) {
9682                 return (1);
9683         }
9684 
9685         if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9686                 return (1);
9687         }
9688 
9689         if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9690                 return (1);
9691         }
9692 
9693         if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9694                 return (1);
9695         }
9696 
9697         if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9698                 return (1);
9699         }
9700 
9701         if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9702                 return (1);
9703         }
9704 
9705         if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9706                 return (1);
9707         }
9708 
9709         mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9710         if (mpctl == NULL)
9711                 return (1);
9712 
9713         mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9714         if (mpctl == NULL)
9715                 return (1);
9716 
9717         if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9718                 return (1);
9719         }
9720         if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9721                 return (1);
9722         }
9723         freemsg(mpctl);
9724         return (1);
9725 }
9726 
9727 /* Get global (legacy) IPv4 statistics */
9728 static mblk_t *
9729 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9730     ip_stack_t *ipst, boolean_t legacy_req)
9731 {
9732         mib2_ip_t               old_ip_mib;
9733         struct opthdr           *optp;
9734         mblk_t                  *mp2ctl;
9735         mib2_ipAddrEntry_t      mae;
9736 
9737         /*
9738          * make a copy of the original message
9739          */
9740         mp2ctl = copymsg(mpctl);
9741 
9742         /* fixed length IP structure... */
9743         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9744         optp->level = MIB2_IP;
9745         optp->name = 0;
9746         SET_MIB(old_ip_mib.ipForwarding,
9747             (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9748         SET_MIB(old_ip_mib.ipDefaultTTL,
9749             (uint32_t)ipst->ips_ip_def_ttl);
9750         SET_MIB(old_ip_mib.ipReasmTimeout,
9751             ipst->ips_ip_reassembly_timeout);
9752         SET_MIB(old_ip_mib.ipAddrEntrySize,
9753             (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9754             sizeof (mib2_ipAddrEntry_t));
9755         SET_MIB(old_ip_mib.ipRouteEntrySize,
9756             sizeof (mib2_ipRouteEntry_t));
9757         SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9758             sizeof (mib2_ipNetToMediaEntry_t));
9759         SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9760         SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9761         SET_MIB(old_ip_mib.ipRouteAttributeSize,
9762             sizeof (mib2_ipAttributeEntry_t));
9763         SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9764         SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9765 
9766         /*
9767          * Grab the statistics from the new IP MIB
9768          */
9769         SET_MIB(old_ip_mib.ipInReceives,
9770             (uint32_t)ipmib->ipIfStatsHCInReceives);
9771         SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9772         SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9773         SET_MIB(old_ip_mib.ipForwDatagrams,
9774             (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9775         SET_MIB(old_ip_mib.ipInUnknownProtos,
9776             ipmib->ipIfStatsInUnknownProtos);
9777         SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9778         SET_MIB(old_ip_mib.ipInDelivers,
9779             (uint32_t)ipmib->ipIfStatsHCInDelivers);
9780         SET_MIB(old_ip_mib.ipOutRequests,
9781             (uint32_t)ipmib->ipIfStatsHCOutRequests);
9782         SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9783         SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9784         SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9785         SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9786         SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9787         SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9788         SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9789         SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9790 
9791         /* ipRoutingDiscards is not being used */
9792         SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9793         SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9794         SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9795         SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9796         SET_MIB(old_ip_mib.ipReasmDuplicates,
9797             ipmib->ipIfStatsReasmDuplicates);
9798         SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9799         SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9800         SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9801         SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9802         SET_MIB(old_ip_mib.rawipInOverflows,
9803             ipmib->rawipIfStatsInOverflows);
9804 
9805         SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9806         SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9807         SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9808         SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9809         SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9810             ipmib->ipIfStatsOutSwitchIPVersion);
9811 
9812         if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9813             (int)sizeof (old_ip_mib))) {
9814                 ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9815                     (uint_t)sizeof (old_ip_mib)));
9816         }
9817 
9818         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9819         ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9820             (int)optp->level, (int)optp->name, (int)optp->len));
9821         qreply(q, mpctl);
9822         return (mp2ctl);
9823 }
9824 
9825 /* Per interface IPv4 statistics */
9826 static mblk_t *
9827 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9828     boolean_t legacy_req)
9829 {
9830         struct opthdr           *optp;
9831         mblk_t                  *mp2ctl;
9832         ill_t                   *ill;
9833         ill_walk_context_t      ctx;
9834         mblk_t                  *mp_tail = NULL;
9835         mib2_ipIfStatsEntry_t   global_ip_mib;
9836         mib2_ipAddrEntry_t      mae;
9837 
9838         /*
9839          * Make a copy of the original message
9840          */
9841         mp2ctl = copymsg(mpctl);
9842 
9843         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9844         optp->level = MIB2_IP;
9845         optp->name = MIB2_IP_TRAFFIC_STATS;
9846         /* Include "unknown interface" ip_mib */
9847         ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9848         ipst->ips_ip_mib.ipIfStatsIfIndex =
9849             MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9850         SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9851             (ipst->ips_ip_forwarding ? 1 : 2));
9852         SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9853             (uint32_t)ipst->ips_ip_def_ttl);
9854         SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9855             sizeof (mib2_ipIfStatsEntry_t));
9856         SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9857             sizeof (mib2_ipAddrEntry_t));
9858         SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9859             sizeof (mib2_ipRouteEntry_t));
9860         SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9861             sizeof (mib2_ipNetToMediaEntry_t));
9862         SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9863             sizeof (ip_member_t));
9864         SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9865             sizeof (ip_grpsrc_t));
9866 
9867         bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9868 
9869         if (legacy_req) {
9870                 SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9871                     LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9872         }
9873 
9874         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9875             (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9876                 ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9877                     "failed to allocate %u bytes\n",
9878                     (uint_t)sizeof (global_ip_mib)));
9879         }
9880 
9881         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9882         ill = ILL_START_WALK_V4(&ctx, ipst);
9883         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9884                 ill->ill_ip_mib->ipIfStatsIfIndex =
9885                     ill->ill_phyint->phyint_ifindex;
9886                 SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9887                     (ipst->ips_ip_forwarding ? 1 : 2));
9888                 SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9889                     (uint32_t)ipst->ips_ip_def_ttl);
9890 
9891                 ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9892                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9893                     (char *)ill->ill_ip_mib,
9894                     (int)sizeof (*ill->ill_ip_mib))) {
9895                         ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9896                             "failed to allocate %u bytes\n",
9897                             (uint_t)sizeof (*ill->ill_ip_mib)));
9898                 }
9899         }
9900         rw_exit(&ipst->ips_ill_g_lock);
9901 
9902         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9903         ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9904             "level %d, name %d, len %d\n",
9905             (int)optp->level, (int)optp->name, (int)optp->len));
9906         qreply(q, mpctl);
9907 
9908         if (mp2ctl == NULL)
9909                 return (NULL);
9910 
9911         return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9912             legacy_req));
9913 }
9914 
9915 /* Global IPv4 ICMP statistics */
9916 static mblk_t *
9917 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9918 {
9919         struct opthdr           *optp;
9920         mblk_t                  *mp2ctl;
9921 
9922         /*
9923          * Make a copy of the original message
9924          */
9925         mp2ctl = copymsg(mpctl);
9926 
9927         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9928         optp->level = MIB2_ICMP;
9929         optp->name = 0;
9930         if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9931             (int)sizeof (ipst->ips_icmp_mib))) {
9932                 ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9933                     (uint_t)sizeof (ipst->ips_icmp_mib)));
9934         }
9935         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9936         ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9937             (int)optp->level, (int)optp->name, (int)optp->len));
9938         qreply(q, mpctl);
9939         return (mp2ctl);
9940 }
9941 
9942 /* Global IPv4 IGMP statistics */
9943 static mblk_t *
9944 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9945 {
9946         struct opthdr           *optp;
9947         mblk_t                  *mp2ctl;
9948 
9949         /*
9950          * make a copy of the original message
9951          */
9952         mp2ctl = copymsg(mpctl);
9953 
9954         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9955         optp->level = EXPER_IGMP;
9956         optp->name = 0;
9957         if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9958             (int)sizeof (ipst->ips_igmpstat))) {
9959                 ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9960                     (uint_t)sizeof (ipst->ips_igmpstat)));
9961         }
9962         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9963         ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9964             (int)optp->level, (int)optp->name, (int)optp->len));
9965         qreply(q, mpctl);
9966         return (mp2ctl);
9967 }
9968 
9969 /* Global IPv4 Multicast Routing statistics */
9970 static mblk_t *
9971 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9972 {
9973         struct opthdr           *optp;
9974         mblk_t                  *mp2ctl;
9975 
9976         /*
9977          * make a copy of the original message
9978          */
9979         mp2ctl = copymsg(mpctl);
9980 
9981         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9982         optp->level = EXPER_DVMRP;
9983         optp->name = 0;
9984         if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9985                 ip0dbg(("ip_mroute_stats: failed\n"));
9986         }
9987         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9988         ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9989             (int)optp->level, (int)optp->name, (int)optp->len));
9990         qreply(q, mpctl);
9991         return (mp2ctl);
9992 }
9993 
9994 /* IPv4 address information */
9995 static mblk_t *
9996 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9997     boolean_t legacy_req)
9998 {
9999         struct opthdr           *optp;
10000         mblk_t                  *mp2ctl;
10001         mblk_t                  *mp_tail = NULL;
10002         ill_t                   *ill;
10003         ipif_t                  *ipif;
10004         uint_t                  bitval;
10005         mib2_ipAddrEntry_t      mae;
10006         size_t                  mae_size;
10007         zoneid_t                zoneid;
10008         ill_walk_context_t      ctx;
10009 
10010         /*
10011          * make a copy of the original message
10012          */
10013         mp2ctl = copymsg(mpctl);
10014 
10015         mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
10016             sizeof (mib2_ipAddrEntry_t);
10017 
10018         /* ipAddrEntryTable */
10019 
10020         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10021         optp->level = MIB2_IP;
10022         optp->name = MIB2_IP_ADDR;
10023         zoneid = Q_TO_CONN(q)->conn_zoneid;
10024 
10025         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10026         ill = ILL_START_WALK_V4(&ctx, ipst);
10027         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10028                 for (ipif = ill->ill_ipif; ipif != NULL;
10029                     ipif = ipif->ipif_next) {
10030                         if (ipif->ipif_zoneid != zoneid &&
10031                             ipif->ipif_zoneid != ALL_ZONES)
10032                                 continue;
10033                         /* Sum of count from dead IRE_LO* and our current */
10034                         mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10035                         if (ipif->ipif_ire_local != NULL) {
10036                                 mae.ipAdEntInfo.ae_ibcnt +=
10037                                     ipif->ipif_ire_local->ire_ib_pkt_count;
10038                         }
10039                         mae.ipAdEntInfo.ae_obcnt = 0;
10040                         mae.ipAdEntInfo.ae_focnt = 0;
10041 
10042                         ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10043                             OCTET_LENGTH);
10044                         mae.ipAdEntIfIndex.o_length =
10045                             mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10046                         mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10047                         mae.ipAdEntNetMask = ipif->ipif_net_mask;
10048                         mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10049                         mae.ipAdEntInfo.ae_subnet_len =
10050                             ip_mask_to_plen(ipif->ipif_net_mask);
10051                         mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10052                         for (bitval = 1;
10053                             bitval &&
10054                             !(bitval & ipif->ipif_brd_addr);
10055                             bitval <<= 1)
10056                                 noop;
10057                         mae.ipAdEntBcastAddr = bitval;
10058                         mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10059                         mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10060                         mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
10061                         mae.ipAdEntInfo.ae_broadcast_addr =
10062                             ipif->ipif_brd_addr;
10063                         mae.ipAdEntInfo.ae_pp_dst_addr =
10064                             ipif->ipif_pp_dst_addr;
10065                         mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10066                             ill->ill_flags | ill->ill_phyint->phyint_flags;
10067                         mae.ipAdEntRetransmitTime =
10068                             ill->ill_reachable_retrans_time;
10069 
10070                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10071                             (char *)&mae, (int)mae_size)) {
10072                                 ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10073                                     "allocate %u bytes\n", (uint_t)mae_size));
10074                         }
10075                 }
10076         }
10077         rw_exit(&ipst->ips_ill_g_lock);
10078 
10079         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10080         ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10081             (int)optp->level, (int)optp->name, (int)optp->len));
10082         qreply(q, mpctl);
10083         return (mp2ctl);
10084 }
10085 
10086 /* IPv6 address information */
10087 static mblk_t *
10088 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10089     boolean_t legacy_req)
10090 {
10091         struct opthdr           *optp;
10092         mblk_t                  *mp2ctl;
10093         mblk_t                  *mp_tail = NULL;
10094         ill_t                   *ill;
10095         ipif_t                  *ipif;
10096         mib2_ipv6AddrEntry_t    mae6;
10097         size_t                  mae6_size;
10098         zoneid_t                zoneid;
10099         ill_walk_context_t      ctx;
10100 
10101         /*
10102          * make a copy of the original message
10103          */
10104         mp2ctl = copymsg(mpctl);
10105 
10106         mae6_size = (legacy_req) ?
10107             LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10108             sizeof (mib2_ipv6AddrEntry_t);
10109 
10110         /* ipv6AddrEntryTable */
10111 
10112         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10113         optp->level = MIB2_IP6;
10114         optp->name = MIB2_IP6_ADDR;
10115         zoneid = Q_TO_CONN(q)->conn_zoneid;
10116 
10117         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10118         ill = ILL_START_WALK_V6(&ctx, ipst);
10119         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10120                 for (ipif = ill->ill_ipif; ipif != NULL;
10121                     ipif = ipif->ipif_next) {
10122                         if (ipif->ipif_zoneid != zoneid &&
10123                             ipif->ipif_zoneid != ALL_ZONES)
10124                                 continue;
10125                         /* Sum of count from dead IRE_LO* and our current */
10126                         mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10127                         if (ipif->ipif_ire_local != NULL) {
10128                                 mae6.ipv6AddrInfo.ae_ibcnt +=
10129                                     ipif->ipif_ire_local->ire_ib_pkt_count;
10130                         }
10131                         mae6.ipv6AddrInfo.ae_obcnt = 0;
10132                         mae6.ipv6AddrInfo.ae_focnt = 0;
10133 
10134                         ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10135                             OCTET_LENGTH);
10136                         mae6.ipv6AddrIfIndex.o_length =
10137                             mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10138                         mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10139                         mae6.ipv6AddrPfxLength =
10140                             ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10141                         mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10142                         mae6.ipv6AddrInfo.ae_subnet_len =
10143                             mae6.ipv6AddrPfxLength;
10144                         mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10145 
10146                         /* Type: stateless(1), stateful(2), unknown(3) */
10147                         if (ipif->ipif_flags & IPIF_ADDRCONF)
10148                                 mae6.ipv6AddrType = 1;
10149                         else
10150                                 mae6.ipv6AddrType = 2;
10151                         /* Anycast: true(1), false(2) */
10152                         if (ipif->ipif_flags & IPIF_ANYCAST)
10153                                 mae6.ipv6AddrAnycastFlag = 1;
10154                         else
10155                                 mae6.ipv6AddrAnycastFlag = 2;
10156 
10157                         /*
10158                          * Address status: preferred(1), deprecated(2),
10159                          * invalid(3), inaccessible(4), unknown(5)
10160                          */
10161                         if (ipif->ipif_flags & IPIF_NOLOCAL)
10162                                 mae6.ipv6AddrStatus = 3;
10163                         else if (ipif->ipif_flags & IPIF_DEPRECATED)
10164                                 mae6.ipv6AddrStatus = 2;
10165                         else
10166                                 mae6.ipv6AddrStatus = 1;
10167                         mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10168                         mae6.ipv6AddrInfo.ae_metric  =
10169                             ipif->ipif_ill->ill_metric;
10170                         mae6.ipv6AddrInfo.ae_pp_dst_addr =
10171                             ipif->ipif_v6pp_dst_addr;
10172                         mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10173                             ill->ill_flags | ill->ill_phyint->phyint_flags;
10174                         mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10175                         mae6.ipv6AddrIdentifier = ill->ill_token;
10176                         mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10177                         mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10178                         mae6.ipv6AddrRetransmitTime =
10179                             ill->ill_reachable_retrans_time;
10180                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10181                             (char *)&mae6, (int)mae6_size)) {
10182                                 ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10183                                     "allocate %u bytes\n",
10184                                     (uint_t)mae6_size));
10185                         }
10186                 }
10187         }
10188         rw_exit(&ipst->ips_ill_g_lock);
10189 
10190         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10191         ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10192             (int)optp->level, (int)optp->name, (int)optp->len));
10193         qreply(q, mpctl);
10194         return (mp2ctl);
10195 }
10196 
10197 /* IPv4 multicast group membership. */
10198 static mblk_t *
10199 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10200 {
10201         struct opthdr           *optp;
10202         mblk_t                  *mp2ctl;
10203         ill_t                   *ill;
10204         ipif_t                  *ipif;
10205         ilm_t                   *ilm;
10206         ip_member_t             ipm;
10207         mblk_t                  *mp_tail = NULL;
10208         ill_walk_context_t      ctx;
10209         zoneid_t                zoneid;
10210 
10211         /*
10212          * make a copy of the original message
10213          */
10214         mp2ctl = copymsg(mpctl);
10215         zoneid = Q_TO_CONN(q)->conn_zoneid;
10216 
10217         /* ipGroupMember table */
10218         optp = (struct opthdr *)&mpctl->b_rptr[
10219             sizeof (struct T_optmgmt_ack)];
10220         optp->level = MIB2_IP;
10221         optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10222 
10223         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10224         ill = ILL_START_WALK_V4(&ctx, ipst);
10225         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10226                 /* Make sure the ill isn't going away. */
10227                 if (!ill_check_and_refhold(ill))
10228                         continue;
10229                 rw_exit(&ipst->ips_ill_g_lock);
10230                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10231                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10232                         if (ilm->ilm_zoneid != zoneid &&
10233                             ilm->ilm_zoneid != ALL_ZONES)
10234                                 continue;
10235 
10236                         /* Is there an ipif for ilm_ifaddr? */
10237                         for (ipif = ill->ill_ipif; ipif != NULL;
10238                             ipif = ipif->ipif_next) {
10239                                 if (!IPIF_IS_CONDEMNED(ipif) &&
10240                                     ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10241                                     ilm->ilm_ifaddr != INADDR_ANY)
10242                                         break;
10243                         }
10244                         if (ipif != NULL) {
10245                                 ipif_get_name(ipif,
10246                                     ipm.ipGroupMemberIfIndex.o_bytes,
10247                                     OCTET_LENGTH);
10248                         } else {
10249                                 ill_get_name(ill,
10250                                     ipm.ipGroupMemberIfIndex.o_bytes,
10251                                     OCTET_LENGTH);
10252                         }
10253                         ipm.ipGroupMemberIfIndex.o_length =
10254                             mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10255 
10256                         ipm.ipGroupMemberAddress = ilm->ilm_addr;
10257                         ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10258                         ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10259                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10260                             (char *)&ipm, (int)sizeof (ipm))) {
10261                                 ip1dbg(("ip_snmp_get_mib2_ip_group: "
10262                                     "failed to allocate %u bytes\n",
10263                                     (uint_t)sizeof (ipm)));
10264                         }
10265                 }
10266                 rw_exit(&ill->ill_mcast_lock);
10267                 ill_refrele(ill);
10268                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10269         }
10270         rw_exit(&ipst->ips_ill_g_lock);
10271         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10272         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10273             (int)optp->level, (int)optp->name, (int)optp->len));
10274         qreply(q, mpctl);
10275         return (mp2ctl);
10276 }
10277 
10278 /* IPv6 multicast group membership. */
10279 static mblk_t *
10280 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10281 {
10282         struct opthdr           *optp;
10283         mblk_t                  *mp2ctl;
10284         ill_t                   *ill;
10285         ilm_t                   *ilm;
10286         ipv6_member_t           ipm6;
10287         mblk_t                  *mp_tail = NULL;
10288         ill_walk_context_t      ctx;
10289         zoneid_t                zoneid;
10290 
10291         /*
10292          * make a copy of the original message
10293          */
10294         mp2ctl = copymsg(mpctl);
10295         zoneid = Q_TO_CONN(q)->conn_zoneid;
10296 
10297         /* ip6GroupMember table */
10298         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10299         optp->level = MIB2_IP6;
10300         optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10301 
10302         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10303         ill = ILL_START_WALK_V6(&ctx, ipst);
10304         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10305                 /* Make sure the ill isn't going away. */
10306                 if (!ill_check_and_refhold(ill))
10307                         continue;
10308                 rw_exit(&ipst->ips_ill_g_lock);
10309                 /*
10310                  * Normally we don't have any members on under IPMP interfaces.
10311                  * We report them as a debugging aid.
10312                  */
10313                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10314                 ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10315                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10316                         if (ilm->ilm_zoneid != zoneid &&
10317                             ilm->ilm_zoneid != ALL_ZONES)
10318                                 continue;       /* not this zone */
10319                         ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10320                         ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10321                         ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10322                         if (!snmp_append_data2(mpctl->b_cont,
10323                             &mp_tail,
10324                             (char *)&ipm6, (int)sizeof (ipm6))) {
10325                                 ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10326                                     "failed to allocate %u bytes\n",
10327                                     (uint_t)sizeof (ipm6)));
10328                         }
10329                 }
10330                 rw_exit(&ill->ill_mcast_lock);
10331                 ill_refrele(ill);
10332                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10333         }
10334         rw_exit(&ipst->ips_ill_g_lock);
10335 
10336         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10337         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10338             (int)optp->level, (int)optp->name, (int)optp->len));
10339         qreply(q, mpctl);
10340         return (mp2ctl);
10341 }
10342 
10343 /* IP multicast filtered sources */
10344 static mblk_t *
10345 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10346 {
10347         struct opthdr           *optp;
10348         mblk_t                  *mp2ctl;
10349         ill_t                   *ill;
10350         ipif_t                  *ipif;
10351         ilm_t                   *ilm;
10352         ip_grpsrc_t             ips;
10353         mblk_t                  *mp_tail = NULL;
10354         ill_walk_context_t      ctx;
10355         zoneid_t                zoneid;
10356         int                     i;
10357         slist_t                 *sl;
10358 
10359         /*
10360          * make a copy of the original message
10361          */
10362         mp2ctl = copymsg(mpctl);
10363         zoneid = Q_TO_CONN(q)->conn_zoneid;
10364 
10365         /* ipGroupSource table */
10366         optp = (struct opthdr *)&mpctl->b_rptr[
10367             sizeof (struct T_optmgmt_ack)];
10368         optp->level = MIB2_IP;
10369         optp->name = EXPER_IP_GROUP_SOURCES;
10370 
10371         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10372         ill = ILL_START_WALK_V4(&ctx, ipst);
10373         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10374                 /* Make sure the ill isn't going away. */
10375                 if (!ill_check_and_refhold(ill))
10376                         continue;
10377                 rw_exit(&ipst->ips_ill_g_lock);
10378                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10379                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10380                         sl = ilm->ilm_filter;
10381                         if (ilm->ilm_zoneid != zoneid &&
10382                             ilm->ilm_zoneid != ALL_ZONES)
10383                                 continue;
10384                         if (SLIST_IS_EMPTY(sl))
10385                                 continue;
10386 
10387                         /* Is there an ipif for ilm_ifaddr? */
10388                         for (ipif = ill->ill_ipif; ipif != NULL;
10389                             ipif = ipif->ipif_next) {
10390                                 if (!IPIF_IS_CONDEMNED(ipif) &&
10391                                     ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10392                                     ilm->ilm_ifaddr != INADDR_ANY)
10393                                         break;
10394                         }
10395                         if (ipif != NULL) {
10396                                 ipif_get_name(ipif,
10397                                     ips.ipGroupSourceIfIndex.o_bytes,
10398                                     OCTET_LENGTH);
10399                         } else {
10400                                 ill_get_name(ill,
10401                                     ips.ipGroupSourceIfIndex.o_bytes,
10402                                     OCTET_LENGTH);
10403                         }
10404                         ips.ipGroupSourceIfIndex.o_length =
10405                             mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10406 
10407                         ips.ipGroupSourceGroup = ilm->ilm_addr;
10408                         for (i = 0; i < sl->sl_numsrc; i++) {
10409                                 if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10410                                         continue;
10411                                 IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10412                                     ips.ipGroupSourceAddress);
10413                                 if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10414                                     (char *)&ips, (int)sizeof (ips)) == 0) {
10415                                         ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10416                                             " failed to allocate %u bytes\n",
10417                                             (uint_t)sizeof (ips)));
10418                                 }
10419                         }
10420                 }
10421                 rw_exit(&ill->ill_mcast_lock);
10422                 ill_refrele(ill);
10423                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10424         }
10425         rw_exit(&ipst->ips_ill_g_lock);
10426         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10427         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10428             (int)optp->level, (int)optp->name, (int)optp->len));
10429         qreply(q, mpctl);
10430         return (mp2ctl);
10431 }
10432 
10433 /* IPv6 multicast filtered sources. */
10434 static mblk_t *
10435 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10436 {
10437         struct opthdr           *optp;
10438         mblk_t                  *mp2ctl;
10439         ill_t                   *ill;
10440         ilm_t                   *ilm;
10441         ipv6_grpsrc_t           ips6;
10442         mblk_t                  *mp_tail = NULL;
10443         ill_walk_context_t      ctx;
10444         zoneid_t                zoneid;
10445         int                     i;
10446         slist_t                 *sl;
10447 
10448         /*
10449          * make a copy of the original message
10450          */
10451         mp2ctl = copymsg(mpctl);
10452         zoneid = Q_TO_CONN(q)->conn_zoneid;
10453 
10454         /* ip6GroupMember table */
10455         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10456         optp->level = MIB2_IP6;
10457         optp->name = EXPER_IP6_GROUP_SOURCES;
10458 
10459         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10460         ill = ILL_START_WALK_V6(&ctx, ipst);
10461         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10462                 /* Make sure the ill isn't going away. */
10463                 if (!ill_check_and_refhold(ill))
10464                         continue;
10465                 rw_exit(&ipst->ips_ill_g_lock);
10466                 /*
10467                  * Normally we don't have any members on under IPMP interfaces.
10468                  * We report them as a debugging aid.
10469                  */
10470                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10471                 ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10472                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10473                         sl = ilm->ilm_filter;
10474                         if (ilm->ilm_zoneid != zoneid &&
10475                             ilm->ilm_zoneid != ALL_ZONES)
10476                                 continue;
10477                         if (SLIST_IS_EMPTY(sl))
10478                                 continue;
10479                         ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10480                         for (i = 0; i < sl->sl_numsrc; i++) {
10481                                 ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10482                                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10483                                     (char *)&ips6, (int)sizeof (ips6))) {
10484                                         ip1dbg(("ip_snmp_get_mib2_ip6_"
10485                                             "group_src: failed to allocate "
10486                                             "%u bytes\n",
10487                                             (uint_t)sizeof (ips6)));
10488                                 }
10489                         }
10490                 }
10491                 rw_exit(&ill->ill_mcast_lock);
10492                 ill_refrele(ill);
10493                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10494         }
10495         rw_exit(&ipst->ips_ill_g_lock);
10496 
10497         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10498         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10499             (int)optp->level, (int)optp->name, (int)optp->len));
10500         qreply(q, mpctl);
10501         return (mp2ctl);
10502 }
10503 
10504 /* Multicast routing virtual interface table. */
10505 static mblk_t *
10506 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10507 {
10508         struct opthdr           *optp;
10509         mblk_t                  *mp2ctl;
10510 
10511         /*
10512          * make a copy of the original message
10513          */
10514         mp2ctl = copymsg(mpctl);
10515 
10516         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10517         optp->level = EXPER_DVMRP;
10518         optp->name = EXPER_DVMRP_VIF;
10519         if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10520                 ip0dbg(("ip_mroute_vif: failed\n"));
10521         }
10522         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10523         ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10524             (int)optp->level, (int)optp->name, (int)optp->len));
10525         qreply(q, mpctl);
10526         return (mp2ctl);
10527 }
10528 
10529 /* Multicast routing table. */
10530 static mblk_t *
10531 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10532 {
10533         struct opthdr           *optp;
10534         mblk_t                  *mp2ctl;
10535 
10536         /*
10537          * make a copy of the original message
10538          */
10539         mp2ctl = copymsg(mpctl);
10540 
10541         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10542         optp->level = EXPER_DVMRP;
10543         optp->name = EXPER_DVMRP_MRT;
10544         if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10545                 ip0dbg(("ip_mroute_mrt: failed\n"));
10546         }
10547         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10548         ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10549             (int)optp->level, (int)optp->name, (int)optp->len));
10550         qreply(q, mpctl);
10551         return (mp2ctl);
10552 }
10553 
10554 /*
10555  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10556  * in one IRE walk.
10557  */
10558 static mblk_t *
10559 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10560     ip_stack_t *ipst)
10561 {
10562         struct opthdr   *optp;
10563         mblk_t          *mp2ctl;        /* Returned */
10564         mblk_t          *mp3ctl;        /* nettomedia */
10565         mblk_t          *mp4ctl;        /* routeattrs */
10566         iproutedata_t   ird;
10567         zoneid_t        zoneid;
10568 
10569         /*
10570          * make copies of the original message
10571          *      - mp2ctl is returned unchanged to the caller for its use
10572          *      - mpctl is sent upstream as ipRouteEntryTable
10573          *      - mp3ctl is sent upstream as ipNetToMediaEntryTable
10574          *      - mp4ctl is sent upstream as ipRouteAttributeTable
10575          */
10576         mp2ctl = copymsg(mpctl);
10577         mp3ctl = copymsg(mpctl);
10578         mp4ctl = copymsg(mpctl);
10579         if (mp3ctl == NULL || mp4ctl == NULL) {
10580                 freemsg(mp4ctl);
10581                 freemsg(mp3ctl);
10582                 freemsg(mp2ctl);
10583                 freemsg(mpctl);
10584                 return (NULL);
10585         }
10586 
10587         bzero(&ird, sizeof (ird));
10588 
10589         ird.ird_route.lp_head = mpctl->b_cont;
10590         ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10591         ird.ird_attrs.lp_head = mp4ctl->b_cont;
10592         /*
10593          * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10594          * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10595          * intended a temporary solution until a proper MIB API is provided
10596          * that provides complete filtering/caller-opt-in.
10597          */
10598         if (level == EXPER_IP_AND_ALL_IRES)
10599                 ird.ird_flags |= IRD_REPORT_ALL;
10600 
10601         zoneid = Q_TO_CONN(q)->conn_zoneid;
10602         ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10603 
10604         /* ipRouteEntryTable in mpctl */
10605         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10606         optp->level = MIB2_IP;
10607         optp->name = MIB2_IP_ROUTE;
10608         optp->len = msgdsize(ird.ird_route.lp_head);
10609         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10610             (int)optp->level, (int)optp->name, (int)optp->len));
10611         qreply(q, mpctl);
10612 
10613         /* ipNetToMediaEntryTable in mp3ctl */
10614         ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10615 
10616         optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10617         optp->level = MIB2_IP;
10618         optp->name = MIB2_IP_MEDIA;
10619         optp->len = msgdsize(ird.ird_netmedia.lp_head);
10620         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10621             (int)optp->level, (int)optp->name, (int)optp->len));
10622         qreply(q, mp3ctl);
10623 
10624         /* ipRouteAttributeTable in mp4ctl */
10625         optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10626         optp->level = MIB2_IP;
10627         optp->name = EXPER_IP_RTATTR;
10628         optp->len = msgdsize(ird.ird_attrs.lp_head);
10629         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10630             (int)optp->level, (int)optp->name, (int)optp->len));
10631         if (optp->len == 0)
10632                 freemsg(mp4ctl);
10633         else
10634                 qreply(q, mp4ctl);
10635 
10636         return (mp2ctl);
10637 }
10638 
10639 /*
10640  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10641  * ipv6NetToMediaEntryTable in an NDP walk.
10642  */
10643 static mblk_t *
10644 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10645     ip_stack_t *ipst)
10646 {
10647         struct opthdr   *optp;
10648         mblk_t          *mp2ctl;        /* Returned */
10649         mblk_t          *mp3ctl;        /* nettomedia */
10650         mblk_t          *mp4ctl;        /* routeattrs */
10651         iproutedata_t   ird;
10652         zoneid_t        zoneid;
10653 
10654         /*
10655          * make copies of the original message
10656          *      - mp2ctl is returned unchanged to the caller for its use
10657          *      - mpctl is sent upstream as ipv6RouteEntryTable
10658          *      - mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10659          *      - mp4ctl is sent upstream as ipv6RouteAttributeTable
10660          */
10661         mp2ctl = copymsg(mpctl);
10662         mp3ctl = copymsg(mpctl);
10663         mp4ctl = copymsg(mpctl);
10664         if (mp3ctl == NULL || mp4ctl == NULL) {
10665                 freemsg(mp4ctl);
10666                 freemsg(mp3ctl);
10667                 freemsg(mp2ctl);
10668                 freemsg(mpctl);
10669                 return (NULL);
10670         }
10671 
10672         bzero(&ird, sizeof (ird));
10673 
10674         ird.ird_route.lp_head = mpctl->b_cont;
10675         ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10676         ird.ird_attrs.lp_head = mp4ctl->b_cont;
10677         /*
10678          * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10679          * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10680          * intended a temporary solution until a proper MIB API is provided
10681          * that provides complete filtering/caller-opt-in.
10682          */
10683         if (level == EXPER_IP_AND_ALL_IRES)
10684                 ird.ird_flags |= IRD_REPORT_ALL;
10685 
10686         zoneid = Q_TO_CONN(q)->conn_zoneid;
10687         ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10688 
10689         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10690         optp->level = MIB2_IP6;
10691         optp->name = MIB2_IP6_ROUTE;
10692         optp->len = msgdsize(ird.ird_route.lp_head);
10693         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10694             (int)optp->level, (int)optp->name, (int)optp->len));
10695         qreply(q, mpctl);
10696 
10697         /* ipv6NetToMediaEntryTable in mp3ctl */
10698         ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10699 
10700         optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10701         optp->level = MIB2_IP6;
10702         optp->name = MIB2_IP6_MEDIA;
10703         optp->len = msgdsize(ird.ird_netmedia.lp_head);
10704         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10705             (int)optp->level, (int)optp->name, (int)optp->len));
10706         qreply(q, mp3ctl);
10707 
10708         /* ipv6RouteAttributeTable in mp4ctl */
10709         optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10710         optp->level = MIB2_IP6;
10711         optp->name = EXPER_IP_RTATTR;
10712         optp->len = msgdsize(ird.ird_attrs.lp_head);
10713         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10714             (int)optp->level, (int)optp->name, (int)optp->len));
10715         if (optp->len == 0)
10716                 freemsg(mp4ctl);
10717         else
10718                 qreply(q, mp4ctl);
10719 
10720         return (mp2ctl);
10721 }
10722 
10723 /*
10724  * IPv6 mib: One per ill
10725  */
10726 static mblk_t *
10727 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10728     boolean_t legacy_req)
10729 {
10730         struct opthdr           *optp;
10731         mblk_t                  *mp2ctl;
10732         ill_t                   *ill;
10733         ill_walk_context_t      ctx;
10734         mblk_t                  *mp_tail = NULL;
10735         mib2_ipv6AddrEntry_t    mae6;
10736         mib2_ipIfStatsEntry_t   *ise;
10737         size_t                  ise_size, iae_size;
10738 
10739         /*
10740          * Make a copy of the original message
10741          */
10742         mp2ctl = copymsg(mpctl);
10743 
10744         /* fixed length IPv6 structure ... */
10745 
10746         if (legacy_req) {
10747                 ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10748                     mib2_ipIfStatsEntry_t);
10749                 iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10750         } else {
10751                 ise_size = sizeof (mib2_ipIfStatsEntry_t);
10752                 iae_size = sizeof (mib2_ipv6AddrEntry_t);
10753         }
10754 
10755         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10756         optp->level = MIB2_IP6;
10757         optp->name = 0;
10758         /* Include "unknown interface" ip6_mib */
10759         ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10760         ipst->ips_ip6_mib.ipIfStatsIfIndex =
10761             MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10762         SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10763             ipst->ips_ipv6_forwarding ? 1 : 2);
10764         SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10765             ipst->ips_ipv6_def_hops);
10766         SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10767             sizeof (mib2_ipIfStatsEntry_t));
10768         SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10769             sizeof (mib2_ipv6AddrEntry_t));
10770         SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10771             sizeof (mib2_ipv6RouteEntry_t));
10772         SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10773             sizeof (mib2_ipv6NetToMediaEntry_t));
10774         SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10775             sizeof (ipv6_member_t));
10776         SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10777             sizeof (ipv6_grpsrc_t));
10778 
10779         /*
10780          * Synchronize 64- and 32-bit counters
10781          */
10782         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10783             ipIfStatsHCInReceives);
10784         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10785             ipIfStatsHCInDelivers);
10786         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10787             ipIfStatsHCOutRequests);
10788         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10789             ipIfStatsHCOutForwDatagrams);
10790         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10791             ipIfStatsHCOutMcastPkts);
10792         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10793             ipIfStatsHCInMcastPkts);
10794 
10795         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10796             (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10797                 ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10798                     (uint_t)ise_size));
10799         } else if (legacy_req) {
10800                 /* Adjust the EntrySize fields for legacy requests. */
10801                 ise =
10802                     (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10803                 SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10804                 SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10805         }
10806 
10807         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10808         ill = ILL_START_WALK_V6(&ctx, ipst);
10809         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10810                 ill->ill_ip_mib->ipIfStatsIfIndex =
10811                     ill->ill_phyint->phyint_ifindex;
10812                 SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10813                     ipst->ips_ipv6_forwarding ? 1 : 2);
10814                 SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10815                     ill->ill_max_hops);
10816 
10817                 /*
10818                  * Synchronize 64- and 32-bit counters
10819                  */
10820                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10821                     ipIfStatsHCInReceives);
10822                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10823                     ipIfStatsHCInDelivers);
10824                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10825                     ipIfStatsHCOutRequests);
10826                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10827                     ipIfStatsHCOutForwDatagrams);
10828                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10829                     ipIfStatsHCOutMcastPkts);
10830                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10831                     ipIfStatsHCInMcastPkts);
10832 
10833                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10834                     (char *)ill->ill_ip_mib, (int)ise_size)) {
10835                         ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10836                         "%u bytes\n", (uint_t)ise_size));
10837                 } else if (legacy_req) {
10838                         /* Adjust the EntrySize fields for legacy requests. */
10839                         ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10840                             (int)ise_size);
10841                         SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10842                         SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
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_ip6: 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  * ICMPv6 mib: One per ill
10856  */
10857 static mblk_t *
10858 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10859 {
10860         struct opthdr           *optp;
10861         mblk_t                  *mp2ctl;
10862         ill_t                   *ill;
10863         ill_walk_context_t      ctx;
10864         mblk_t                  *mp_tail = NULL;
10865         /*
10866          * Make a copy of the original message
10867          */
10868         mp2ctl = copymsg(mpctl);
10869 
10870         /* fixed length ICMPv6 structure ... */
10871 
10872         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10873         optp->level = MIB2_ICMP6;
10874         optp->name = 0;
10875         /* Include "unknown interface" icmp6_mib */
10876         ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10877             MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10878         ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10879             sizeof (mib2_ipv6IfIcmpEntry_t);
10880         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10881             (char *)&ipst->ips_icmp6_mib,
10882             (int)sizeof (ipst->ips_icmp6_mib))) {
10883                 ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10884                     (uint_t)sizeof (ipst->ips_icmp6_mib)));
10885         }
10886 
10887         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10888         ill = ILL_START_WALK_V6(&ctx, ipst);
10889         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10890                 ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10891                     ill->ill_phyint->phyint_ifindex;
10892                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10893                     (char *)ill->ill_icmp6_mib,
10894                     (int)sizeof (*ill->ill_icmp6_mib))) {
10895                         ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10896                             "%u bytes\n",
10897                             (uint_t)sizeof (*ill->ill_icmp6_mib)));
10898                 }
10899         }
10900         rw_exit(&ipst->ips_ill_g_lock);
10901 
10902         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10903         ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10904             (int)optp->level, (int)optp->name, (int)optp->len));
10905         qreply(q, mpctl);
10906         return (mp2ctl);
10907 }
10908 
10909 /*
10910  * ire_walk routine to create both ipRouteEntryTable and
10911  * ipRouteAttributeTable in one IRE walk
10912  */
10913 static void
10914 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10915 {
10916         ill_t                           *ill;
10917         mib2_ipRouteEntry_t             *re;
10918         mib2_ipAttributeEntry_t         iaes;
10919         tsol_ire_gw_secattr_t           *attrp;
10920         tsol_gc_t                       *gc = NULL;
10921         tsol_gcgrp_t                    *gcgrp = NULL;
10922         ip_stack_t                      *ipst = ire->ire_ipst;
10923 
10924         ASSERT(ire->ire_ipversion == IPV4_VERSION);
10925 
10926         if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10927                 if (ire->ire_testhidden)
10928                         return;
10929                 if (ire->ire_type & IRE_IF_CLONE)
10930                         return;
10931         }
10932 
10933         if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10934                 return;
10935 
10936         if ((attrp = ire->ire_gw_secattr) != NULL) {
10937                 mutex_enter(&attrp->igsa_lock);
10938                 if ((gc = attrp->igsa_gc) != NULL) {
10939                         gcgrp = gc->gc_grp;
10940                         ASSERT(gcgrp != NULL);
10941                         rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10942                 }
10943                 mutex_exit(&attrp->igsa_lock);
10944         }
10945         /*
10946          * Return all IRE types for route table... let caller pick and choose
10947          */
10948         re->ipRouteDest = ire->ire_addr;
10949         ill = ire->ire_ill;
10950         re->ipRouteIfIndex.o_length = 0;
10951         if (ill != NULL) {
10952                 ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10953                 re->ipRouteIfIndex.o_length =
10954                     mi_strlen(re->ipRouteIfIndex.o_bytes);
10955         }
10956         re->ipRouteMetric1 = -1;
10957         re->ipRouteMetric2 = -1;
10958         re->ipRouteMetric3 = -1;
10959         re->ipRouteMetric4 = -1;
10960 
10961         re->ipRouteNextHop = ire->ire_gateway_addr;
10962         /* indirect(4), direct(3), or invalid(2) */
10963         if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10964                 re->ipRouteType = 2;
10965         else if (ire->ire_type & IRE_ONLINK)
10966                 re->ipRouteType = 3;
10967         else
10968                 re->ipRouteType = 4;
10969 
10970         re->ipRouteProto = -1;
10971         re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10972         re->ipRouteMask = ire->ire_mask;
10973         re->ipRouteMetric5 = -1;
10974         re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10975         if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10976                 re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10977 
10978         re->ipRouteInfo.re_frag_flag = 0;
10979         re->ipRouteInfo.re_rtt               = 0;
10980         re->ipRouteInfo.re_src_addr  = 0;
10981         re->ipRouteInfo.re_ref               = ire->ire_refcnt;
10982         re->ipRouteInfo.re_obpkt     = ire->ire_ob_pkt_count;
10983         re->ipRouteInfo.re_ibpkt     = ire->ire_ib_pkt_count;
10984         re->ipRouteInfo.re_flags     = ire->ire_flags;
10985 
10986         /* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10987         if (ire->ire_type & IRE_INTERFACE) {
10988                 ire_t *child;
10989 
10990                 rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10991                 child = ire->ire_dep_children;
10992                 while (child != NULL) {
10993                         re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10994                         re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10995                         child = child->ire_dep_sib_next;
10996                 }
10997                 rw_exit(&ipst->ips_ire_dep_lock);
10998         }
10999 
11000         if (ire->ire_flags & RTF_DYNAMIC) {
11001                 re->ipRouteInfo.re_ire_type  = IRE_HOST_REDIRECT;
11002         } else {
11003                 re->ipRouteInfo.re_ire_type  = ire->ire_type;
11004         }
11005 
11006         if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11007             (char *)re, (int)sizeof (*re))) {
11008                 ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11009                     (uint_t)sizeof (*re)));
11010         }
11011 
11012         if (gc != NULL) {
11013                 iaes.iae_routeidx = ird->ird_idx;
11014                 iaes.iae_doi = gc->gc_db->gcdb_doi;
11015                 iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11016 
11017                 if (!snmp_append_data2(ird->ird_attrs.lp_head,
11018                     &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11019                         ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11020                             "bytes\n", (uint_t)sizeof (iaes)));
11021                 }
11022         }
11023 
11024         /* bump route index for next pass */
11025         ird->ird_idx++;
11026 
11027         kmem_free(re, sizeof (*re));
11028         if (gcgrp != NULL)
11029                 rw_exit(&gcgrp->gcgrp_rwlock);
11030 }
11031 
11032 /*
11033  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11034  */
11035 static void
11036 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11037 {
11038         ill_t                           *ill;
11039         mib2_ipv6RouteEntry_t           *re;
11040         mib2_ipAttributeEntry_t         iaes;
11041         tsol_ire_gw_secattr_t           *attrp;
11042         tsol_gc_t                       *gc = NULL;
11043         tsol_gcgrp_t                    *gcgrp = NULL;
11044         ip_stack_t                      *ipst = ire->ire_ipst;
11045 
11046         ASSERT(ire->ire_ipversion == IPV6_VERSION);
11047 
11048         if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11049                 if (ire->ire_testhidden)
11050                         return;
11051                 if (ire->ire_type & IRE_IF_CLONE)
11052                         return;
11053         }
11054 
11055         if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11056                 return;
11057 
11058         if ((attrp = ire->ire_gw_secattr) != NULL) {
11059                 mutex_enter(&attrp->igsa_lock);
11060                 if ((gc = attrp->igsa_gc) != NULL) {
11061                         gcgrp = gc->gc_grp;
11062                         ASSERT(gcgrp != NULL);
11063                         rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11064                 }
11065                 mutex_exit(&attrp->igsa_lock);
11066         }
11067         /*
11068          * Return all IRE types for route table... let caller pick and choose
11069          */
11070         re->ipv6RouteDest = ire->ire_addr_v6;
11071         re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11072         re->ipv6RouteIndex = 0;      /* Unique when multiple with same dest/plen */
11073         re->ipv6RouteIfIndex.o_length = 0;
11074         ill = ire->ire_ill;
11075         if (ill != NULL) {
11076                 ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11077                 re->ipv6RouteIfIndex.o_length =
11078                     mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11079         }
11080 
11081         ASSERT(!(ire->ire_type & IRE_BROADCAST));
11082 
11083         mutex_enter(&ire->ire_lock);
11084         re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11085         mutex_exit(&ire->ire_lock);
11086 
11087         /* remote(4), local(3), or discard(2) */
11088         if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11089                 re->ipv6RouteType = 2;
11090         else if (ire->ire_type & IRE_ONLINK)
11091                 re->ipv6RouteType = 3;
11092         else
11093                 re->ipv6RouteType = 4;
11094 
11095         re->ipv6RouteProtocol        = -1;
11096         re->ipv6RoutePolicy  = 0;
11097         re->ipv6RouteAge     = gethrestime_sec() - ire->ire_create_time;
11098         re->ipv6RouteNextHopRDI      = 0;
11099         re->ipv6RouteWeight  = 0;
11100         re->ipv6RouteMetric  = 0;
11101         re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11102         if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11103                 re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11104 
11105         re->ipv6RouteInfo.re_frag_flag       = 0;
11106         re->ipv6RouteInfo.re_rtt     = 0;
11107         re->ipv6RouteInfo.re_src_addr        = ipv6_all_zeros;
11108         re->ipv6RouteInfo.re_obpkt   = ire->ire_ob_pkt_count;
11109         re->ipv6RouteInfo.re_ibpkt   = ire->ire_ib_pkt_count;
11110         re->ipv6RouteInfo.re_ref     = ire->ire_refcnt;
11111         re->ipv6RouteInfo.re_flags   = ire->ire_flags;
11112 
11113         /* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11114         if (ire->ire_type & IRE_INTERFACE) {
11115                 ire_t *child;
11116 
11117                 rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11118                 child = ire->ire_dep_children;
11119                 while (child != NULL) {
11120                         re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11121                         re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11122                         child = child->ire_dep_sib_next;
11123                 }
11124                 rw_exit(&ipst->ips_ire_dep_lock);
11125         }
11126         if (ire->ire_flags & RTF_DYNAMIC) {
11127                 re->ipv6RouteInfo.re_ire_type        = IRE_HOST_REDIRECT;
11128         } else {
11129                 re->ipv6RouteInfo.re_ire_type        = ire->ire_type;
11130         }
11131 
11132         if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11133             (char *)re, (int)sizeof (*re))) {
11134                 ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11135                     (uint_t)sizeof (*re)));
11136         }
11137 
11138         if (gc != NULL) {
11139                 iaes.iae_routeidx = ird->ird_idx;
11140                 iaes.iae_doi = gc->gc_db->gcdb_doi;
11141                 iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11142 
11143                 if (!snmp_append_data2(ird->ird_attrs.lp_head,
11144                     &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11145                         ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11146                             "bytes\n", (uint_t)sizeof (iaes)));
11147                 }
11148         }
11149 
11150         /* bump route index for next pass */
11151         ird->ird_idx++;
11152 
11153         kmem_free(re, sizeof (*re));
11154         if (gcgrp != NULL)
11155                 rw_exit(&gcgrp->gcgrp_rwlock);
11156 }
11157 
11158 /*
11159  * ncec_walk routine to create ipv6NetToMediaEntryTable
11160  */
11161 static int
11162 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11163 {
11164         ill_t                           *ill;
11165         mib2_ipv6NetToMediaEntry_t      ntme;
11166 
11167         ill = ncec->ncec_ill;
11168         /* skip arpce entries, and loopback ncec entries */
11169         if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11170                 return (0);
11171         /*
11172          * Neighbor cache entry attached to IRE with on-link
11173          * destination.
11174          * We report all IPMP groups on ncec_ill which is normally the upper.
11175          */
11176         ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11177         ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11178         ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11179         if (ncec->ncec_lladdr != NULL) {
11180                 bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11181                     ntme.ipv6NetToMediaPhysAddress.o_length);
11182         }
11183         /*
11184          * Note: Returns ND_* states. Should be:
11185          * reachable(1), stale(2), delay(3), probe(4),
11186          * invalid(5), unknown(6)
11187          */
11188         ntme.ipv6NetToMediaState = ncec->ncec_state;
11189         ntme.ipv6NetToMediaLastUpdated = 0;
11190 
11191         /* other(1), dynamic(2), static(3), local(4) */
11192         if (NCE_MYADDR(ncec)) {
11193                 ntme.ipv6NetToMediaType = 4;
11194         } else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11195                 ntme.ipv6NetToMediaType = 1; /* proxy */
11196         } else if (ncec->ncec_flags & NCE_F_STATIC) {
11197                 ntme.ipv6NetToMediaType = 3;
11198         } else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11199                 ntme.ipv6NetToMediaType = 1;
11200         } else {
11201                 ntme.ipv6NetToMediaType = 2;
11202         }
11203 
11204         if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11205             &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11206                 ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11207                     (uint_t)sizeof (ntme)));
11208         }
11209         return (0);
11210 }
11211 
11212 int
11213 nce2ace(ncec_t *ncec)
11214 {
11215         int flags = 0;
11216 
11217         if (NCE_ISREACHABLE(ncec))
11218                 flags |= ACE_F_RESOLVED;
11219         if (ncec->ncec_flags & NCE_F_AUTHORITY)
11220                 flags |= ACE_F_AUTHORITY;
11221         if (ncec->ncec_flags & NCE_F_PUBLISH)
11222                 flags |= ACE_F_PUBLISH;
11223         if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11224                 flags |= ACE_F_PERMANENT;
11225         if (NCE_MYADDR(ncec))
11226                 flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11227         if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11228                 flags |= ACE_F_UNVERIFIED;
11229         if (ncec->ncec_flags & NCE_F_AUTHORITY)
11230                 flags |= ACE_F_AUTHORITY;
11231         if (ncec->ncec_flags & NCE_F_DELAYED)
11232                 flags |= ACE_F_DELAYED;
11233         return (flags);
11234 }
11235 
11236 /*
11237  * ncec_walk routine to create ipNetToMediaEntryTable
11238  */
11239 static int
11240 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11241 {
11242         ill_t                           *ill;
11243         mib2_ipNetToMediaEntry_t        ntme;
11244         const char                      *name = "unknown";
11245         ipaddr_t                        ncec_addr;
11246 
11247         ill = ncec->ncec_ill;
11248         if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11249             ill->ill_net_type == IRE_LOOPBACK)
11250                 return (0);
11251 
11252         /* We report all IPMP groups on ncec_ill which is normally the upper. */
11253         name = ill->ill_name;
11254         /* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11255         if (NCE_MYADDR(ncec)) {
11256                 ntme.ipNetToMediaType = 4;
11257         } else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11258                 ntme.ipNetToMediaType = 1;
11259         } else {
11260                 ntme.ipNetToMediaType = 3;
11261         }
11262         ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11263         bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11264             ntme.ipNetToMediaIfIndex.o_length);
11265 
11266         IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11267         bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11268 
11269         ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11270         ncec_addr = INADDR_BROADCAST;
11271         bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11272             sizeof (ncec_addr));
11273         /*
11274          * map all the flags to the ACE counterpart.
11275          */
11276         ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11277 
11278         ntme.ipNetToMediaPhysAddress.o_length =
11279             MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11280 
11281         if (!NCE_ISREACHABLE(ncec))
11282                 ntme.ipNetToMediaPhysAddress.o_length = 0;
11283         else {
11284                 if (ncec->ncec_lladdr != NULL) {
11285                         bcopy(ncec->ncec_lladdr,
11286                             ntme.ipNetToMediaPhysAddress.o_bytes,
11287                             ntme.ipNetToMediaPhysAddress.o_length);
11288                 }
11289         }
11290 
11291         if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11292             &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11293                 ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11294                     (uint_t)sizeof (ntme)));
11295         }
11296         return (0);
11297 }
11298 
11299 /*
11300  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11301  */
11302 /* ARGSUSED */
11303 int
11304 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11305 {
11306         switch (level) {
11307         case MIB2_IP:
11308         case MIB2_ICMP:
11309                 switch (name) {
11310                 default:
11311                         break;
11312                 }
11313                 return (1);
11314         default:
11315                 return (1);
11316         }
11317 }
11318 
11319 /*
11320  * When there exists both a 64- and 32-bit counter of a particular type
11321  * (i.e., InReceives), only the 64-bit counters are added.
11322  */
11323 void
11324 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11325 {
11326         UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11327         UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11328         UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11329         UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11330         UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11331         UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11332         UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11333         UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11334         UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11335         UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11336         UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11337         UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11338         UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11339         UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11340         UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11341         UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11342         UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11343         UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11344         UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11345         UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11346         UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11347         UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11348             o2->ipIfStatsInWrongIPVersion);
11349         UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11350             o2->ipIfStatsInWrongIPVersion);
11351         UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11352             o2->ipIfStatsOutSwitchIPVersion);
11353         UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11354         UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11355         UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11356             o2->ipIfStatsHCInForwDatagrams);
11357         UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11358         UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11359         UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11360             o2->ipIfStatsHCOutForwDatagrams);
11361         UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11362         UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11363         UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11364         UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11365         UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11366         UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11367         UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11368             o2->ipIfStatsHCOutMcastOctets);
11369         UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11370         UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11371         UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11372         UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11373         UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11374         UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11375         UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11376 }
11377 
11378 void
11379 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11380 {
11381         UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11382         UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11383         UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11384         UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11385         UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11386         UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11387         UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11388         UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11389         UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11390         UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11391             o2->ipv6IfIcmpInRouterSolicits);
11392         UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11393             o2->ipv6IfIcmpInRouterAdvertisements);
11394         UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11395             o2->ipv6IfIcmpInNeighborSolicits);
11396         UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11397             o2->ipv6IfIcmpInNeighborAdvertisements);
11398         UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11399         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11400             o2->ipv6IfIcmpInGroupMembQueries);
11401         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11402             o2->ipv6IfIcmpInGroupMembResponses);
11403         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11404             o2->ipv6IfIcmpInGroupMembReductions);
11405         UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11406         UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11407         UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11408             o2->ipv6IfIcmpOutDestUnreachs);
11409         UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11410             o2->ipv6IfIcmpOutAdminProhibs);
11411         UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11412         UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11413             o2->ipv6IfIcmpOutParmProblems);
11414         UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11415         UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11416         UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11417         UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11418             o2->ipv6IfIcmpOutRouterSolicits);
11419         UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11420             o2->ipv6IfIcmpOutRouterAdvertisements);
11421         UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11422             o2->ipv6IfIcmpOutNeighborSolicits);
11423         UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11424             o2->ipv6IfIcmpOutNeighborAdvertisements);
11425         UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11426         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11427             o2->ipv6IfIcmpOutGroupMembQueries);
11428         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11429             o2->ipv6IfIcmpOutGroupMembResponses);
11430         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11431             o2->ipv6IfIcmpOutGroupMembReductions);
11432         UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11433         UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11434         UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11435             o2->ipv6IfIcmpInBadNeighborAdvertisements);
11436         UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11437             o2->ipv6IfIcmpInBadNeighborSolicitations);
11438         UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11439         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11440             o2->ipv6IfIcmpInGroupMembTotal);
11441         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11442             o2->ipv6IfIcmpInGroupMembBadQueries);
11443         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11444             o2->ipv6IfIcmpInGroupMembBadReports);
11445         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11446             o2->ipv6IfIcmpInGroupMembOurReports);
11447 }
11448 
11449 /*
11450  * Called before the options are updated to check if this packet will
11451  * be source routed from here.
11452  * This routine assumes that the options are well formed i.e. that they
11453  * have already been checked.
11454  */
11455 boolean_t
11456 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11457 {
11458         ipoptp_t        opts;
11459         uchar_t         *opt;
11460         uint8_t         optval;
11461         uint8_t         optlen;
11462         ipaddr_t        dst;
11463 
11464         if (IS_SIMPLE_IPH(ipha)) {
11465                 ip2dbg(("not source routed\n"));
11466                 return (B_FALSE);
11467         }
11468         dst = ipha->ipha_dst;
11469         for (optval = ipoptp_first(&opts, ipha);
11470             optval != IPOPT_EOL;
11471             optval = ipoptp_next(&opts)) {
11472                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11473                 opt = opts.ipoptp_cur;
11474                 optlen = opts.ipoptp_len;
11475                 ip2dbg(("ip_source_routed: opt %d, len %d\n",
11476                     optval, optlen));
11477                 switch (optval) {
11478                         uint32_t off;
11479                 case IPOPT_SSRR:
11480                 case IPOPT_LSRR:
11481                         /*
11482                          * If dst is one of our addresses and there are some
11483                          * entries left in the source route return (true).
11484                          */
11485                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11486                                 ip2dbg(("ip_source_routed: not next"
11487                                     " source route 0x%x\n",
11488                                     ntohl(dst)));
11489                                 return (B_FALSE);
11490                         }
11491                         off = opt[IPOPT_OFFSET];
11492                         off--;
11493                         if (optlen < IP_ADDR_LEN ||
11494                             off > optlen - IP_ADDR_LEN) {
11495                                 /* End of source route */
11496                                 ip1dbg(("ip_source_routed: end of SR\n"));
11497                                 return (B_FALSE);
11498                         }
11499                         return (B_TRUE);
11500                 }
11501         }
11502         ip2dbg(("not source routed\n"));
11503         return (B_FALSE);
11504 }
11505 
11506 /*
11507  * ip_unbind is called by the transports to remove a conn from
11508  * the fanout table.
11509  */
11510 void
11511 ip_unbind(conn_t *connp)
11512 {
11513 
11514         ASSERT(!MUTEX_HELD(&connp->conn_lock));
11515 
11516         if (is_system_labeled() && connp->conn_anon_port) {
11517                 (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11518                     connp->conn_mlp_type, connp->conn_proto,
11519                     ntohs(connp->conn_lport), B_FALSE);
11520                 connp->conn_anon_port = 0;
11521         }
11522         connp->conn_mlp_type = mlptSingle;
11523 
11524         ipcl_hash_remove(connp);
11525 }
11526 
11527 /*
11528  * Used for deciding the MSS size for the upper layer. Thus
11529  * we need to check the outbound policy values in the conn.
11530  */
11531 int
11532 conn_ipsec_length(conn_t *connp)
11533 {
11534         ipsec_latch_t *ipl;
11535 
11536         ipl = connp->conn_latch;
11537         if (ipl == NULL)
11538                 return (0);
11539 
11540         if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11541                 return (0);
11542 
11543         return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11544 }
11545 
11546 /*
11547  * Returns an estimate of the IPsec headers size. This is used if
11548  * we don't want to call into IPsec to get the exact size.
11549  */
11550 int
11551 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11552 {
11553         ipsec_action_t *a;
11554 
11555         if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11556                 return (0);
11557 
11558         a = ixa->ixa_ipsec_action;
11559         if (a == NULL) {
11560                 ASSERT(ixa->ixa_ipsec_policy != NULL);
11561                 a = ixa->ixa_ipsec_policy->ipsp_act;
11562         }
11563         ASSERT(a != NULL);
11564 
11565         return (a->ipa_ovhd);
11566 }
11567 
11568 /*
11569  * If there are any source route options, return the true final
11570  * destination. Otherwise, return the destination.
11571  */
11572 ipaddr_t
11573 ip_get_dst(ipha_t *ipha)
11574 {
11575         ipoptp_t        opts;
11576         uchar_t         *opt;
11577         uint8_t         optval;
11578         uint8_t         optlen;
11579         ipaddr_t        dst;
11580         uint32_t off;
11581 
11582         dst = ipha->ipha_dst;
11583 
11584         if (IS_SIMPLE_IPH(ipha))
11585                 return (dst);
11586 
11587         for (optval = ipoptp_first(&opts, ipha);
11588             optval != IPOPT_EOL;
11589             optval = ipoptp_next(&opts)) {
11590                 opt = opts.ipoptp_cur;
11591                 optlen = opts.ipoptp_len;
11592                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11593                 switch (optval) {
11594                 case IPOPT_SSRR:
11595                 case IPOPT_LSRR:
11596                         off = opt[IPOPT_OFFSET];
11597                         /*
11598                          * If one of the conditions is true, it means
11599                          * end of options and dst already has the right
11600                          * value.
11601                          */
11602                         if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11603                                 off = optlen - IP_ADDR_LEN;
11604                                 bcopy(&opt[off], &dst, IP_ADDR_LEN);
11605                         }
11606                         return (dst);
11607                 default:
11608                         break;
11609                 }
11610         }
11611 
11612         return (dst);
11613 }
11614 
11615 /*
11616  * Outbound IP fragmentation routine.
11617  * Assumes the caller has checked whether or not fragmentation should
11618  * be allowed. Here we copy the DF bit from the header to all the generated
11619  * fragments.
11620  */
11621 int
11622 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11623     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11624     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11625 {
11626         int             i1;
11627         int             hdr_len;
11628         mblk_t          *hdr_mp;
11629         ipha_t          *ipha;
11630         int             ip_data_end;
11631         int             len;
11632         mblk_t          *mp = mp_orig;
11633         int             offset;
11634         ill_t           *ill = nce->nce_ill;
11635         ip_stack_t      *ipst = ill->ill_ipst;
11636         mblk_t          *carve_mp;
11637         uint32_t        frag_flag;
11638         uint_t          priority = mp->b_band;
11639         int             error = 0;
11640 
11641         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11642 
11643         if (pkt_len != msgdsize(mp)) {
11644                 ip0dbg(("Packet length mismatch: %d, %ld\n",
11645                     pkt_len, msgdsize(mp)));
11646                 freemsg(mp);
11647                 return (EINVAL);
11648         }
11649 
11650         if (max_frag == 0) {
11651                 ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11652                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11653                 ip_drop_output("FragFails: zero max_frag", mp, ill);
11654                 freemsg(mp);
11655                 return (EINVAL);
11656         }
11657 
11658         ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11659         ipha = (ipha_t *)mp->b_rptr;
11660         ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11661         frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11662 
11663         /*
11664          * Establish the starting offset.  May not be zero if we are fragging
11665          * a fragment that is being forwarded.
11666          */
11667         offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11668 
11669         /* TODO why is this test needed? */
11670         if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11671                 /* TODO: notify ulp somehow */
11672                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11673                 ip_drop_output("FragFails: bad starting offset", mp, ill);
11674                 freemsg(mp);
11675                 return (EINVAL);
11676         }
11677 
11678         hdr_len = IPH_HDR_LENGTH(ipha);
11679         ipha->ipha_hdr_checksum = 0;
11680 
11681         /*
11682          * Establish the number of bytes maximum per frag, after putting
11683          * in the header.
11684          */
11685         len = (max_frag - hdr_len) & ~7;
11686 
11687         /* Get a copy of the header for the trailing frags */
11688         hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11689             mp);
11690         if (hdr_mp == NULL) {
11691                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11692                 ip_drop_output("FragFails: no hdr_mp", mp, ill);
11693                 freemsg(mp);
11694                 return (ENOBUFS);
11695         }
11696 
11697         /* Store the starting offset, with the MoreFrags flag. */
11698         i1 = offset | IPH_MF | frag_flag;
11699         ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11700 
11701         /* Establish the ending byte offset, based on the starting offset. */
11702         offset <<= 3;
11703         ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11704 
11705         /* Store the length of the first fragment in the IP header. */
11706         i1 = len + hdr_len;
11707         ASSERT(i1 <= IP_MAXPACKET);
11708         ipha->ipha_length = htons((uint16_t)i1);
11709 
11710         /*
11711          * Compute the IP header checksum for the first frag.  We have to
11712          * watch out that we stop at the end of the header.
11713          */
11714         ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11715 
11716         /*
11717          * Now carve off the first frag.  Note that this will include the
11718          * original IP header.
11719          */
11720         if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11721                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11722                 ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11723                 freeb(hdr_mp);
11724                 freemsg(mp_orig);
11725                 return (ENOBUFS);
11726         }
11727 
11728         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11729 
11730         error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11731             ixa_cookie);
11732         if (error != 0 && error != EWOULDBLOCK) {
11733                 /* No point in sending the other fragments */
11734                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11735                 ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11736                 freeb(hdr_mp);
11737                 freemsg(mp_orig);
11738                 return (error);
11739         }
11740 
11741         /* No need to redo state machine in loop */
11742         ixaflags &= ~IXAF_REACH_CONF;
11743 
11744         /* Advance the offset to the second frag starting point. */
11745         offset += len;
11746         /*
11747          * Update hdr_len from the copied header - there might be less options
11748          * in the later fragments.
11749          */
11750         hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11751         /* Loop until done. */
11752         for (;;) {
11753                 uint16_t        offset_and_flags;
11754                 uint16_t        ip_len;
11755 
11756                 if (ip_data_end - offset > len) {
11757                         /*
11758                          * Carve off the appropriate amount from the original
11759                          * datagram.
11760                          */
11761                         if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11762                                 mp = NULL;
11763                                 break;
11764                         }
11765                         /*
11766                          * More frags after this one.  Get another copy
11767                          * of the header.
11768                          */
11769                         if (carve_mp->b_datap->db_ref == 1 &&
11770                             hdr_mp->b_wptr - hdr_mp->b_rptr <
11771                             carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11772                                 /* Inline IP header */
11773                                 carve_mp->b_rptr -= hdr_mp->b_wptr -
11774                                     hdr_mp->b_rptr;
11775                                 bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11776                                     hdr_mp->b_wptr - hdr_mp->b_rptr);
11777                                 mp = carve_mp;
11778                         } else {
11779                                 if (!(mp = copyb(hdr_mp))) {
11780                                         freemsg(carve_mp);
11781                                         break;
11782                                 }
11783                                 /* Get priority marking, if any. */
11784                                 mp->b_band = priority;
11785                                 mp->b_cont = carve_mp;
11786                         }
11787                         ipha = (ipha_t *)mp->b_rptr;
11788                         offset_and_flags = IPH_MF;
11789                 } else {
11790                         /*
11791                          * Last frag.  Consume the header. Set len to
11792                          * the length of this last piece.
11793                          */
11794                         len = ip_data_end - offset;
11795 
11796                         /*
11797                          * Carve off the appropriate amount from the original
11798                          * datagram.
11799                          */
11800                         if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11801                                 mp = NULL;
11802                                 break;
11803                         }
11804                         if (carve_mp->b_datap->db_ref == 1 &&
11805                             hdr_mp->b_wptr - hdr_mp->b_rptr <
11806                             carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11807                                 /* Inline IP header */
11808                                 carve_mp->b_rptr -= hdr_mp->b_wptr -
11809                                     hdr_mp->b_rptr;
11810                                 bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11811                                     hdr_mp->b_wptr - hdr_mp->b_rptr);
11812                                 mp = carve_mp;
11813                                 freeb(hdr_mp);
11814                                 hdr_mp = mp;
11815                         } else {
11816                                 mp = hdr_mp;
11817                                 /* Get priority marking, if any. */
11818                                 mp->b_band = priority;
11819                                 mp->b_cont = carve_mp;
11820                         }
11821                         ipha = (ipha_t *)mp->b_rptr;
11822                         /* A frag of a frag might have IPH_MF non-zero */
11823                         offset_and_flags =
11824                             ntohs(ipha->ipha_fragment_offset_and_flags) &
11825                             IPH_MF;
11826                 }
11827                 offset_and_flags |= (uint16_t)(offset >> 3);
11828                 offset_and_flags |= (uint16_t)frag_flag;
11829                 /* Store the offset and flags in the IP header. */
11830                 ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11831 
11832                 /* Store the length in the IP header. */
11833                 ip_len = (uint16_t)(len + hdr_len);
11834                 ipha->ipha_length = htons(ip_len);
11835 
11836                 /*
11837                  * Set the IP header checksum.  Note that mp is just
11838                  * the header, so this is easy to pass to ip_csum.
11839                  */
11840                 ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11841 
11842                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11843 
11844                 error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11845                     nolzid, ixa_cookie);
11846                 /* All done if we just consumed the hdr_mp. */
11847                 if (mp == hdr_mp) {
11848                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11849                         return (error);
11850                 }
11851                 if (error != 0 && error != EWOULDBLOCK) {
11852                         DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11853                             mblk_t *, hdr_mp);
11854                         /* No point in sending the other fragments */
11855                         break;
11856                 }
11857 
11858                 /* Otherwise, advance and loop. */
11859                 offset += len;
11860         }
11861         /* Clean up following allocation failure. */
11862         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11863         ip_drop_output("FragFails: loop ended", NULL, ill);
11864         if (mp != hdr_mp)
11865                 freeb(hdr_mp);
11866         if (mp != mp_orig)
11867                 freemsg(mp_orig);
11868         return (error);
11869 }
11870 
11871 /*
11872  * Copy the header plus those options which have the copy bit set
11873  */
11874 static mblk_t *
11875 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11876     mblk_t *src)
11877 {
11878         mblk_t  *mp;
11879         uchar_t *up;
11880 
11881         /*
11882          * Quick check if we need to look for options without the copy bit
11883          * set
11884          */
11885         mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11886         if (!mp)
11887                 return (mp);
11888         mp->b_rptr += ipst->ips_ip_wroff_extra;
11889         if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11890                 bcopy(rptr, mp->b_rptr, hdr_len);
11891                 mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11892                 return (mp);
11893         }
11894         up  = mp->b_rptr;
11895         bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11896         up += IP_SIMPLE_HDR_LENGTH;
11897         rptr += IP_SIMPLE_HDR_LENGTH;
11898         hdr_len -= IP_SIMPLE_HDR_LENGTH;
11899         while (hdr_len > 0) {
11900                 uint32_t optval;
11901                 uint32_t optlen;
11902 
11903                 optval = *rptr;
11904                 if (optval == IPOPT_EOL)
11905                         break;
11906                 if (optval == IPOPT_NOP)
11907                         optlen = 1;
11908                 else
11909                         optlen = rptr[1];
11910                 if (optval & IPOPT_COPY) {
11911                         bcopy(rptr, up, optlen);
11912                         up += optlen;
11913                 }
11914                 rptr += optlen;
11915                 hdr_len -= optlen;
11916         }
11917         /*
11918          * Make sure that we drop an even number of words by filling
11919          * with EOL to the next word boundary.
11920          */
11921         for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11922             hdr_len & 0x3; hdr_len++)
11923                 *up++ = IPOPT_EOL;
11924         mp->b_wptr = up;
11925         /* Update header length */
11926         mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11927         return (mp);
11928 }
11929 
11930 /*
11931  * Update any source route, record route, or timestamp options when
11932  * sending a packet back to ourselves.
11933  * Check that we are at end of strict source route.
11934  * The options have been sanity checked by ip_output_options().
11935  */
11936 void
11937 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11938 {
11939         ipoptp_t        opts;
11940         uchar_t         *opt;
11941         uint8_t         optval;
11942         uint8_t         optlen;
11943         ipaddr_t        dst;
11944         uint32_t        ts;
11945         timestruc_t     now;
11946 
11947         for (optval = ipoptp_first(&opts, ipha);
11948             optval != IPOPT_EOL;
11949             optval = ipoptp_next(&opts)) {
11950                 opt = opts.ipoptp_cur;
11951                 optlen = opts.ipoptp_len;
11952                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11953                 switch (optval) {
11954                         uint32_t off;
11955                 case IPOPT_SSRR:
11956                 case IPOPT_LSRR:
11957                         off = opt[IPOPT_OFFSET];
11958                         off--;
11959                         if (optlen < IP_ADDR_LEN ||
11960                             off > optlen - IP_ADDR_LEN) {
11961                                 /* End of source route */
11962                                 break;
11963                         }
11964                         /*
11965                          * This will only happen if two consecutive entries
11966                          * in the source route contains our address or if
11967                          * it is a packet with a loose source route which
11968                          * reaches us before consuming the whole source route
11969                          */
11970 
11971                         if (optval == IPOPT_SSRR) {
11972                                 return;
11973                         }
11974                         /*
11975                          * Hack: instead of dropping the packet truncate the
11976                          * source route to what has been used by filling the
11977                          * rest with IPOPT_NOP.
11978                          */
11979                         opt[IPOPT_OLEN] = (uint8_t)off;
11980                         while (off < optlen) {
11981                                 opt[off++] = IPOPT_NOP;
11982                         }
11983                         break;
11984                 case IPOPT_RR:
11985                         off = opt[IPOPT_OFFSET];
11986                         off--;
11987                         if (optlen < IP_ADDR_LEN ||
11988                             off > optlen - IP_ADDR_LEN) {
11989                                 /* No more room - ignore */
11990                                 ip1dbg((
11991                                     "ip_output_local_options: end of RR\n"));
11992                                 break;
11993                         }
11994                         dst = htonl(INADDR_LOOPBACK);
11995                         bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11996                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11997                         break;
11998                 case IPOPT_TS:
11999                         /* Insert timestamp if there is romm */
12000                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12001                         case IPOPT_TS_TSONLY:
12002                                 off = IPOPT_TS_TIMELEN;
12003                                 break;
12004                         case IPOPT_TS_PRESPEC:
12005                         case IPOPT_TS_PRESPEC_RFC791:
12006                                 /* Verify that the address matched */
12007                                 off = opt[IPOPT_OFFSET] - 1;
12008                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12009                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12010                                         /* Not for us */
12011                                         break;
12012                                 }
12013                                 /* FALLTHRU */
12014                         case IPOPT_TS_TSANDADDR:
12015                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12016                                 break;
12017                         default:
12018                                 /*
12019                                  * ip_*put_options should have already
12020                                  * dropped this packet.
12021                                  */
12022                                 cmn_err(CE_PANIC, "ip_output_local_options: "
12023                                     "unknown IT - bug in ip_output_options?\n");
12024                                 return; /* Keep "lint" happy */
12025                         }
12026                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12027                                 /* Increase overflow counter */
12028                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12029                                 opt[IPOPT_POS_OV_FLG] = (uint8_t)
12030                                     (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12031                                     (off << 4);
12032                                 break;
12033                         }
12034                         off = opt[IPOPT_OFFSET] - 1;
12035                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12036                         case IPOPT_TS_PRESPEC:
12037                         case IPOPT_TS_PRESPEC_RFC791:
12038                         case IPOPT_TS_TSANDADDR:
12039                                 dst = htonl(INADDR_LOOPBACK);
12040                                 bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12041                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12042                                 /* FALLTHRU */
12043                         case IPOPT_TS_TSONLY:
12044                                 off = opt[IPOPT_OFFSET] - 1;
12045                                 /* Compute # of milliseconds since midnight */
12046                                 gethrestime(&now);
12047                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12048                                     NSEC2MSEC(now.tv_nsec);
12049                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12050                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12051                                 break;
12052                         }
12053                         break;
12054                 }
12055         }
12056 }
12057 
12058 /*
12059  * Prepend an M_DATA fastpath header, and if none present prepend a
12060  * DL_UNITDATA_REQ. Frees the mblk on failure.
12061  *
12062  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12063  * If there is a change to them, the nce will be deleted (condemned) and
12064  * a new nce_t will be created when packets are sent. Thus we need no locks
12065  * to access those fields.
12066  *
12067  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12068  * we place b_band in dl_priority.dl_max.
12069  */
12070 static mblk_t *
12071 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12072 {
12073         uint_t  hlen;
12074         mblk_t *mp1;
12075         uint_t  priority;
12076         uchar_t *rptr;
12077 
12078         rptr = mp->b_rptr;
12079 
12080         ASSERT(DB_TYPE(mp) == M_DATA);
12081         priority = mp->b_band;
12082 
12083         ASSERT(nce != NULL);
12084         if ((mp1 = nce->nce_fp_mp) != NULL) {
12085                 hlen = MBLKL(mp1);
12086                 /*
12087                  * Check if we have enough room to prepend fastpath
12088                  * header
12089                  */
12090                 if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12091                         rptr -= hlen;
12092                         bcopy(mp1->b_rptr, rptr, hlen);
12093                         /*
12094                          * Set the b_rptr to the start of the link layer
12095                          * header
12096                          */
12097                         mp->b_rptr = rptr;
12098                         return (mp);
12099                 }
12100                 mp1 = copyb(mp1);
12101                 if (mp1 == NULL) {
12102                         ill_t *ill = nce->nce_ill;
12103 
12104                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12105                         ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12106                         freemsg(mp);
12107                         return (NULL);
12108                 }
12109                 mp1->b_band = priority;
12110                 mp1->b_cont = mp;
12111                 DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12112                 DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12113                 DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12114                 DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12115                 DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12116                 DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12117                 /*
12118                  * XXX disable ICK_VALID and compute checksum
12119                  * here; can happen if nce_fp_mp changes and
12120                  * it can't be copied now due to insufficient
12121                  * space. (unlikely, fp mp can change, but it
12122                  * does not increase in length)
12123                  */
12124                 return (mp1);
12125         }
12126         mp1 = copyb(nce->nce_dlur_mp);
12127 
12128         if (mp1 == NULL) {
12129                 ill_t *ill = nce->nce_ill;
12130 
12131                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12132                 ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12133                 freemsg(mp);
12134                 return (NULL);
12135         }
12136         mp1->b_cont = mp;
12137         if (priority != 0) {
12138                 mp1->b_band = priority;
12139                 ((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12140                     priority;
12141         }
12142         return (mp1);
12143 }
12144 
12145 /*
12146  * Finish the outbound IPsec processing. This function is called from
12147  * ipsec_out_process() if the IPsec packet was processed
12148  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12149  * asynchronously.
12150  *
12151  * This is common to IPv4 and IPv6.
12152  */
12153 int
12154 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12155 {
12156         iaflags_t       ixaflags = ixa->ixa_flags;
12157         uint_t          pktlen;
12158 
12159 
12160         /* AH/ESP don't update ixa_pktlen when they modify the packet */
12161         if (ixaflags & IXAF_IS_IPV4) {
12162                 ipha_t          *ipha = (ipha_t *)mp->b_rptr;
12163 
12164                 ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12165                 pktlen = ntohs(ipha->ipha_length);
12166         } else {
12167                 ip6_t           *ip6h = (ip6_t *)mp->b_rptr;
12168 
12169                 ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12170                 pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12171         }
12172 
12173         /*
12174          * We release any hard reference on the SAs here to make
12175          * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12176          * on the SAs.
12177          * If in the future we want the hard latching of the SAs in the
12178          * ip_xmit_attr_t then we should remove this.
12179          */
12180         if (ixa->ixa_ipsec_esp_sa != NULL) {
12181                 IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12182                 ixa->ixa_ipsec_esp_sa = NULL;
12183         }
12184         if (ixa->ixa_ipsec_ah_sa != NULL) {
12185                 IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12186                 ixa->ixa_ipsec_ah_sa = NULL;
12187         }
12188 
12189         /* Do we need to fragment? */
12190         if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12191             pktlen > ixa->ixa_fragsize) {
12192                 if (ixaflags & IXAF_IS_IPV4) {
12193                         ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12194                         /*
12195                          * We check for the DF case in ipsec_out_process
12196                          * hence this only handles the non-DF case.
12197                          */
12198                         return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12199                             pktlen, ixa->ixa_fragsize,
12200                             ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12201                             ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12202                             &ixa->ixa_cookie));
12203                 } else {
12204                         mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12205                         if (mp == NULL) {
12206                                 /* MIB and ip_drop_output already done */
12207                                 return (ENOMEM);
12208                         }
12209                         pktlen += sizeof (ip6_frag_t);
12210                         if (pktlen > ixa->ixa_fragsize) {
12211                                 return (ip_fragment_v6(mp, ixa->ixa_nce,
12212                                     ixa->ixa_flags, pktlen,
12213                                     ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12214                                     ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12215                                     ixa->ixa_postfragfn, &ixa->ixa_cookie));
12216                         }
12217                 }
12218         }
12219         return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12220             pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12221             ixa->ixa_no_loop_zoneid, NULL));
12222 }
12223 
12224 /*
12225  * Finish the inbound IPsec processing. This function is called from
12226  * ipsec_out_process() if the IPsec packet was processed
12227  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12228  * asynchronously.
12229  *
12230  * This is common to IPv4 and IPv6.
12231  */
12232 void
12233 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12234 {
12235         iaflags_t       iraflags = ira->ira_flags;
12236 
12237         /* Length might have changed */
12238         if (iraflags & IRAF_IS_IPV4) {
12239                 ipha_t          *ipha = (ipha_t *)mp->b_rptr;
12240 
12241                 ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12242                 ira->ira_pktlen = ntohs(ipha->ipha_length);
12243                 ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12244                 ira->ira_protocol = ipha->ipha_protocol;
12245 
12246                 ip_fanout_v4(mp, ipha, ira);
12247         } else {
12248                 ip6_t           *ip6h = (ip6_t *)mp->b_rptr;
12249                 uint8_t         *nexthdrp;
12250 
12251                 ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12252                 ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12253                 if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12254                     &nexthdrp)) {
12255                         /* Malformed packet */
12256                         BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12257                         ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12258                         freemsg(mp);
12259                         return;
12260                 }
12261                 ira->ira_protocol = *nexthdrp;
12262                 ip_fanout_v6(mp, ip6h, ira);
12263         }
12264 }
12265 
12266 /*
12267  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12268  *
12269  * If this function returns B_TRUE, the requested SA's have been filled
12270  * into the ixa_ipsec_*_sa pointers.
12271  *
12272  * If the function returns B_FALSE, the packet has been "consumed", most
12273  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12274  *
12275  * The SA references created by the protocol-specific "select"
12276  * function will be released in ip_output_post_ipsec.
12277  */
12278 static boolean_t
12279 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12280 {
12281         boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12282         ipsec_policy_t *pp;
12283         ipsec_action_t *ap;
12284 
12285         ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12286         ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12287             (ixa->ixa_ipsec_action != NULL));
12288 
12289         ap = ixa->ixa_ipsec_action;
12290         if (ap == NULL) {
12291                 pp = ixa->ixa_ipsec_policy;
12292                 ASSERT(pp != NULL);
12293                 ap = pp->ipsp_act;
12294                 ASSERT(ap != NULL);
12295         }
12296 
12297         /*
12298          * We have an action.  now, let's select SA's.
12299          * A side effect of setting ixa_ipsec_*_sa is that it will
12300          * be cached in the conn_t.
12301          */
12302         if (ap->ipa_want_esp) {
12303                 if (ixa->ixa_ipsec_esp_sa == NULL) {
12304                         need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12305                             IPPROTO_ESP);
12306                 }
12307                 ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12308         }
12309 
12310         if (ap->ipa_want_ah) {
12311                 if (ixa->ixa_ipsec_ah_sa == NULL) {
12312                         need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12313                             IPPROTO_AH);
12314                 }
12315                 ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12316                 /*
12317                  * The ESP and AH processing order needs to be preserved
12318                  * when both protocols are required (ESP should be applied
12319                  * before AH for an outbound packet). Force an ESP ACQUIRE
12320                  * when both ESP and AH are required, and an AH ACQUIRE
12321                  * is needed.
12322                  */
12323                 if (ap->ipa_want_esp && need_ah_acquire)
12324                         need_esp_acquire = B_TRUE;
12325         }
12326 
12327         /*
12328          * Send an ACQUIRE (extended, regular, or both) if we need one.
12329          * Release SAs that got referenced, but will not be used until we
12330          * acquire _all_ of the SAs we need.
12331          */
12332         if (need_ah_acquire || need_esp_acquire) {
12333                 if (ixa->ixa_ipsec_ah_sa != NULL) {
12334                         IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12335                         ixa->ixa_ipsec_ah_sa = NULL;
12336                 }
12337                 if (ixa->ixa_ipsec_esp_sa != NULL) {
12338                         IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12339                         ixa->ixa_ipsec_esp_sa = NULL;
12340                 }
12341 
12342                 sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12343                 return (B_FALSE);
12344         }
12345 
12346         return (B_TRUE);
12347 }
12348 
12349 /*
12350  * Handle IPsec output processing.
12351  * This function is only entered once for a given packet.
12352  * We try to do things synchronously, but if we need to have user-level
12353  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12354  * will be completed
12355  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12356  *  - when asynchronous ESP is done it will do AH
12357  *
12358  * In all cases we come back in ip_output_post_ipsec() to fragment and
12359  * send out the packet.
12360  */
12361 int
12362 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12363 {
12364         ill_t           *ill = ixa->ixa_nce->nce_ill;
12365         ip_stack_t      *ipst = ixa->ixa_ipst;
12366         ipsec_stack_t   *ipss;
12367         ipsec_policy_t  *pp;
12368         ipsec_action_t  *ap;
12369 
12370         ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12371 
12372         ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12373             (ixa->ixa_ipsec_action != NULL));
12374 
12375         ipss = ipst->ips_netstack->netstack_ipsec;
12376         if (!ipsec_loaded(ipss)) {
12377                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12378                 ip_drop_packet(mp, B_TRUE, ill,
12379                     DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12380                     &ipss->ipsec_dropper);
12381                 return (ENOTSUP);
12382         }
12383 
12384         ap = ixa->ixa_ipsec_action;
12385         if (ap == NULL) {
12386                 pp = ixa->ixa_ipsec_policy;
12387                 ASSERT(pp != NULL);
12388                 ap = pp->ipsp_act;
12389                 ASSERT(ap != NULL);
12390         }
12391 
12392         /* Handle explicit drop action and bypass. */
12393         switch (ap->ipa_act.ipa_type) {
12394         case IPSEC_ACT_DISCARD:
12395         case IPSEC_ACT_REJECT:
12396                 ip_drop_packet(mp, B_FALSE, ill,
12397                     DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12398                 return (EHOSTUNREACH);  /* IPsec policy failure */
12399         case IPSEC_ACT_BYPASS:
12400                 return (ip_output_post_ipsec(mp, ixa));
12401         }
12402 
12403         /*
12404          * The order of processing is first insert a IP header if needed.
12405          * Then insert the ESP header and then the AH header.
12406          */
12407         if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12408                 /*
12409                  * First get the outer IP header before sending
12410                  * it to ESP.
12411                  */
12412                 ipha_t *oipha, *iipha;
12413                 mblk_t *outer_mp, *inner_mp;
12414 
12415                 if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12416                         (void) mi_strlog(ill->ill_rq, 0,
12417                             SL_ERROR|SL_TRACE|SL_CONSOLE,
12418                             "ipsec_out_process: "
12419                             "Self-Encapsulation failed: Out of memory\n");
12420                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12421                         ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12422                         freemsg(mp);
12423                         return (ENOBUFS);
12424                 }
12425                 inner_mp = mp;
12426                 ASSERT(inner_mp->b_datap->db_type == M_DATA);
12427                 oipha = (ipha_t *)outer_mp->b_rptr;
12428                 iipha = (ipha_t *)inner_mp->b_rptr;
12429                 *oipha = *iipha;
12430                 outer_mp->b_wptr += sizeof (ipha_t);
12431                 oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12432                     sizeof (ipha_t));
12433                 oipha->ipha_protocol = IPPROTO_ENCAP;
12434                 oipha->ipha_version_and_hdr_length =
12435                     IP_SIMPLE_HDR_VERSION;
12436                 oipha->ipha_hdr_checksum = 0;
12437                 oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12438                 outer_mp->b_cont = inner_mp;
12439                 mp = outer_mp;
12440 
12441                 ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12442         }
12443 
12444         /* If we need to wait for a SA then we can't return any errno */
12445         if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12446             (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12447             !ipsec_out_select_sa(mp, ixa))
12448                 return (0);
12449 
12450         /*
12451          * By now, we know what SA's to use.  Toss over to ESP & AH
12452          * to do the heavy lifting.
12453          */
12454         if (ap->ipa_want_esp) {
12455                 ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12456 
12457                 mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12458                 if (mp == NULL) {
12459                         /*
12460                          * Either it failed or is pending. In the former case
12461                          * ipIfStatsInDiscards was increased.
12462                          */
12463                         return (0);
12464                 }
12465         }
12466 
12467         if (ap->ipa_want_ah) {
12468                 ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12469 
12470                 mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12471                 if (mp == NULL) {
12472                         /*
12473                          * Either it failed or is pending. In the former case
12474                          * ipIfStatsInDiscards was increased.
12475                          */
12476                         return (0);
12477                 }
12478         }
12479         /*
12480          * We are done with IPsec processing. Send it over
12481          * the wire.
12482          */
12483         return (ip_output_post_ipsec(mp, ixa));
12484 }
12485 
12486 /*
12487  * ioctls that go through a down/up sequence may need to wait for the down
12488  * to complete. This involves waiting for the ire and ipif refcnts to go down
12489  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12490  */
12491 /* ARGSUSED */
12492 void
12493 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12494 {
12495         struct iocblk *iocp;
12496         mblk_t *mp1;
12497         ip_ioctl_cmd_t *ipip;
12498         int err;
12499         sin_t   *sin;
12500         struct lifreq *lifr;
12501         struct ifreq *ifr;
12502 
12503         iocp = (struct iocblk *)mp->b_rptr;
12504         ASSERT(ipsq != NULL);
12505         /* Existence of mp1 verified in ip_wput_nondata */
12506         mp1 = mp->b_cont->b_cont;
12507         ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12508         if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12509                 /*
12510                  * Special case where ipx_current_ipif is not set:
12511                  * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12512                  * We are here as were not able to complete the operation in
12513                  * ipif_set_values because we could not become exclusive on
12514                  * the new ipsq.
12515                  */
12516                 ill_t *ill = q->q_ptr;
12517                 ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12518         }
12519         ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12520 
12521         if (ipip->ipi_cmd_type == IF_CMD) {
12522                 /* This a old style SIOC[GS]IF* command */
12523                 ifr = (struct ifreq *)mp1->b_rptr;
12524                 sin = (sin_t *)&ifr->ifr_addr;
12525         } else if (ipip->ipi_cmd_type == LIF_CMD) {
12526                 /* This a new style SIOC[GS]LIF* command */
12527                 lifr = (struct lifreq *)mp1->b_rptr;
12528                 sin = (sin_t *)&lifr->lifr_addr;
12529         } else {
12530                 sin = NULL;
12531         }
12532 
12533         err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12534             q, mp, ipip, mp1->b_rptr);
12535 
12536         DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12537             int, ipip->ipi_cmd,
12538             ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12539             ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12540 
12541         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12542 }
12543 
12544 /*
12545  * ioctl processing
12546  *
12547  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12548  * the ioctl command in the ioctl tables, determines the copyin data size
12549  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12550  *
12551  * ioctl processing then continues when the M_IOCDATA makes its way down to
12552  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12553  * associated 'conn' is refheld till the end of the ioctl and the general
12554  * ioctl processing function ip_process_ioctl() is called to extract the
12555  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12556  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12557  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12558  * is used to extract the ioctl's arguments.
12559  *
12560  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12561  * so goes thru the serialization primitive ipsq_try_enter. Then the
12562  * appropriate function to handle the ioctl is called based on the entry in
12563  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12564  * which also refreleases the 'conn' that was refheld at the start of the
12565  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12566  *
12567  * Many exclusive ioctls go thru an internal down up sequence as part of
12568  * the operation. For example an attempt to change the IP address of an
12569  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12570  * does all the cleanup such as deleting all ires that use this address.
12571  * Then we need to wait till all references to the interface go away.
12572  */
12573 void
12574 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12575 {
12576         struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12577         ip_ioctl_cmd_t *ipip = arg;
12578         ip_extract_func_t *extract_funcp;
12579         ill_t *ill;
12580         cmd_info_t ci;
12581         int err;
12582         boolean_t entered_ipsq = B_FALSE;
12583 
12584         ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12585 
12586         if (ipip == NULL)
12587                 ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12588 
12589         /*
12590          * SIOCLIFADDIF needs to go thru a special path since the
12591          * ill may not exist yet. This happens in the case of lo0
12592          * which is created using this ioctl.
12593          */
12594         if (ipip->ipi_cmd == SIOCLIFADDIF) {
12595                 err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12596                 DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12597                     int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12598                 ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12599                 return;
12600         }
12601 
12602         ci.ci_ipif = NULL;
12603         switch (ipip->ipi_cmd_type) {
12604         case MISC_CMD:
12605         case MSFILT_CMD:
12606                 /*
12607                  * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12608                  */
12609                 if (ipip->ipi_cmd == IF_UNITSEL) {
12610                         /* ioctl comes down the ill */
12611                         ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12612                         ipif_refhold(ci.ci_ipif);
12613                 }
12614                 err = 0;
12615                 ci.ci_sin = NULL;
12616                 ci.ci_sin6 = NULL;
12617                 ci.ci_lifr = NULL;
12618                 extract_funcp = NULL;
12619                 break;
12620 
12621         case IF_CMD:
12622         case LIF_CMD:
12623                 extract_funcp = ip_extract_lifreq;
12624                 break;
12625 
12626         case ARP_CMD:
12627         case XARP_CMD:
12628                 extract_funcp = ip_extract_arpreq;
12629                 break;
12630 
12631         default:
12632                 ASSERT(0);
12633         }
12634 
12635         if (extract_funcp != NULL) {
12636                 err = (*extract_funcp)(q, mp, ipip, &ci);
12637                 if (err != 0) {
12638                         DTRACE_PROBE4(ipif__ioctl,
12639                             char *, "ip_process_ioctl finish err",
12640                             int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12641                         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12642                         return;
12643                 }
12644 
12645                 /*
12646                  * All of the extraction functions return a refheld ipif.
12647                  */
12648                 ASSERT(ci.ci_ipif != NULL);
12649         }
12650 
12651         if (!(ipip->ipi_flags & IPI_WR)) {
12652                 /*
12653                  * A return value of EINPROGRESS means the ioctl is
12654                  * either queued and waiting for some reason or has
12655                  * already completed.
12656                  */
12657                 err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12658                     ci.ci_lifr);
12659                 if (ci.ci_ipif != NULL) {
12660                         DTRACE_PROBE4(ipif__ioctl,
12661                             char *, "ip_process_ioctl finish RD",
12662                             int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12663                             ipif_t *, ci.ci_ipif);
12664                         ipif_refrele(ci.ci_ipif);
12665                 } else {
12666                         DTRACE_PROBE4(ipif__ioctl,
12667                             char *, "ip_process_ioctl finish RD",
12668                             int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12669                 }
12670                 ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12671                 return;
12672         }
12673 
12674         ASSERT(ci.ci_ipif != NULL);
12675 
12676         /*
12677          * If ipsq is non-NULL, we are already being called exclusively
12678          */
12679         ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12680         if (ipsq == NULL) {
12681                 ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12682                     NEW_OP, B_TRUE);
12683                 if (ipsq == NULL) {
12684                         ipif_refrele(ci.ci_ipif);
12685                         return;
12686                 }
12687                 entered_ipsq = B_TRUE;
12688         }
12689         /*
12690          * Release the ipif so that ipif_down and friends that wait for
12691          * references to go away are not misled about the current ipif_refcnt
12692          * values. We are writer so we can access the ipif even after releasing
12693          * the ipif.
12694          */
12695         ipif_refrele(ci.ci_ipif);
12696 
12697         ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12698 
12699         /*
12700          * We need to cache the ill_t that we're going to use as the argument
12701          * to the ipif-ioctl DTrace probe (below) because the ci_ipif can be
12702          * blown away by calling ipi_func.
12703          */
12704         ill = ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill;
12705 
12706         /*
12707          * A return value of EINPROGRESS means the ioctl is
12708          * either queued and waiting for some reason or has
12709          * already completed.
12710          */
12711         err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12712 
12713         DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12714             int, ipip->ipi_cmd, ill_t *, ill, ipif_t *, ci.ci_ipif);
12715         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12716 
12717         if (entered_ipsq)
12718                 ipsq_exit(ipsq);
12719 }
12720 
12721 /*
12722  * Complete the ioctl. Typically ioctls use the mi package and need to
12723  * do mi_copyout/mi_copy_done.
12724  */
12725 void
12726 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12727 {
12728         conn_t  *connp = NULL;
12729 
12730         if (err == EINPROGRESS)
12731                 return;
12732 
12733         if (CONN_Q(q)) {
12734                 connp = Q_TO_CONN(q);
12735                 ASSERT(connp->conn_ref >= 2);
12736         }
12737 
12738         switch (mode) {
12739         case COPYOUT:
12740                 if (err == 0)
12741                         mi_copyout(q, mp);
12742                 else
12743                         mi_copy_done(q, mp, err);
12744                 break;
12745 
12746         case NO_COPYOUT:
12747                 mi_copy_done(q, mp, err);
12748                 break;
12749 
12750         default:
12751                 ASSERT(mode == CONN_CLOSE);     /* aborted through CONN_CLOSE */
12752                 break;
12753         }
12754 
12755         /*
12756          * The conn refhold and ioctlref placed on the conn at the start of the
12757          * ioctl are released here.
12758          */
12759         if (connp != NULL) {
12760                 CONN_DEC_IOCTLREF(connp);
12761                 CONN_OPER_PENDING_DONE(connp);
12762         }
12763 
12764         if (ipsq != NULL)
12765                 ipsq_current_finish(ipsq);
12766 }
12767 
12768 /* Handles all non data messages */
12769 void
12770 ip_wput_nondata(queue_t *q, mblk_t *mp)
12771 {
12772         mblk_t          *mp1;
12773         struct iocblk   *iocp;
12774         ip_ioctl_cmd_t  *ipip;
12775         conn_t          *connp;
12776         cred_t          *cr;
12777         char            *proto_str;
12778 
12779         if (CONN_Q(q))
12780                 connp = Q_TO_CONN(q);
12781         else
12782                 connp = NULL;
12783 
12784         switch (DB_TYPE(mp)) {
12785         case M_IOCTL:
12786                 /*
12787                  * IOCTL processing begins in ip_sioctl_copyin_setup which
12788                  * will arrange to copy in associated control structures.
12789                  */
12790                 ip_sioctl_copyin_setup(q, mp);
12791                 return;
12792         case M_IOCDATA:
12793                 /*
12794                  * Ensure that this is associated with one of our trans-
12795                  * parent ioctls.  If it's not ours, discard it if we're
12796                  * running as a driver, or pass it on if we're a module.
12797                  */
12798                 iocp = (struct iocblk *)mp->b_rptr;
12799                 ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12800                 if (ipip == NULL) {
12801                         if (q->q_next == NULL) {
12802                                 goto nak;
12803                         } else {
12804                                 putnext(q, mp);
12805                         }
12806                         return;
12807                 }
12808                 if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12809                         /*
12810                          * The ioctl is one we recognise, but is not consumed
12811                          * by IP as a module and we are a module, so we drop
12812                          */
12813                         goto nak;
12814                 }
12815 
12816                 /* IOCTL continuation following copyin or copyout. */
12817                 if (mi_copy_state(q, mp, NULL) == -1) {
12818                         /*
12819                          * The copy operation failed.  mi_copy_state already
12820                          * cleaned up, so we're out of here.
12821                          */
12822                         return;
12823                 }
12824                 /*
12825                  * If we just completed a copy in, we become writer and
12826                  * continue processing in ip_sioctl_copyin_done.  If it
12827                  * was a copy out, we call mi_copyout again.  If there is
12828                  * nothing more to copy out, it will complete the IOCTL.
12829                  */
12830                 if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12831                         if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12832                                 mi_copy_done(q, mp, EPROTO);
12833                                 return;
12834                         }
12835                         /*
12836                          * Check for cases that need more copying.  A return
12837                          * value of 0 means a second copyin has been started,
12838                          * so we return; a return value of 1 means no more
12839                          * copying is needed, so we continue.
12840                          */
12841                         if (ipip->ipi_cmd_type == MSFILT_CMD &&
12842                             MI_COPY_COUNT(mp) == 1) {
12843                                 if (ip_copyin_msfilter(q, mp) == 0)
12844                                         return;
12845                         }
12846                         /*
12847                          * Refhold the conn, till the ioctl completes. This is
12848                          * needed in case the ioctl ends up in the pending mp
12849                          * list. Every mp in the ipx_pending_mp list must have
12850                          * a refhold on the conn to resume processing. The
12851                          * refhold is released when the ioctl completes
12852                          * (whether normally or abnormally). An ioctlref is also
12853                          * placed on the conn to prevent TCP from removing the
12854                          * queue needed to send the ioctl reply back.
12855                          * In all cases ip_ioctl_finish is called to finish
12856                          * the ioctl and release the refholds.
12857                          */
12858                         if (connp != NULL) {
12859                                 /* This is not a reentry */
12860                                 CONN_INC_REF(connp);
12861                                 CONN_INC_IOCTLREF(connp);
12862                         } else {
12863                                 if (!(ipip->ipi_flags & IPI_MODOK)) {
12864                                         mi_copy_done(q, mp, EINVAL);
12865                                         return;
12866                                 }
12867                         }
12868 
12869                         ip_process_ioctl(NULL, q, mp, ipip);
12870 
12871                 } else {
12872                         mi_copyout(q, mp);
12873                 }
12874                 return;
12875 
12876         case M_IOCNAK:
12877                 /*
12878                  * The only way we could get here is if a resolver didn't like
12879                  * an IOCTL we sent it.  This shouldn't happen.
12880                  */
12881                 (void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12882                     "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12883                     ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12884                 freemsg(mp);
12885                 return;
12886         case M_IOCACK:
12887                 /* /dev/ip shouldn't see this */
12888                 goto nak;
12889         case M_FLUSH:
12890                 if (*mp->b_rptr & FLUSHW)
12891                         flushq(q, FLUSHALL);
12892                 if (q->q_next) {
12893                         putnext(q, mp);
12894                         return;
12895                 }
12896                 if (*mp->b_rptr & FLUSHR) {
12897                         *mp->b_rptr &= ~FLUSHW;
12898                         qreply(q, mp);
12899                         return;
12900                 }
12901                 freemsg(mp);
12902                 return;
12903         case M_CTL:
12904                 break;
12905         case M_PROTO:
12906         case M_PCPROTO:
12907                 /*
12908                  * The only PROTO messages we expect are SNMP-related.
12909                  */
12910                 switch (((union T_primitives *)mp->b_rptr)->type) {
12911                 case T_SVR4_OPTMGMT_REQ:
12912                         ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12913                             "flags %x\n",
12914                             ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12915 
12916                         if (connp == NULL) {
12917                                 proto_str = "T_SVR4_OPTMGMT_REQ";
12918                                 goto protonak;
12919                         }
12920 
12921                         /*
12922                          * All Solaris components should pass a db_credp
12923                          * for this TPI message, hence we ASSERT.
12924                          * But in case there is some other M_PROTO that looks
12925                          * like a TPI message sent by some other kernel
12926                          * component, we check and return an error.
12927                          */
12928                         cr = msg_getcred(mp, NULL);
12929                         ASSERT(cr != NULL);
12930                         if (cr == NULL) {
12931                                 mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12932                                 if (mp != NULL)
12933                                         qreply(q, mp);
12934                                 return;
12935                         }
12936 
12937                         if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12938                                 proto_str = "Bad SNMPCOM request?";
12939                                 goto protonak;
12940                         }
12941                         return;
12942                 default:
12943                         ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12944                             (int)*(uint_t *)mp->b_rptr));
12945                         freemsg(mp);
12946                         return;
12947                 }
12948         default:
12949                 break;
12950         }
12951         if (q->q_next) {
12952                 putnext(q, mp);
12953         } else
12954                 freemsg(mp);
12955         return;
12956 
12957 nak:
12958         iocp->ioc_error = EINVAL;
12959         mp->b_datap->db_type = M_IOCNAK;
12960         iocp->ioc_count = 0;
12961         qreply(q, mp);
12962         return;
12963 
12964 protonak:
12965         cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12966         if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12967                 qreply(q, mp);
12968 }
12969 
12970 /*
12971  * Process IP options in an outbound packet.  Verify that the nexthop in a
12972  * strict source route is onlink.
12973  * Returns non-zero if something fails in which case an ICMP error has been
12974  * sent and mp freed.
12975  *
12976  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12977  */
12978 int
12979 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12980 {
12981         ipoptp_t        opts;
12982         uchar_t         *opt;
12983         uint8_t         optval;
12984         uint8_t         optlen;
12985         ipaddr_t        dst;
12986         intptr_t        code = 0;
12987         ire_t           *ire;
12988         ip_stack_t      *ipst = ixa->ixa_ipst;
12989         ip_recv_attr_t  iras;
12990 
12991         ip2dbg(("ip_output_options\n"));
12992 
12993         dst = ipha->ipha_dst;
12994         for (optval = ipoptp_first(&opts, ipha);
12995             optval != IPOPT_EOL;
12996             optval = ipoptp_next(&opts)) {
12997                 opt = opts.ipoptp_cur;
12998                 optlen = opts.ipoptp_len;
12999                 ip2dbg(("ip_output_options: opt %d, len %d\n",
13000                     optval, optlen));
13001                 switch (optval) {
13002                         uint32_t off;
13003                 case IPOPT_SSRR:
13004                 case IPOPT_LSRR:
13005                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13006                                 ip1dbg((
13007                                     "ip_output_options: bad option offset\n"));
13008                                 code = (char *)&opt[IPOPT_OLEN] -
13009                                     (char *)ipha;
13010                                 goto param_prob;
13011                         }
13012                         off = opt[IPOPT_OFFSET];
13013                         ip1dbg(("ip_output_options: next hop 0x%x\n",
13014                             ntohl(dst)));
13015                         /*
13016                          * For strict: verify that dst is directly
13017                          * reachable.
13018                          */
13019                         if (optval == IPOPT_SSRR) {
13020                                 ire = ire_ftable_lookup_v4(dst, 0, 0,
13021                                     IRE_INTERFACE, NULL, ALL_ZONES,
13022                                     ixa->ixa_tsl,
13023                                     MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13024                                     NULL);
13025                                 if (ire == NULL) {
13026                                         ip1dbg(("ip_output_options: SSRR not"
13027                                             " directly reachable: 0x%x\n",
13028                                             ntohl(dst)));
13029                                         goto bad_src_route;
13030                                 }
13031                                 ire_refrele(ire);
13032                         }
13033                         break;
13034                 case IPOPT_RR:
13035                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13036                                 ip1dbg((
13037                                     "ip_output_options: bad option offset\n"));
13038                                 code = (char *)&opt[IPOPT_OLEN] -
13039                                     (char *)ipha;
13040                                 goto param_prob;
13041                         }
13042                         break;
13043                 case IPOPT_TS:
13044                         /*
13045                          * Verify that length >=5 and that there is either
13046                          * room for another timestamp or that the overflow
13047                          * counter is not maxed out.
13048                          */
13049                         code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13050                         if (optlen < IPOPT_MINLEN_IT) {
13051                                 goto param_prob;
13052                         }
13053                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13054                                 ip1dbg((
13055                                     "ip_output_options: bad option offset\n"));
13056                                 code = (char *)&opt[IPOPT_OFFSET] -
13057                                     (char *)ipha;
13058                                 goto param_prob;
13059                         }
13060                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13061                         case IPOPT_TS_TSONLY:
13062                                 off = IPOPT_TS_TIMELEN;
13063                                 break;
13064                         case IPOPT_TS_TSANDADDR:
13065                         case IPOPT_TS_PRESPEC:
13066                         case IPOPT_TS_PRESPEC_RFC791:
13067                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13068                                 break;
13069                         default:
13070                                 code = (char *)&opt[IPOPT_POS_OV_FLG] -
13071                                     (char *)ipha;
13072                                 goto param_prob;
13073                         }
13074                         if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13075                             (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13076                                 /*
13077                                  * No room and the overflow counter is 15
13078                                  * already.
13079                                  */
13080                                 goto param_prob;
13081                         }
13082                         break;
13083                 }
13084         }
13085 
13086         if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13087                 return (0);
13088 
13089         ip1dbg(("ip_output_options: error processing IP options."));
13090         code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13091 
13092 param_prob:
13093         bzero(&iras, sizeof (iras));
13094         iras.ira_ill = iras.ira_rill = ill;
13095         iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13096         iras.ira_rifindex = iras.ira_ruifindex;
13097         iras.ira_flags = IRAF_IS_IPV4;
13098 
13099         ip_drop_output("ip_output_options", mp, ill);
13100         icmp_param_problem(mp, (uint8_t)code, &iras);
13101         ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13102         return (-1);
13103 
13104 bad_src_route:
13105         bzero(&iras, sizeof (iras));
13106         iras.ira_ill = iras.ira_rill = ill;
13107         iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13108         iras.ira_rifindex = iras.ira_ruifindex;
13109         iras.ira_flags = IRAF_IS_IPV4;
13110 
13111         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13112         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13113         ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13114         return (-1);
13115 }
13116 
13117 /*
13118  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13119  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13120  * thru /etc/system.
13121  */
13122 #define CONN_MAXDRAINCNT        64
13123 
13124 static void
13125 conn_drain_init(ip_stack_t *ipst)
13126 {
13127         int i, j;
13128         idl_tx_list_t *itl_tx;
13129 
13130         ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13131 
13132         if ((ipst->ips_conn_drain_list_cnt == 0) ||
13133             (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13134                 /*
13135                  * Default value of the number of drainers is the
13136                  * number of cpus, subject to maximum of 8 drainers.
13137                  */
13138                 if (boot_max_ncpus != -1)
13139                         ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13140                 else
13141                         ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13142         }
13143 
13144         ipst->ips_idl_tx_list =
13145             kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13146         for (i = 0; i < TX_FANOUT_SIZE; i++) {
13147                 itl_tx =  &ipst->ips_idl_tx_list[i];
13148                 itl_tx->txl_drain_list =
13149                     kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13150                     sizeof (idl_t), KM_SLEEP);
13151                 mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13152                 for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13153                         mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13154                             MUTEX_DEFAULT, NULL);
13155                         itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13156                 }
13157         }
13158 }
13159 
13160 static void
13161 conn_drain_fini(ip_stack_t *ipst)
13162 {
13163         int i;
13164         idl_tx_list_t *itl_tx;
13165 
13166         for (i = 0; i < TX_FANOUT_SIZE; i++) {
13167                 itl_tx =  &ipst->ips_idl_tx_list[i];
13168                 kmem_free(itl_tx->txl_drain_list,
13169                     ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13170         }
13171         kmem_free(ipst->ips_idl_tx_list,
13172             TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13173         ipst->ips_idl_tx_list = NULL;
13174 }
13175 
13176 /*
13177  * Flow control has blocked us from proceeding.  Insert the given conn in one
13178  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13179  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13180  * will call conn_walk_drain().  See the flow control notes at the top of this
13181  * file for more details.
13182  */
13183 void
13184 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13185 {
13186         idl_t   *idl = tx_list->txl_drain_list;
13187         uint_t  index;
13188         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
13189 
13190         mutex_enter(&connp->conn_lock);
13191         if (connp->conn_state_flags & CONN_CLOSING) {
13192                 /*
13193                  * The conn is closing as a result of which CONN_CLOSING
13194                  * is set. Return.
13195                  */
13196                 mutex_exit(&connp->conn_lock);
13197                 return;
13198         } else if (connp->conn_idl == NULL) {
13199                 /*
13200                  * Assign the next drain list round robin. We dont' use
13201                  * a lock, and thus it may not be strictly round robin.
13202                  * Atomicity of load/stores is enough to make sure that
13203                  * conn_drain_list_index is always within bounds.
13204                  */
13205                 index = tx_list->txl_drain_index;
13206                 ASSERT(index < ipst->ips_conn_drain_list_cnt);
13207                 connp->conn_idl = &tx_list->txl_drain_list[index];
13208                 index++;
13209                 if (index == ipst->ips_conn_drain_list_cnt)
13210                         index = 0;
13211                 tx_list->txl_drain_index = index;
13212         } else {
13213                 ASSERT(connp->conn_idl->idl_itl == tx_list);
13214         }
13215         mutex_exit(&connp->conn_lock);
13216 
13217         idl = connp->conn_idl;
13218         mutex_enter(&idl->idl_lock);
13219         if ((connp->conn_drain_prev != NULL) ||
13220             (connp->conn_state_flags & CONN_CLOSING)) {
13221                 /*
13222                  * The conn is either already in the drain list or closing.
13223                  * (We needed to check for CONN_CLOSING again since close can
13224                  * sneak in between dropping conn_lock and acquiring idl_lock.)
13225                  */
13226                 mutex_exit(&idl->idl_lock);
13227                 return;
13228         }
13229 
13230         /*
13231          * The conn is not in the drain list. Insert it at the
13232          * tail of the drain list. The drain list is circular
13233          * and doubly linked. idl_conn points to the 1st element
13234          * in the list.
13235          */
13236         if (idl->idl_conn == NULL) {
13237                 idl->idl_conn = connp;
13238                 connp->conn_drain_next = connp;
13239                 connp->conn_drain_prev = connp;
13240         } else {
13241                 conn_t *head = idl->idl_conn;
13242 
13243                 connp->conn_drain_next = head;
13244                 connp->conn_drain_prev = head->conn_drain_prev;
13245                 head->conn_drain_prev->conn_drain_next = connp;
13246                 head->conn_drain_prev = connp;
13247         }
13248         /*
13249          * For non streams based sockets assert flow control.
13250          */
13251         conn_setqfull(connp, NULL);
13252         mutex_exit(&idl->idl_lock);
13253 }
13254 
13255 static void
13256 conn_drain_remove(conn_t *connp)
13257 {
13258         idl_t *idl = connp->conn_idl;
13259 
13260         if (idl != NULL) {
13261                 /*
13262                  * Remove ourself from the drain list.
13263                  */
13264                 if (connp->conn_drain_next == connp) {
13265                         /* Singleton in the list */
13266                         ASSERT(connp->conn_drain_prev == connp);
13267                         idl->idl_conn = NULL;
13268                 } else {
13269                         connp->conn_drain_prev->conn_drain_next =
13270                             connp->conn_drain_next;
13271                         connp->conn_drain_next->conn_drain_prev =
13272                             connp->conn_drain_prev;
13273                         if (idl->idl_conn == connp)
13274                                 idl->idl_conn = connp->conn_drain_next;
13275                 }
13276 
13277                 /*
13278                  * NOTE: because conn_idl is associated with a specific drain
13279                  * list which in turn is tied to the index the TX ring
13280                  * (txl_cookie) hashes to, and because the TX ring can change
13281                  * over the lifetime of the conn_t, we must clear conn_idl so
13282                  * a subsequent conn_drain_insert() will set conn_idl again
13283                  * based on the latest txl_cookie.
13284                  */
13285                 connp->conn_idl = NULL;
13286         }
13287         connp->conn_drain_next = NULL;
13288         connp->conn_drain_prev = NULL;
13289 
13290         conn_clrqfull(connp, NULL);
13291         /*
13292          * For streams based sockets open up flow control.
13293          */
13294         if (!IPCL_IS_NONSTR(connp))
13295                 enableok(connp->conn_wq);
13296 }
13297 
13298 /*
13299  * This conn is closing, and we are called from ip_close. OR
13300  * this conn is draining because flow-control on the ill has been relieved.
13301  *
13302  * We must also need to remove conn's on this idl from the list, and also
13303  * inform the sockfs upcalls about the change in flow-control.
13304  */
13305 static void
13306 conn_drain(conn_t *connp, boolean_t closing)
13307 {
13308         idl_t *idl;
13309         conn_t *next_connp;
13310 
13311         /*
13312          * connp->conn_idl is stable at this point, and no lock is needed
13313          * to check it. If we are called from ip_close, close has already
13314          * set CONN_CLOSING, thus freezing the value of conn_idl, and
13315          * called us only because conn_idl is non-null. If we are called thru
13316          * service, conn_idl could be null, but it cannot change because
13317          * service is single-threaded per queue, and there cannot be another
13318          * instance of service trying to call conn_drain_insert on this conn
13319          * now.
13320          */
13321         ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13322 
13323         /*
13324          * If the conn doesn't exist or is not on a drain list, bail.
13325          */
13326         if (connp == NULL || connp->conn_idl == NULL ||
13327             connp->conn_drain_prev == NULL) {
13328                 return;
13329         }
13330 
13331         idl = connp->conn_idl;
13332         ASSERT(MUTEX_HELD(&idl->idl_lock));
13333 
13334         if (!closing) {
13335                 next_connp = connp->conn_drain_next;
13336                 while (next_connp != connp) {
13337                         conn_t *delconnp = next_connp;
13338 
13339                         next_connp = next_connp->conn_drain_next;
13340                         conn_drain_remove(delconnp);
13341                 }
13342                 ASSERT(connp->conn_drain_next == idl->idl_conn);
13343         }
13344         conn_drain_remove(connp);
13345 }
13346 
13347 /*
13348  * Write service routine. Shared perimeter entry point.
13349  * The device queue's messages has fallen below the low water mark and STREAMS
13350  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13351  * each waiting conn.
13352  */
13353 void
13354 ip_wsrv(queue_t *q)
13355 {
13356         ill_t   *ill;
13357 
13358         ill = (ill_t *)q->q_ptr;
13359         if (ill->ill_state_flags == 0) {
13360                 ip_stack_t *ipst = ill->ill_ipst;
13361 
13362                 /*
13363                  * The device flow control has opened up.
13364                  * Walk through conn drain lists and qenable the
13365                  * first conn in each list. This makes sense only
13366                  * if the stream is fully plumbed and setup.
13367                  * Hence the ill_state_flags check above.
13368                  */
13369                 ip1dbg(("ip_wsrv: walking\n"));
13370                 conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13371                 enableok(ill->ill_wq);
13372         }
13373 }
13374 
13375 /*
13376  * Callback to disable flow control in IP.
13377  *
13378  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13379  * is enabled.
13380  *
13381  * When MAC_TX() is not able to send any more packets, dld sets its queue
13382  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13383  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13384  * function and wakes up corresponding mac worker threads, which in turn
13385  * calls this callback function, and disables flow control.
13386  */
13387 void
13388 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13389 {
13390         ill_t *ill = (ill_t *)arg;
13391         ip_stack_t *ipst = ill->ill_ipst;
13392         idl_tx_list_t *idl_txl;
13393 
13394         idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13395         mutex_enter(&idl_txl->txl_lock);
13396         /* add code to to set a flag to indicate idl_txl is enabled */
13397         conn_walk_drain(ipst, idl_txl);
13398         mutex_exit(&idl_txl->txl_lock);
13399 }
13400 
13401 /*
13402  * Flow control has been relieved and STREAMS has backenabled us; drain
13403  * all the conn lists on `tx_list'.
13404  */
13405 static void
13406 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13407 {
13408         int i;
13409         idl_t *idl;
13410 
13411         IP_STAT(ipst, ip_conn_walk_drain);
13412 
13413         for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13414                 idl = &tx_list->txl_drain_list[i];
13415                 mutex_enter(&idl->idl_lock);
13416                 conn_drain(idl->idl_conn, B_FALSE);
13417                 mutex_exit(&idl->idl_lock);
13418         }
13419 }
13420 
13421 /*
13422  * Determine if the ill and multicast aspects of that packets
13423  * "matches" the conn.
13424  */
13425 boolean_t
13426 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13427 {
13428         ill_t           *ill = ira->ira_rill;
13429         zoneid_t        zoneid = ira->ira_zoneid;
13430         uint_t          in_ifindex;
13431         ipaddr_t        dst, src;
13432 
13433         dst = ipha->ipha_dst;
13434         src = ipha->ipha_src;
13435 
13436         /*
13437          * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13438          * unicast, broadcast and multicast reception to
13439          * conn_incoming_ifindex.
13440          * conn_wantpacket is called for unicast, broadcast and
13441          * multicast packets.
13442          */
13443         in_ifindex = connp->conn_incoming_ifindex;
13444 
13445         /* mpathd can bind to the under IPMP interface, which we allow */
13446         if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13447                 if (!IS_UNDER_IPMP(ill))
13448                         return (B_FALSE);
13449 
13450                 if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13451                         return (B_FALSE);
13452         }
13453 
13454         if (!IPCL_ZONE_MATCH(connp, zoneid))
13455                 return (B_FALSE);
13456 
13457         if (!(ira->ira_flags & IRAF_MULTICAST))
13458                 return (B_TRUE);
13459 
13460         if (connp->conn_multi_router) {
13461                 /* multicast packet and multicast router socket: send up */
13462                 return (B_TRUE);
13463         }
13464 
13465         if (ipha->ipha_protocol == IPPROTO_PIM ||
13466             ipha->ipha_protocol == IPPROTO_RSVP)
13467                 return (B_TRUE);
13468 
13469         return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13470 }
13471 
13472 void
13473 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13474 {
13475         if (IPCL_IS_NONSTR(connp)) {
13476                 (*connp->conn_upcalls->su_txq_full)
13477                     (connp->conn_upper_handle, B_TRUE);
13478                 if (flow_stopped != NULL)
13479                         *flow_stopped = B_TRUE;
13480         } else {
13481                 queue_t *q = connp->conn_wq;
13482 
13483                 ASSERT(q != NULL);
13484                 if (!(q->q_flag & QFULL)) {
13485                         mutex_enter(QLOCK(q));
13486                         if (!(q->q_flag & QFULL)) {
13487                                 /* still need to set QFULL */
13488                                 q->q_flag |= QFULL;
13489                                 /* set flow_stopped to true under QLOCK */
13490                                 if (flow_stopped != NULL)
13491                                         *flow_stopped = B_TRUE;
13492                                 mutex_exit(QLOCK(q));
13493                         } else {
13494                                 /* flow_stopped is left unchanged */
13495                                 mutex_exit(QLOCK(q));
13496                         }
13497                 }
13498         }
13499 }
13500 
13501 void
13502 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13503 {
13504         if (IPCL_IS_NONSTR(connp)) {
13505                 (*connp->conn_upcalls->su_txq_full)
13506                     (connp->conn_upper_handle, B_FALSE);
13507                 if (flow_stopped != NULL)
13508                         *flow_stopped = B_FALSE;
13509         } else {
13510                 queue_t *q = connp->conn_wq;
13511 
13512                 ASSERT(q != NULL);
13513                 if (q->q_flag & QFULL) {
13514                         mutex_enter(QLOCK(q));
13515                         if (q->q_flag & QFULL) {
13516                                 q->q_flag &= ~QFULL;
13517                                 /* set flow_stopped to false under QLOCK */
13518                                 if (flow_stopped != NULL)
13519                                         *flow_stopped = B_FALSE;
13520                                 mutex_exit(QLOCK(q));
13521                                 if (q->q_flag & QWANTW)
13522                                         qbackenable(q, 0);
13523                         } else {
13524                                 /* flow_stopped is left unchanged */
13525                                 mutex_exit(QLOCK(q));
13526                         }
13527                 }
13528         }
13529 
13530         mutex_enter(&connp->conn_lock);
13531         connp->conn_blocked = B_FALSE;
13532         mutex_exit(&connp->conn_lock);
13533 }
13534 
13535 /*
13536  * Return the length in bytes of the IPv4 headers (base header, label, and
13537  * other IP options) that will be needed based on the
13538  * ip_pkt_t structure passed by the caller.
13539  *
13540  * The returned length does not include the length of the upper level
13541  * protocol (ULP) header.
13542  * The caller needs to check that the length doesn't exceed the max for IPv4.
13543  */
13544 int
13545 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13546 {
13547         int len;
13548 
13549         len = IP_SIMPLE_HDR_LENGTH;
13550         if (ipp->ipp_fields & IPPF_LABEL_V4) {
13551                 ASSERT(ipp->ipp_label_len_v4 != 0);
13552                 /* We need to round up here */
13553                 len += (ipp->ipp_label_len_v4 + 3) & ~3;
13554         }
13555 
13556         if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13557                 ASSERT(ipp->ipp_ipv4_options_len != 0);
13558                 ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13559                 len += ipp->ipp_ipv4_options_len;
13560         }
13561         return (len);
13562 }
13563 
13564 /*
13565  * All-purpose routine to build an IPv4 header with options based
13566  * on the abstract ip_pkt_t.
13567  *
13568  * The caller has to set the source and destination address as well as
13569  * ipha_length. The caller has to massage any source route and compensate
13570  * for the ULP pseudo-header checksum due to the source route.
13571  */
13572 void
13573 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13574     uint8_t protocol)
13575 {
13576         ipha_t  *ipha = (ipha_t *)buf;
13577         uint8_t *cp;
13578 
13579         /* Initialize IPv4 header */
13580         ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13581         ipha->ipha_length = 0;       /* Caller will set later */
13582         ipha->ipha_ident = 0;
13583         ipha->ipha_fragment_offset_and_flags = 0;
13584         ipha->ipha_ttl = ipp->ipp_unicast_hops;
13585         ipha->ipha_protocol = protocol;
13586         ipha->ipha_hdr_checksum = 0;
13587 
13588         if ((ipp->ipp_fields & IPPF_ADDR) &&
13589             IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13590                 ipha->ipha_src = ipp->ipp_addr_v4;
13591 
13592         cp = (uint8_t *)&ipha[1];
13593         if (ipp->ipp_fields & IPPF_LABEL_V4) {
13594                 ASSERT(ipp->ipp_label_len_v4 != 0);
13595                 bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13596                 cp += ipp->ipp_label_len_v4;
13597                 /* We need to round up here */
13598                 while ((uintptr_t)cp & 0x3) {
13599                         *cp++ = IPOPT_NOP;
13600                 }
13601         }
13602 
13603         if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13604                 ASSERT(ipp->ipp_ipv4_options_len != 0);
13605                 ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13606                 bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13607                 cp += ipp->ipp_ipv4_options_len;
13608         }
13609         ipha->ipha_version_and_hdr_length =
13610             (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13611 
13612         ASSERT((int)(cp - buf) == buf_len);
13613 }
13614 
13615 /* Allocate the private structure */
13616 static int
13617 ip_priv_alloc(void **bufp)
13618 {
13619         void    *buf;
13620 
13621         if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13622                 return (ENOMEM);
13623 
13624         *bufp = buf;
13625         return (0);
13626 }
13627 
13628 /* Function to delete the private structure */
13629 void
13630 ip_priv_free(void *buf)
13631 {
13632         ASSERT(buf != NULL);
13633         kmem_free(buf, sizeof (ip_priv_t));
13634 }
13635 
13636 /*
13637  * The entry point for IPPF processing.
13638  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13639  * routine just returns.
13640  *
13641  * When called, ip_process generates an ipp_packet_t structure
13642  * which holds the state information for this packet and invokes the
13643  * the classifier (via ipp_packet_process). The classification, depending on
13644  * configured filters, results in a list of actions for this packet. Invoking
13645  * an action may cause the packet to be dropped, in which case we return NULL.
13646  * proc indicates the callout position for
13647  * this packet and ill is the interface this packet arrived on or will leave
13648  * on (inbound and outbound resp.).
13649  *
13650  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13651  * on the ill corrsponding to the destination IP address.
13652  */
13653 mblk_t *
13654 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13655 {
13656         ip_priv_t       *priv;
13657         ipp_action_id_t aid;
13658         int             rc = 0;
13659         ipp_packet_t    *pp;
13660 
13661         /* If the classifier is not loaded, return  */
13662         if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13663                 return (mp);
13664         }
13665 
13666         ASSERT(mp != NULL);
13667 
13668         /* Allocate the packet structure */
13669         rc = ipp_packet_alloc(&pp, "ip", aid);
13670         if (rc != 0)
13671                 goto drop;
13672 
13673         /* Allocate the private structure */
13674         rc = ip_priv_alloc((void **)&priv);
13675         if (rc != 0) {
13676                 ipp_packet_free(pp);
13677                 goto drop;
13678         }
13679         priv->proc = proc;
13680         priv->ill_index = ill_get_upper_ifindex(rill);
13681 
13682         ipp_packet_set_private(pp, priv, ip_priv_free);
13683         ipp_packet_set_data(pp, mp);
13684 
13685         /* Invoke the classifier */
13686         rc = ipp_packet_process(&pp);
13687         if (pp != NULL) {
13688                 mp = ipp_packet_get_data(pp);
13689                 ipp_packet_free(pp);
13690                 if (rc != 0)
13691                         goto drop;
13692                 return (mp);
13693         } else {
13694                 /* No mp to trace in ip_drop_input/ip_drop_output  */
13695                 mp = NULL;
13696         }
13697 drop:
13698         if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13699                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13700                 ip_drop_input("ip_process", mp, ill);
13701         } else {
13702                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13703                 ip_drop_output("ip_process", mp, ill);
13704         }
13705         freemsg(mp);
13706         return (NULL);
13707 }
13708 
13709 /*
13710  * Propagate a multicast group membership operation (add/drop) on
13711  * all the interfaces crossed by the related multirt routes.
13712  * The call is considered successful if the operation succeeds
13713  * on at least one interface.
13714  *
13715  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13716  * multicast addresses with the ire argument being the first one.
13717  * We walk the bucket to find all the of those.
13718  *
13719  * Common to IPv4 and IPv6.
13720  */
13721 static int
13722 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13723     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13724     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13725     mcast_record_t fmode, const in6_addr_t *v6src)
13726 {
13727         ire_t           *ire_gw;
13728         irb_t           *irb;
13729         int             ifindex;
13730         int             error = 0;
13731         int             result;
13732         ip_stack_t      *ipst = ire->ire_ipst;
13733         ipaddr_t        group;
13734         boolean_t       isv6;
13735         int             match_flags;
13736 
13737         if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13738                 IN6_V4MAPPED_TO_IPADDR(v6group, group);
13739                 isv6 = B_FALSE;
13740         } else {
13741                 isv6 = B_TRUE;
13742         }
13743 
13744         irb = ire->ire_bucket;
13745         ASSERT(irb != NULL);
13746 
13747         result = 0;
13748         irb_refhold(irb);
13749         for (; ire != NULL; ire = ire->ire_next) {
13750                 if ((ire->ire_flags & RTF_MULTIRT) == 0)
13751                         continue;
13752 
13753                 /* We handle -ifp routes by matching on the ill if set */
13754                 match_flags = MATCH_IRE_TYPE;
13755                 if (ire->ire_ill != NULL)
13756                         match_flags |= MATCH_IRE_ILL;
13757 
13758                 if (isv6) {
13759                         if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13760                                 continue;
13761 
13762                         ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13763                             0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13764                             match_flags, 0, ipst, NULL);
13765                 } else {
13766                         if (ire->ire_addr != group)
13767                                 continue;
13768 
13769                         ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13770                             0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13771                             match_flags, 0, ipst, NULL);
13772                 }
13773                 /* No interface route exists for the gateway; skip this ire. */
13774                 if (ire_gw == NULL)
13775                         continue;
13776                 if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13777                         ire_refrele(ire_gw);
13778                         continue;
13779                 }
13780                 ASSERT(ire_gw->ire_ill != NULL);     /* IRE_INTERFACE */
13781                 ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13782 
13783                 /*
13784                  * The operation is considered a success if
13785                  * it succeeds at least once on any one interface.
13786                  */
13787                 error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13788                     fmode, v6src);
13789                 if (error == 0)
13790                         result = CGTP_MCAST_SUCCESS;
13791 
13792                 ire_refrele(ire_gw);
13793         }
13794         irb_refrele(irb);
13795         /*
13796          * Consider the call as successful if we succeeded on at least
13797          * one interface. Otherwise, return the last encountered error.
13798          */
13799         return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13800 }
13801 
13802 /*
13803  * Return the expected CGTP hooks version number.
13804  */
13805 int
13806 ip_cgtp_filter_supported(void)
13807 {
13808         return (ip_cgtp_filter_rev);
13809 }
13810 
13811 /*
13812  * CGTP hooks can be registered by invoking this function.
13813  * Checks that the version number matches.
13814  */
13815 int
13816 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13817 {
13818         netstack_t *ns;
13819         ip_stack_t *ipst;
13820 
13821         if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13822                 return (ENOTSUP);
13823 
13824         ns = netstack_find_by_stackid(stackid);
13825         if (ns == NULL)
13826                 return (EINVAL);
13827         ipst = ns->netstack_ip;
13828         ASSERT(ipst != NULL);
13829 
13830         if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13831                 netstack_rele(ns);
13832                 return (EALREADY);
13833         }
13834 
13835         ipst->ips_ip_cgtp_filter_ops = ops;
13836 
13837         ill_set_inputfn_all(ipst);
13838 
13839         netstack_rele(ns);
13840         return (0);
13841 }
13842 
13843 /*
13844  * CGTP hooks can be unregistered by invoking this function.
13845  * Returns ENXIO if there was no registration.
13846  * Returns EBUSY if the ndd variable has not been turned off.
13847  */
13848 int
13849 ip_cgtp_filter_unregister(netstackid_t stackid)
13850 {
13851         netstack_t *ns;
13852         ip_stack_t *ipst;
13853 
13854         ns = netstack_find_by_stackid(stackid);
13855         if (ns == NULL)
13856                 return (EINVAL);
13857         ipst = ns->netstack_ip;
13858         ASSERT(ipst != NULL);
13859 
13860         if (ipst->ips_ip_cgtp_filter) {
13861                 netstack_rele(ns);
13862                 return (EBUSY);
13863         }
13864 
13865         if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13866                 netstack_rele(ns);
13867                 return (ENXIO);
13868         }
13869         ipst->ips_ip_cgtp_filter_ops = NULL;
13870 
13871         ill_set_inputfn_all(ipst);
13872 
13873         netstack_rele(ns);
13874         return (0);
13875 }
13876 
13877 /*
13878  * Check whether there is a CGTP filter registration.
13879  * Returns non-zero if there is a registration, otherwise returns zero.
13880  * Note: returns zero if bad stackid.
13881  */
13882 int
13883 ip_cgtp_filter_is_registered(netstackid_t stackid)
13884 {
13885         netstack_t *ns;
13886         ip_stack_t *ipst;
13887         int ret;
13888 
13889         ns = netstack_find_by_stackid(stackid);
13890         if (ns == NULL)
13891                 return (0);
13892         ipst = ns->netstack_ip;
13893         ASSERT(ipst != NULL);
13894 
13895         if (ipst->ips_ip_cgtp_filter_ops != NULL)
13896                 ret = 1;
13897         else
13898                 ret = 0;
13899 
13900         netstack_rele(ns);
13901         return (ret);
13902 }
13903 
13904 static int
13905 ip_squeue_switch(int val)
13906 {
13907         int rval;
13908 
13909         switch (val) {
13910         case IP_SQUEUE_ENTER_NODRAIN:
13911                 rval = SQ_NODRAIN;
13912                 break;
13913         case IP_SQUEUE_ENTER:
13914                 rval = SQ_PROCESS;
13915                 break;
13916         case IP_SQUEUE_FILL:
13917         default:
13918                 rval = SQ_FILL;
13919                 break;
13920         }
13921         return (rval);
13922 }
13923 
13924 static void *
13925 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13926 {
13927         kstat_t *ksp;
13928 
13929         ip_stat_t template = {
13930                 { "ip_udp_fannorm",             KSTAT_DATA_UINT64 },
13931                 { "ip_udp_fanmb",               KSTAT_DATA_UINT64 },
13932                 { "ip_recv_pullup",             KSTAT_DATA_UINT64 },
13933                 { "ip_db_ref",                  KSTAT_DATA_UINT64 },
13934                 { "ip_notaligned",              KSTAT_DATA_UINT64 },
13935                 { "ip_multimblk",               KSTAT_DATA_UINT64 },
13936                 { "ip_opt",                     KSTAT_DATA_UINT64 },
13937                 { "ipsec_proto_ahesp",          KSTAT_DATA_UINT64 },
13938                 { "ip_conn_flputbq",            KSTAT_DATA_UINT64 },
13939                 { "ip_conn_walk_drain",         KSTAT_DATA_UINT64 },
13940                 { "ip_out_sw_cksum",            KSTAT_DATA_UINT64 },
13941                 { "ip_out_sw_cksum_bytes",      KSTAT_DATA_UINT64 },
13942                 { "ip_in_sw_cksum",             KSTAT_DATA_UINT64 },
13943                 { "ip_ire_reclaim_calls",       KSTAT_DATA_UINT64 },
13944                 { "ip_ire_reclaim_deleted",     KSTAT_DATA_UINT64 },
13945                 { "ip_nce_reclaim_calls",       KSTAT_DATA_UINT64 },
13946                 { "ip_nce_reclaim_deleted",     KSTAT_DATA_UINT64 },
13947                 { "ip_dce_reclaim_calls",       KSTAT_DATA_UINT64 },
13948                 { "ip_dce_reclaim_deleted",     KSTAT_DATA_UINT64 },
13949                 { "ip_tcp_in_full_hw_cksum_err",        KSTAT_DATA_UINT64 },
13950                 { "ip_tcp_in_part_hw_cksum_err",        KSTAT_DATA_UINT64 },
13951                 { "ip_tcp_in_sw_cksum_err",             KSTAT_DATA_UINT64 },
13952                 { "ip_udp_in_full_hw_cksum_err",        KSTAT_DATA_UINT64 },
13953                 { "ip_udp_in_part_hw_cksum_err",        KSTAT_DATA_UINT64 },
13954                 { "ip_udp_in_sw_cksum_err",     KSTAT_DATA_UINT64 },
13955                 { "conn_in_recvdstaddr",        KSTAT_DATA_UINT64 },
13956                 { "conn_in_recvopts",           KSTAT_DATA_UINT64 },
13957                 { "conn_in_recvif",             KSTAT_DATA_UINT64 },
13958                 { "conn_in_recvslla",           KSTAT_DATA_UINT64 },
13959                 { "conn_in_recvucred",          KSTAT_DATA_UINT64 },
13960                 { "conn_in_recvttl",            KSTAT_DATA_UINT64 },
13961                 { "conn_in_recvhopopts",        KSTAT_DATA_UINT64 },
13962                 { "conn_in_recvhoplimit",       KSTAT_DATA_UINT64 },
13963                 { "conn_in_recvdstopts",        KSTAT_DATA_UINT64 },
13964                 { "conn_in_recvrthdrdstopts",   KSTAT_DATA_UINT64 },
13965                 { "conn_in_recvrthdr",          KSTAT_DATA_UINT64 },
13966                 { "conn_in_recvpktinfo",        KSTAT_DATA_UINT64 },
13967                 { "conn_in_recvtclass",         KSTAT_DATA_UINT64 },
13968                 { "conn_in_timestamp",          KSTAT_DATA_UINT64 },
13969         };
13970 
13971         ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13972             KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13973             KSTAT_FLAG_VIRTUAL, stackid);
13974 
13975         if (ksp == NULL)
13976                 return (NULL);
13977 
13978         bcopy(&template, ip_statisticsp, sizeof (template));
13979         ksp->ks_data = (void *)ip_statisticsp;
13980         ksp->ks_private = (void *)(uintptr_t)stackid;
13981 
13982         kstat_install(ksp);
13983         return (ksp);
13984 }
13985 
13986 static void
13987 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13988 {
13989         if (ksp != NULL) {
13990                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13991                 kstat_delete_netstack(ksp, stackid);
13992         }
13993 }
13994 
13995 static void *
13996 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13997 {
13998         kstat_t *ksp;
13999 
14000         ip_named_kstat_t template = {
14001                 { "forwarding",         KSTAT_DATA_UINT32, 0 },
14002                 { "defaultTTL",         KSTAT_DATA_UINT32, 0 },
14003                 { "inReceives",         KSTAT_DATA_UINT64, 0 },
14004                 { "inHdrErrors",        KSTAT_DATA_UINT32, 0 },
14005                 { "inAddrErrors",       KSTAT_DATA_UINT32, 0 },
14006                 { "forwDatagrams",      KSTAT_DATA_UINT64, 0 },
14007                 { "inUnknownProtos",    KSTAT_DATA_UINT32, 0 },
14008                 { "inDiscards",         KSTAT_DATA_UINT32, 0 },
14009                 { "inDelivers",         KSTAT_DATA_UINT64, 0 },
14010                 { "outRequests",        KSTAT_DATA_UINT64, 0 },
14011                 { "outDiscards",        KSTAT_DATA_UINT32, 0 },
14012                 { "outNoRoutes",        KSTAT_DATA_UINT32, 0 },
14013                 { "reasmTimeout",       KSTAT_DATA_UINT32, 0 },
14014                 { "reasmReqds",         KSTAT_DATA_UINT32, 0 },
14015                 { "reasmOKs",           KSTAT_DATA_UINT32, 0 },
14016                 { "reasmFails",         KSTAT_DATA_UINT32, 0 },
14017                 { "fragOKs",            KSTAT_DATA_UINT32, 0 },
14018                 { "fragFails",          KSTAT_DATA_UINT32, 0 },
14019                 { "fragCreates",        KSTAT_DATA_UINT32, 0 },
14020                 { "addrEntrySize",      KSTAT_DATA_INT32, 0 },
14021                 { "routeEntrySize",     KSTAT_DATA_INT32, 0 },
14022                 { "netToMediaEntrySize",        KSTAT_DATA_INT32, 0 },
14023                 { "routingDiscards",    KSTAT_DATA_UINT32, 0 },
14024                 { "inErrs",             KSTAT_DATA_UINT32, 0 },
14025                 { "noPorts",            KSTAT_DATA_UINT32, 0 },
14026                 { "inCksumErrs",        KSTAT_DATA_UINT32, 0 },
14027                 { "reasmDuplicates",    KSTAT_DATA_UINT32, 0 },
14028                 { "reasmPartDups",      KSTAT_DATA_UINT32, 0 },
14029                 { "forwProhibits",      KSTAT_DATA_UINT32, 0 },
14030                 { "udpInCksumErrs",     KSTAT_DATA_UINT32, 0 },
14031                 { "udpInOverflows",     KSTAT_DATA_UINT32, 0 },
14032                 { "rawipInOverflows",   KSTAT_DATA_UINT32, 0 },
14033                 { "ipsecInSucceeded",   KSTAT_DATA_UINT32, 0 },
14034                 { "ipsecInFailed",      KSTAT_DATA_INT32, 0 },
14035                 { "memberEntrySize",    KSTAT_DATA_INT32, 0 },
14036                 { "inIPv6",             KSTAT_DATA_UINT32, 0 },
14037                 { "outIPv6",            KSTAT_DATA_UINT32, 0 },
14038                 { "outSwitchIPv6",      KSTAT_DATA_UINT32, 0 },
14039         };
14040 
14041         ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14042             NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14043         if (ksp == NULL || ksp->ks_data == NULL)
14044                 return (NULL);
14045 
14046         template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14047         template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14048         template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
14049         template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14050         template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14051 
14052         template.netToMediaEntrySize.value.i32 =
14053             sizeof (mib2_ipNetToMediaEntry_t);
14054 
14055         template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14056 
14057         bcopy(&template, ksp->ks_data, sizeof (template));
14058         ksp->ks_update = ip_kstat_update;
14059         ksp->ks_private = (void *)(uintptr_t)stackid;
14060 
14061         kstat_install(ksp);
14062         return (ksp);
14063 }
14064 
14065 static void
14066 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14067 {
14068         if (ksp != NULL) {
14069                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14070                 kstat_delete_netstack(ksp, stackid);
14071         }
14072 }
14073 
14074 static int
14075 ip_kstat_update(kstat_t *kp, int rw)
14076 {
14077         ip_named_kstat_t *ipkp;
14078         mib2_ipIfStatsEntry_t ipmib;
14079         ill_walk_context_t ctx;
14080         ill_t *ill;
14081         netstackid_t    stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14082         netstack_t      *ns;
14083         ip_stack_t      *ipst;
14084 
14085         if (kp == NULL || kp->ks_data == NULL)
14086                 return (EIO);
14087 
14088         if (rw == KSTAT_WRITE)
14089                 return (EACCES);
14090 
14091         ns = netstack_find_by_stackid(stackid);
14092         if (ns == NULL)
14093                 return (-1);
14094         ipst = ns->netstack_ip;
14095         if (ipst == NULL) {
14096                 netstack_rele(ns);
14097                 return (-1);
14098         }
14099         ipkp = (ip_named_kstat_t *)kp->ks_data;
14100 
14101         bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14102         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14103         ill = ILL_START_WALK_V4(&ctx, ipst);
14104         for (; ill != NULL; ill = ill_next(&ctx, ill))
14105                 ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14106         rw_exit(&ipst->ips_ill_g_lock);
14107 
14108         ipkp->forwarding.value.ui32 =                ipmib.ipIfStatsForwarding;
14109         ipkp->defaultTTL.value.ui32 =                ipmib.ipIfStatsDefaultTTL;
14110         ipkp->inReceives.value.ui64 =                ipmib.ipIfStatsHCInReceives;
14111         ipkp->inHdrErrors.value.ui32 =               ipmib.ipIfStatsInHdrErrors;
14112         ipkp->inAddrErrors.value.ui32 =              ipmib.ipIfStatsInAddrErrors;
14113         ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14114         ipkp->inUnknownProtos.value.ui32 =   ipmib.ipIfStatsInUnknownProtos;
14115         ipkp->inDiscards.value.ui32 =                ipmib.ipIfStatsInDiscards;
14116         ipkp->inDelivers.value.ui64 =                ipmib.ipIfStatsHCInDelivers;
14117         ipkp->outRequests.value.ui64 =               ipmib.ipIfStatsHCOutRequests;
14118         ipkp->outDiscards.value.ui32 =               ipmib.ipIfStatsOutDiscards;
14119         ipkp->outNoRoutes.value.ui32 =               ipmib.ipIfStatsOutNoRoutes;
14120         ipkp->reasmTimeout.value.ui32 =              ipst->ips_ip_reassembly_timeout;
14121         ipkp->reasmReqds.value.ui32 =                ipmib.ipIfStatsReasmReqds;
14122         ipkp->reasmOKs.value.ui32 =          ipmib.ipIfStatsReasmOKs;
14123         ipkp->reasmFails.value.ui32 =                ipmib.ipIfStatsReasmFails;
14124         ipkp->fragOKs.value.ui32 =           ipmib.ipIfStatsOutFragOKs;
14125         ipkp->fragFails.value.ui32 =         ipmib.ipIfStatsOutFragFails;
14126         ipkp->fragCreates.value.ui32 =               ipmib.ipIfStatsOutFragCreates;
14127 
14128         ipkp->routingDiscards.value.ui32 =   0;
14129         ipkp->inErrs.value.ui32 =            ipmib.tcpIfStatsInErrs;
14130         ipkp->noPorts.value.ui32 =           ipmib.udpIfStatsNoPorts;
14131         ipkp->inCksumErrs.value.ui32 =               ipmib.ipIfStatsInCksumErrs;
14132         ipkp->reasmDuplicates.value.ui32 =   ipmib.ipIfStatsReasmDuplicates;
14133         ipkp->reasmPartDups.value.ui32 =     ipmib.ipIfStatsReasmPartDups;
14134         ipkp->forwProhibits.value.ui32 =     ipmib.ipIfStatsForwProhibits;
14135         ipkp->udpInCksumErrs.value.ui32 =    ipmib.udpIfStatsInCksumErrs;
14136         ipkp->udpInOverflows.value.ui32 =    ipmib.udpIfStatsInOverflows;
14137         ipkp->rawipInOverflows.value.ui32 =  ipmib.rawipIfStatsInOverflows;
14138         ipkp->ipsecInSucceeded.value.ui32 =  ipmib.ipsecIfStatsInSucceeded;
14139         ipkp->ipsecInFailed.value.i32 =              ipmib.ipsecIfStatsInFailed;
14140 
14141         ipkp->inIPv6.value.ui32 =    ipmib.ipIfStatsInWrongIPVersion;
14142         ipkp->outIPv6.value.ui32 =   ipmib.ipIfStatsOutWrongIPVersion;
14143         ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14144 
14145         netstack_rele(ns);
14146 
14147         return (0);
14148 }
14149 
14150 static void *
14151 icmp_kstat_init(netstackid_t stackid)
14152 {
14153         kstat_t *ksp;
14154 
14155         icmp_named_kstat_t template = {
14156                 { "inMsgs",             KSTAT_DATA_UINT32 },
14157                 { "inErrors",           KSTAT_DATA_UINT32 },
14158                 { "inDestUnreachs",     KSTAT_DATA_UINT32 },
14159                 { "inTimeExcds",        KSTAT_DATA_UINT32 },
14160                 { "inParmProbs",        KSTAT_DATA_UINT32 },
14161                 { "inSrcQuenchs",       KSTAT_DATA_UINT32 },
14162                 { "inRedirects",        KSTAT_DATA_UINT32 },
14163                 { "inEchos",            KSTAT_DATA_UINT32 },
14164                 { "inEchoReps",         KSTAT_DATA_UINT32 },
14165                 { "inTimestamps",       KSTAT_DATA_UINT32 },
14166                 { "inTimestampReps",    KSTAT_DATA_UINT32 },
14167                 { "inAddrMasks",        KSTAT_DATA_UINT32 },
14168                 { "inAddrMaskReps",     KSTAT_DATA_UINT32 },
14169                 { "outMsgs",            KSTAT_DATA_UINT32 },
14170                 { "outErrors",          KSTAT_DATA_UINT32 },
14171                 { "outDestUnreachs",    KSTAT_DATA_UINT32 },
14172                 { "outTimeExcds",       KSTAT_DATA_UINT32 },
14173                 { "outParmProbs",       KSTAT_DATA_UINT32 },
14174                 { "outSrcQuenchs",      KSTAT_DATA_UINT32 },
14175                 { "outRedirects",       KSTAT_DATA_UINT32 },
14176                 { "outEchos",           KSTAT_DATA_UINT32 },
14177                 { "outEchoReps",        KSTAT_DATA_UINT32 },
14178                 { "outTimestamps",      KSTAT_DATA_UINT32 },
14179                 { "outTimestampReps",   KSTAT_DATA_UINT32 },
14180                 { "outAddrMasks",       KSTAT_DATA_UINT32 },
14181                 { "outAddrMaskReps",    KSTAT_DATA_UINT32 },
14182                 { "inChksumErrs",       KSTAT_DATA_UINT32 },
14183                 { "inUnknowns",         KSTAT_DATA_UINT32 },
14184                 { "inFragNeeded",       KSTAT_DATA_UINT32 },
14185                 { "outFragNeeded",      KSTAT_DATA_UINT32 },
14186                 { "outDrops",           KSTAT_DATA_UINT32 },
14187                 { "inOverFlows",        KSTAT_DATA_UINT32 },
14188                 { "inBadRedirects",     KSTAT_DATA_UINT32 },
14189         };
14190 
14191         ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14192             NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14193         if (ksp == NULL || ksp->ks_data == NULL)
14194                 return (NULL);
14195 
14196         bcopy(&template, ksp->ks_data, sizeof (template));
14197 
14198         ksp->ks_update = icmp_kstat_update;
14199         ksp->ks_private = (void *)(uintptr_t)stackid;
14200 
14201         kstat_install(ksp);
14202         return (ksp);
14203 }
14204 
14205 static void
14206 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14207 {
14208         if (ksp != NULL) {
14209                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14210                 kstat_delete_netstack(ksp, stackid);
14211         }
14212 }
14213 
14214 static int
14215 icmp_kstat_update(kstat_t *kp, int rw)
14216 {
14217         icmp_named_kstat_t *icmpkp;
14218         netstackid_t    stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14219         netstack_t      *ns;
14220         ip_stack_t      *ipst;
14221 
14222         if ((kp == NULL) || (kp->ks_data == NULL))
14223                 return (EIO);
14224 
14225         if (rw == KSTAT_WRITE)
14226                 return (EACCES);
14227 
14228         ns = netstack_find_by_stackid(stackid);
14229         if (ns == NULL)
14230                 return (-1);
14231         ipst = ns->netstack_ip;
14232         if (ipst == NULL) {
14233                 netstack_rele(ns);
14234                 return (-1);
14235         }
14236         icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14237 
14238         icmpkp->inMsgs.value.ui32 =      ipst->ips_icmp_mib.icmpInMsgs;
14239         icmpkp->inErrors.value.ui32 =            ipst->ips_icmp_mib.icmpInErrors;
14240         icmpkp->inDestUnreachs.value.ui32 =
14241             ipst->ips_icmp_mib.icmpInDestUnreachs;
14242         icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14243         icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14244         icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14245         icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14246         icmpkp->inEchos.value.ui32 =     ipst->ips_icmp_mib.icmpInEchos;
14247         icmpkp->inEchoReps.value.ui32 =          ipst->ips_icmp_mib.icmpInEchoReps;
14248         icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14249         icmpkp->inTimestampReps.value.ui32 =
14250             ipst->ips_icmp_mib.icmpInTimestampReps;
14251         icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14252         icmpkp->inAddrMaskReps.value.ui32 =
14253             ipst->ips_icmp_mib.icmpInAddrMaskReps;
14254         icmpkp->outMsgs.value.ui32 =     ipst->ips_icmp_mib.icmpOutMsgs;
14255         icmpkp->outErrors.value.ui32 =           ipst->ips_icmp_mib.icmpOutErrors;
14256         icmpkp->outDestUnreachs.value.ui32 =
14257             ipst->ips_icmp_mib.icmpOutDestUnreachs;
14258         icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14259         icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14260         icmpkp->outSrcQuenchs.value.ui32 =
14261             ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14262         icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14263         icmpkp->outEchos.value.ui32 =            ipst->ips_icmp_mib.icmpOutEchos;
14264         icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14265         icmpkp->outTimestamps.value.ui32 =
14266             ipst->ips_icmp_mib.icmpOutTimestamps;
14267         icmpkp->outTimestampReps.value.ui32 =
14268             ipst->ips_icmp_mib.icmpOutTimestampReps;
14269         icmpkp->outAddrMasks.value.ui32 =
14270             ipst->ips_icmp_mib.icmpOutAddrMasks;
14271         icmpkp->outAddrMaskReps.value.ui32 =
14272             ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14273         icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14274         icmpkp->inUnknowns.value.ui32 =          ipst->ips_icmp_mib.icmpInUnknowns;
14275         icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14276         icmpkp->outFragNeeded.value.ui32 =
14277             ipst->ips_icmp_mib.icmpOutFragNeeded;
14278         icmpkp->outDrops.value.ui32 =            ipst->ips_icmp_mib.icmpOutDrops;
14279         icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14280         icmpkp->inBadRedirects.value.ui32 =
14281             ipst->ips_icmp_mib.icmpInBadRedirects;
14282 
14283         netstack_rele(ns);
14284         return (0);
14285 }
14286 
14287 /*
14288  * This is the fanout function for raw socket opened for SCTP.  Note
14289  * that it is called after SCTP checks that there is no socket which
14290  * wants a packet.  Then before SCTP handles this out of the blue packet,
14291  * this function is called to see if there is any raw socket for SCTP.
14292  * If there is and it is bound to the correct address, the packet will
14293  * be sent to that socket.  Note that only one raw socket can be bound to
14294  * a port.  This is assured in ipcl_sctp_hash_insert();
14295  */
14296 void
14297 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14298     ip_recv_attr_t *ira)
14299 {
14300         conn_t          *connp;
14301         queue_t         *rq;
14302         boolean_t       secure;
14303         ill_t           *ill = ira->ira_ill;
14304         ip_stack_t      *ipst = ill->ill_ipst;
14305         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
14306         sctp_stack_t    *sctps = ipst->ips_netstack->netstack_sctp;
14307         iaflags_t       iraflags = ira->ira_flags;
14308         ill_t           *rill = ira->ira_rill;
14309 
14310         secure = iraflags & IRAF_IPSEC_SECURE;
14311 
14312         connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14313             ira, ipst);
14314         if (connp == NULL) {
14315                 /*
14316                  * Although raw sctp is not summed, OOB chunks must be.
14317                  * Drop the packet here if the sctp checksum failed.
14318                  */
14319                 if (iraflags & IRAF_SCTP_CSUM_ERR) {
14320                         SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14321                         freemsg(mp);
14322                         return;
14323                 }
14324                 ira->ira_ill = ira->ira_rill = NULL;
14325                 sctp_ootb_input(mp, ira, ipst);
14326                 ira->ira_ill = ill;
14327                 ira->ira_rill = rill;
14328                 return;
14329         }
14330         rq = connp->conn_rq;
14331         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14332                 CONN_DEC_REF(connp);
14333                 BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14334                 freemsg(mp);
14335                 return;
14336         }
14337         if (((iraflags & IRAF_IS_IPV4) ?
14338             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14339             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14340             secure) {
14341                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
14342                     ip6h, ira);
14343                 if (mp == NULL) {
14344                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14345                         /* Note that mp is NULL */
14346                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
14347                         CONN_DEC_REF(connp);
14348                         return;
14349                 }
14350         }
14351 
14352         if (iraflags & IRAF_ICMP_ERROR) {
14353                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
14354         } else {
14355                 ill_t *rill = ira->ira_rill;
14356 
14357                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14358                 /* This is the SOCK_RAW, IPPROTO_SCTP case. */
14359                 ira->ira_ill = ira->ira_rill = NULL;
14360                 (connp->conn_recv)(connp, mp, NULL, ira);
14361                 ira->ira_ill = ill;
14362                 ira->ira_rill = rill;
14363         }
14364         CONN_DEC_REF(connp);
14365 }
14366 
14367 /*
14368  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14369  * header before the ip payload.
14370  */
14371 static void
14372 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14373 {
14374         int len = (mp->b_wptr - mp->b_rptr);
14375         mblk_t *ip_mp;
14376 
14377         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14378         if (is_fp_mp || len != fp_mp_len) {
14379                 if (len > fp_mp_len) {
14380                         /*
14381                          * fastpath header and ip header in the first mblk
14382                          */
14383                         mp->b_rptr += fp_mp_len;
14384                 } else {
14385                         /*
14386                          * ip_xmit_attach_llhdr had to prepend an mblk to
14387                          * attach the fastpath header before ip header.
14388                          */
14389                         ip_mp = mp->b_cont;
14390                         freeb(mp);
14391                         mp = ip_mp;
14392                         mp->b_rptr += (fp_mp_len - len);
14393                 }
14394         } else {
14395                 ip_mp = mp->b_cont;
14396                 freeb(mp);
14397                 mp = ip_mp;
14398         }
14399         ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14400         freemsg(mp);
14401 }
14402 
14403 /*
14404  * Normal post fragmentation function.
14405  *
14406  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14407  * using the same state machine.
14408  *
14409  * We return an error on failure. In particular we return EWOULDBLOCK
14410  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14411  * (currently by canputnext failure resulting in backenabling from GLD.)
14412  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14413  * indication that they can flow control until ip_wsrv() tells then to restart.
14414  *
14415  * If the nce passed by caller is incomplete, this function
14416  * queues the packet and if necessary, sends ARP request and bails.
14417  * If the Neighbor Cache passed is fully resolved, we simply prepend
14418  * the link-layer header to the packet, do ipsec hw acceleration
14419  * work if necessary, and send the packet out on the wire.
14420  */
14421 /* ARGSUSED6 */
14422 int
14423 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14424     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14425 {
14426         queue_t         *wq;
14427         ill_t           *ill = nce->nce_ill;
14428         ip_stack_t      *ipst = ill->ill_ipst;
14429         uint64_t        delta;
14430         boolean_t       isv6 = ill->ill_isv6;
14431         boolean_t       fp_mp;
14432         ncec_t          *ncec = nce->nce_common;
14433         int64_t         now = LBOLT_FASTPATH64;
14434         boolean_t       is_probe;
14435 
14436         DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14437 
14438         ASSERT(mp != NULL);
14439         ASSERT(mp->b_datap->db_type == M_DATA);
14440         ASSERT(pkt_len == msgdsize(mp));
14441 
14442         /*
14443          * If we have already been here and are coming back after ARP/ND.
14444          * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14445          * in that case since they have seen the packet when it came here
14446          * the first time.
14447          */
14448         if (ixaflags & IXAF_NO_TRACE)
14449                 goto sendit;
14450 
14451         if (ixaflags & IXAF_IS_IPV4) {
14452                 ipha_t *ipha = (ipha_t *)mp->b_rptr;
14453 
14454                 ASSERT(!isv6);
14455                 ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14456                 if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14457                     !(ixaflags & IXAF_NO_PFHOOK)) {
14458                         int     error;
14459 
14460                         FW_HOOKS(ipst->ips_ip4_physical_out_event,
14461                             ipst->ips_ipv4firewall_physical_out,
14462                             NULL, ill, ipha, mp, mp, 0, ipst, error);
14463                         DTRACE_PROBE1(ip4__physical__out__end,
14464                             mblk_t *, mp);
14465                         if (mp == NULL)
14466                                 return (error);
14467 
14468                         /* The length could have changed */
14469                         pkt_len = msgdsize(mp);
14470                 }
14471                 if (ipst->ips_ip4_observe.he_interested) {
14472                         /*
14473                          * Note that for TX the zoneid is the sending
14474                          * zone, whether or not MLP is in play.
14475                          * Since the szone argument is the IP zoneid (i.e.,
14476                          * zero for exclusive-IP zones) and ipobs wants
14477                          * the system zoneid, we map it here.
14478                          */
14479                         szone = IP_REAL_ZONEID(szone, ipst);
14480 
14481                         /*
14482                          * On the outbound path the destination zone will be
14483                          * unknown as we're sending this packet out on the
14484                          * wire.
14485                          */
14486                         ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14487                             ill, ipst);
14488                 }
14489                 DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14490                     void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14491                     ipha_t *, ipha, ip6_t *, NULL, int, 0);
14492         } else {
14493                 ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14494 
14495                 ASSERT(isv6);
14496                 ASSERT(pkt_len ==
14497                     ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14498                 if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14499                     !(ixaflags & IXAF_NO_PFHOOK)) {
14500                         int     error;
14501 
14502                         FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14503                             ipst->ips_ipv6firewall_physical_out,
14504                             NULL, ill, ip6h, mp, mp, 0, ipst, error);
14505                         DTRACE_PROBE1(ip6__physical__out__end,
14506                             mblk_t *, mp);
14507                         if (mp == NULL)
14508                                 return (error);
14509 
14510                         /* The length could have changed */
14511                         pkt_len = msgdsize(mp);
14512                 }
14513                 if (ipst->ips_ip6_observe.he_interested) {
14514                         /* See above */
14515                         szone = IP_REAL_ZONEID(szone, ipst);
14516 
14517                         ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14518                             ill, ipst);
14519                 }
14520                 DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14521                     void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14522                     ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14523         }
14524 
14525 sendit:
14526         /*
14527          * We check the state without a lock because the state can never
14528          * move "backwards" to initial or incomplete.
14529          */
14530         switch (ncec->ncec_state) {
14531         case ND_REACHABLE:
14532         case ND_STALE:
14533         case ND_DELAY:
14534         case ND_PROBE:
14535                 mp = ip_xmit_attach_llhdr(mp, nce);
14536                 if (mp == NULL) {
14537                         /*
14538                          * ip_xmit_attach_llhdr has increased
14539                          * ipIfStatsOutDiscards and called ip_drop_output()
14540                          */
14541                         return (ENOBUFS);
14542                 }
14543                 /*
14544                  * check if nce_fastpath completed and we tagged on a
14545                  * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14546                  */
14547                 fp_mp = (mp->b_datap->db_type == M_DATA);
14548 
14549                 if (fp_mp &&
14550                     (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14551                         ill_dld_direct_t *idd;
14552 
14553                         idd = &ill->ill_dld_capab->idc_direct;
14554                         /*
14555                          * Send the packet directly to DLD, where it
14556                          * may be queued depending on the availability
14557                          * of transmit resources at the media layer.
14558                          * Return value should be taken into
14559                          * account and flow control the TCP.
14560                          */
14561                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14562                         UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14563                             pkt_len);
14564 
14565                         if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14566                                 (void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14567                                     (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14568                         } else {
14569                                 uintptr_t cookie;
14570 
14571                                 if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14572                                     mp, (uintptr_t)xmit_hint, 0)) != 0) {
14573                                         if (ixacookie != NULL)
14574                                                 *ixacookie = cookie;
14575                                         return (EWOULDBLOCK);
14576                                 }
14577                         }
14578                 } else {
14579                         wq = ill->ill_wq;
14580 
14581                         if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14582                             !canputnext(wq)) {
14583                                 if (ixacookie != NULL)
14584                                         *ixacookie = 0;
14585                                 ip_xmit_flowctl_drop(ill, mp, fp_mp,
14586                                     nce->nce_fp_mp != NULL ?
14587                                     MBLKL(nce->nce_fp_mp) : 0);
14588                                 return (EWOULDBLOCK);
14589                         }
14590                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14591                         UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14592                             pkt_len);
14593                         putnext(wq, mp);
14594                 }
14595 
14596                 /*
14597                  * The rest of this function implements Neighbor Unreachability
14598                  * detection. Determine if the ncec is eligible for NUD.
14599                  */
14600                 if (ncec->ncec_flags & NCE_F_NONUD)
14601                         return (0);
14602 
14603                 ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14604 
14605                 /*
14606                  * Check for upper layer advice
14607                  */
14608                 if (ixaflags & IXAF_REACH_CONF) {
14609                         timeout_id_t tid;
14610 
14611                         /*
14612                          * It should be o.k. to check the state without
14613                          * a lock here, at most we lose an advice.
14614                          */
14615                         ncec->ncec_last = TICK_TO_MSEC(now);
14616                         if (ncec->ncec_state != ND_REACHABLE) {
14617                                 mutex_enter(&ncec->ncec_lock);
14618                                 ncec->ncec_state = ND_REACHABLE;
14619                                 tid = ncec->ncec_timeout_id;
14620                                 ncec->ncec_timeout_id = 0;
14621                                 mutex_exit(&ncec->ncec_lock);
14622                                 (void) untimeout(tid);
14623                                 if (ip_debug > 2) {
14624                                         /* ip1dbg */
14625                                         pr_addr_dbg("ip_xmit: state"
14626                                             " for %s changed to"
14627                                             " REACHABLE\n", AF_INET6,
14628                                             &ncec->ncec_addr);
14629                                 }
14630                         }
14631                         return (0);
14632                 }
14633 
14634                 delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14635                 ip1dbg(("ip_xmit: delta = %" PRId64
14636                     " ill_reachable_time = %d \n", delta,
14637                     ill->ill_reachable_time));
14638                 if (delta > (uint64_t)ill->ill_reachable_time) {
14639                         mutex_enter(&ncec->ncec_lock);
14640                         switch (ncec->ncec_state) {
14641                         case ND_REACHABLE:
14642                                 ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14643                                 /* FALLTHROUGH */
14644                         case ND_STALE:
14645                                 /*
14646                                  * ND_REACHABLE is identical to
14647                                  * ND_STALE in this specific case. If
14648                                  * reachable time has expired for this
14649                                  * neighbor (delta is greater than
14650                                  * reachable time), conceptually, the
14651                                  * neighbor cache is no longer in
14652                                  * REACHABLE state, but already in
14653                                  * STALE state.  So the correct
14654                                  * transition here is to ND_DELAY.
14655                                  */
14656                                 ncec->ncec_state = ND_DELAY;
14657                                 mutex_exit(&ncec->ncec_lock);
14658                                 nce_restart_timer(ncec,
14659                                     ipst->ips_delay_first_probe_time);
14660                                 if (ip_debug > 3) {
14661                                         /* ip2dbg */
14662                                         pr_addr_dbg("ip_xmit: state"
14663                                             " for %s changed to"
14664                                             " DELAY\n", AF_INET6,
14665                                             &ncec->ncec_addr);
14666                                 }
14667                                 break;
14668                         case ND_DELAY:
14669                         case ND_PROBE:
14670                                 mutex_exit(&ncec->ncec_lock);
14671                                 /* Timers have already started */
14672                                 break;
14673                         case ND_UNREACHABLE:
14674                                 /*
14675                                  * nce_timer has detected that this ncec
14676                                  * is unreachable and initiated deleting
14677                                  * this ncec.
14678                                  * This is a harmless race where we found the
14679                                  * ncec before it was deleted and have
14680                                  * just sent out a packet using this
14681                                  * unreachable ncec.
14682                                  */
14683                                 mutex_exit(&ncec->ncec_lock);
14684                                 break;
14685                         default:
14686                                 ASSERT(0);
14687                                 mutex_exit(&ncec->ncec_lock);
14688                         }
14689                 }
14690                 return (0);
14691 
14692         case ND_INCOMPLETE:
14693                 /*
14694                  * the state could have changed since we didn't hold the lock.
14695                  * Re-verify state under lock.
14696                  */
14697                 is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14698                 mutex_enter(&ncec->ncec_lock);
14699                 if (NCE_ISREACHABLE(ncec)) {
14700                         mutex_exit(&ncec->ncec_lock);
14701                         goto sendit;
14702                 }
14703                 /* queue the packet */
14704                 nce_queue_mp(ncec, mp, is_probe);
14705                 mutex_exit(&ncec->ncec_lock);
14706                 DTRACE_PROBE2(ip__xmit__incomplete,
14707                     (ncec_t *), ncec, (mblk_t *), mp);
14708                 return (0);
14709 
14710         case ND_INITIAL:
14711                 /*
14712                  * State could have changed since we didn't hold the lock, so
14713                  * re-verify state.
14714                  */
14715                 is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14716                 mutex_enter(&ncec->ncec_lock);
14717                 if (NCE_ISREACHABLE(ncec))  {
14718                         mutex_exit(&ncec->ncec_lock);
14719                         goto sendit;
14720                 }
14721                 nce_queue_mp(ncec, mp, is_probe);
14722                 if (ncec->ncec_state == ND_INITIAL) {
14723                         ncec->ncec_state = ND_INCOMPLETE;
14724                         mutex_exit(&ncec->ncec_lock);
14725                         /*
14726                          * figure out the source we want to use
14727                          * and resolve it.
14728                          */
14729                         ip_ndp_resolve(ncec);
14730                 } else  {
14731                         mutex_exit(&ncec->ncec_lock);
14732                 }
14733                 return (0);
14734 
14735         case ND_UNREACHABLE:
14736                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14737                 ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14738                     mp, ill);
14739                 freemsg(mp);
14740                 return (0);
14741 
14742         default:
14743                 ASSERT(0);
14744                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14745                 ip_drop_output("ipIfStatsOutDiscards - ND_other",
14746                     mp, ill);
14747                 freemsg(mp);
14748                 return (ENETUNREACH);
14749         }
14750 }
14751 
14752 /*
14753  * Return B_TRUE if the buffers differ in length or content.
14754  * This is used for comparing extension header buffers.
14755  * Note that an extension header would be declared different
14756  * even if all that changed was the next header value in that header i.e.
14757  * what really changed is the next extension header.
14758  */
14759 boolean_t
14760 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14761     uint_t blen)
14762 {
14763         if (!b_valid)
14764                 blen = 0;
14765 
14766         if (alen != blen)
14767                 return (B_TRUE);
14768         if (alen == 0)
14769                 return (B_FALSE);       /* Both zero length */
14770         return (bcmp(abuf, bbuf, alen));
14771 }
14772 
14773 /*
14774  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14775  * Return B_FALSE if memory allocation fails - don't change any state!
14776  */
14777 boolean_t
14778 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14779     const void *src, uint_t srclen)
14780 {
14781         void *dst;
14782 
14783         if (!src_valid)
14784                 srclen = 0;
14785 
14786         ASSERT(*dstlenp == 0);
14787         if (src != NULL && srclen != 0) {
14788                 dst = mi_alloc(srclen, BPRI_MED);
14789                 if (dst == NULL)
14790                         return (B_FALSE);
14791         } else {
14792                 dst = NULL;
14793         }
14794         if (*dstp != NULL)
14795                 mi_free(*dstp);
14796         *dstp = dst;
14797         *dstlenp = dst == NULL ? 0 : srclen;
14798         return (B_TRUE);
14799 }
14800 
14801 /*
14802  * Replace what is in *dst, *dstlen with the source.
14803  * Assumes ip_allocbuf has already been called.
14804  */
14805 void
14806 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14807     const void *src, uint_t srclen)
14808 {
14809         if (!src_valid)
14810                 srclen = 0;
14811 
14812         ASSERT(*dstlenp == srclen);
14813         if (src != NULL && srclen != 0)
14814                 bcopy(src, *dstp, srclen);
14815 }
14816 
14817 /*
14818  * Free the storage pointed to by the members of an ip_pkt_t.
14819  */
14820 void
14821 ip_pkt_free(ip_pkt_t *ipp)
14822 {
14823         uint_t  fields = ipp->ipp_fields;
14824 
14825         if (fields & IPPF_HOPOPTS) {
14826                 kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14827                 ipp->ipp_hopopts = NULL;
14828                 ipp->ipp_hopoptslen = 0;
14829         }
14830         if (fields & IPPF_RTHDRDSTOPTS) {
14831                 kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14832                 ipp->ipp_rthdrdstopts = NULL;
14833                 ipp->ipp_rthdrdstoptslen = 0;
14834         }
14835         if (fields & IPPF_DSTOPTS) {
14836                 kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14837                 ipp->ipp_dstopts = NULL;
14838                 ipp->ipp_dstoptslen = 0;
14839         }
14840         if (fields & IPPF_RTHDR) {
14841                 kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14842                 ipp->ipp_rthdr = NULL;
14843                 ipp->ipp_rthdrlen = 0;
14844         }
14845         if (fields & IPPF_IPV4_OPTIONS) {
14846                 kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14847                 ipp->ipp_ipv4_options = NULL;
14848                 ipp->ipp_ipv4_options_len = 0;
14849         }
14850         if (fields & IPPF_LABEL_V4) {
14851                 kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14852                 ipp->ipp_label_v4 = NULL;
14853                 ipp->ipp_label_len_v4 = 0;
14854         }
14855         if (fields & IPPF_LABEL_V6) {
14856                 kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14857                 ipp->ipp_label_v6 = NULL;
14858                 ipp->ipp_label_len_v6 = 0;
14859         }
14860         ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14861             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14862 }
14863 
14864 /*
14865  * Copy from src to dst and allocate as needed.
14866  * Returns zero or ENOMEM.
14867  *
14868  * The caller must initialize dst to zero.
14869  */
14870 int
14871 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14872 {
14873         uint_t  fields = src->ipp_fields;
14874 
14875         /* Start with fields that don't require memory allocation */
14876         dst->ipp_fields = fields &
14877             ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14878             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14879 
14880         dst->ipp_addr = src->ipp_addr;
14881         dst->ipp_unicast_hops = src->ipp_unicast_hops;
14882         dst->ipp_hoplimit = src->ipp_hoplimit;
14883         dst->ipp_tclass = src->ipp_tclass;
14884         dst->ipp_type_of_service = src->ipp_type_of_service;
14885 
14886         if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14887             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14888                 return (0);
14889 
14890         if (fields & IPPF_HOPOPTS) {
14891                 dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14892                 if (dst->ipp_hopopts == NULL) {
14893                         ip_pkt_free(dst);
14894                         return (ENOMEM);
14895                 }
14896                 dst->ipp_fields |= IPPF_HOPOPTS;
14897                 bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14898                     src->ipp_hopoptslen);
14899                 dst->ipp_hopoptslen = src->ipp_hopoptslen;
14900         }
14901         if (fields & IPPF_RTHDRDSTOPTS) {
14902                 dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14903                     kmflag);
14904                 if (dst->ipp_rthdrdstopts == NULL) {
14905                         ip_pkt_free(dst);
14906                         return (ENOMEM);
14907                 }
14908                 dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14909                 bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14910                     src->ipp_rthdrdstoptslen);
14911                 dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14912         }
14913         if (fields & IPPF_DSTOPTS) {
14914                 dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14915                 if (dst->ipp_dstopts == NULL) {
14916                         ip_pkt_free(dst);
14917                         return (ENOMEM);
14918                 }
14919                 dst->ipp_fields |= IPPF_DSTOPTS;
14920                 bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14921                     src->ipp_dstoptslen);
14922                 dst->ipp_dstoptslen = src->ipp_dstoptslen;
14923         }
14924         if (fields & IPPF_RTHDR) {
14925                 dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14926                 if (dst->ipp_rthdr == NULL) {
14927                         ip_pkt_free(dst);
14928                         return (ENOMEM);
14929                 }
14930                 dst->ipp_fields |= IPPF_RTHDR;
14931                 bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14932                     src->ipp_rthdrlen);
14933                 dst->ipp_rthdrlen = src->ipp_rthdrlen;
14934         }
14935         if (fields & IPPF_IPV4_OPTIONS) {
14936                 dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14937                     kmflag);
14938                 if (dst->ipp_ipv4_options == NULL) {
14939                         ip_pkt_free(dst);
14940                         return (ENOMEM);
14941                 }
14942                 dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14943                 bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14944                     src->ipp_ipv4_options_len);
14945                 dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14946         }
14947         if (fields & IPPF_LABEL_V4) {
14948                 dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14949                 if (dst->ipp_label_v4 == NULL) {
14950                         ip_pkt_free(dst);
14951                         return (ENOMEM);
14952                 }
14953                 dst->ipp_fields |= IPPF_LABEL_V4;
14954                 bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14955                     src->ipp_label_len_v4);
14956                 dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14957         }
14958         if (fields & IPPF_LABEL_V6) {
14959                 dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14960                 if (dst->ipp_label_v6 == NULL) {
14961                         ip_pkt_free(dst);
14962                         return (ENOMEM);
14963                 }
14964                 dst->ipp_fields |= IPPF_LABEL_V6;
14965                 bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14966                     src->ipp_label_len_v6);
14967                 dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14968         }
14969         if (fields & IPPF_FRAGHDR) {
14970                 dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14971                 if (dst->ipp_fraghdr == NULL) {
14972                         ip_pkt_free(dst);
14973                         return (ENOMEM);
14974                 }
14975                 dst->ipp_fields |= IPPF_FRAGHDR;
14976                 bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14977                     src->ipp_fraghdrlen);
14978                 dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14979         }
14980         return (0);
14981 }
14982 
14983 /*
14984  * Returns INADDR_ANY if no source route
14985  */
14986 ipaddr_t
14987 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14988 {
14989         ipaddr_t        nexthop = INADDR_ANY;
14990         ipoptp_t        opts;
14991         uchar_t         *opt;
14992         uint8_t         optval;
14993         uint8_t         optlen;
14994         uint32_t        totallen;
14995 
14996         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14997                 return (INADDR_ANY);
14998 
14999         totallen = ipp->ipp_ipv4_options_len;
15000         if (totallen & 0x3)
15001                 return (INADDR_ANY);
15002 
15003         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15004             optval != IPOPT_EOL;
15005             optval = ipoptp_next(&opts)) {
15006                 opt = opts.ipoptp_cur;
15007                 switch (optval) {
15008                         uint8_t off;
15009                 case IPOPT_SSRR:
15010                 case IPOPT_LSRR:
15011                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15012                                 break;
15013                         }
15014                         optlen = opts.ipoptp_len;
15015                         off = opt[IPOPT_OFFSET];
15016                         off--;
15017                         if (optlen < IP_ADDR_LEN ||
15018                             off > optlen - IP_ADDR_LEN) {
15019                                 /* End of source route */
15020                                 break;
15021                         }
15022                         bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15023                         if (nexthop == htonl(INADDR_LOOPBACK)) {
15024                                 /* Ignore */
15025                                 nexthop = INADDR_ANY;
15026                                 break;
15027                         }
15028                         break;
15029                 }
15030         }
15031         return (nexthop);
15032 }
15033 
15034 /*
15035  * Reverse a source route.
15036  */
15037 void
15038 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15039 {
15040         ipaddr_t        tmp;
15041         ipoptp_t        opts;
15042         uchar_t         *opt;
15043         uint8_t         optval;
15044         uint32_t        totallen;
15045 
15046         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15047                 return;
15048 
15049         totallen = ipp->ipp_ipv4_options_len;
15050         if (totallen & 0x3)
15051                 return;
15052 
15053         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15054             optval != IPOPT_EOL;
15055             optval = ipoptp_next(&opts)) {
15056                 uint8_t off1, off2;
15057 
15058                 opt = opts.ipoptp_cur;
15059                 switch (optval) {
15060                 case IPOPT_SSRR:
15061                 case IPOPT_LSRR:
15062                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15063                                 break;
15064                         }
15065                         off1 = IPOPT_MINOFF_SR - 1;
15066                         off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15067                         while (off2 > off1) {
15068                                 bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15069                                 bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15070                                 bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15071                                 off2 -= IP_ADDR_LEN;
15072                                 off1 += IP_ADDR_LEN;
15073                         }
15074                         opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15075                         break;
15076                 }
15077         }
15078 }
15079 
15080 /*
15081  * Returns NULL if no routing header
15082  */
15083 in6_addr_t *
15084 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15085 {
15086         in6_addr_t      *nexthop = NULL;
15087         ip6_rthdr0_t    *rthdr;
15088 
15089         if (!(ipp->ipp_fields & IPPF_RTHDR))
15090                 return (NULL);
15091 
15092         rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15093         if (rthdr->ip6r0_segleft == 0)
15094                 return (NULL);
15095 
15096         nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15097         return (nexthop);
15098 }
15099 
15100 zoneid_t
15101 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15102     zoneid_t lookup_zoneid)
15103 {
15104         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
15105         ire_t           *ire;
15106         int             ire_flags = MATCH_IRE_TYPE;
15107         zoneid_t        zoneid = ALL_ZONES;
15108 
15109         if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15110                 return (ALL_ZONES);
15111 
15112         if (lookup_zoneid != ALL_ZONES)
15113                 ire_flags |= MATCH_IRE_ZONEONLY;
15114         ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15115             NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15116         if (ire != NULL) {
15117                 zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15118                 ire_refrele(ire);
15119         }
15120         return (zoneid);
15121 }
15122 
15123 zoneid_t
15124 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15125     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15126 {
15127         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
15128         ire_t           *ire;
15129         int             ire_flags = MATCH_IRE_TYPE;
15130         zoneid_t        zoneid = ALL_ZONES;
15131 
15132         if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15133                 return (ALL_ZONES);
15134 
15135         if (IN6_IS_ADDR_LINKLOCAL(addr))
15136                 ire_flags |= MATCH_IRE_ILL;
15137 
15138         if (lookup_zoneid != ALL_ZONES)
15139                 ire_flags |= MATCH_IRE_ZONEONLY;
15140         ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15141             ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15142         if (ire != NULL) {
15143                 zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15144                 ire_refrele(ire);
15145         }
15146         return (zoneid);
15147 }
15148 
15149 /*
15150  * IP obserability hook support functions.
15151  */
15152 static void
15153 ipobs_init(ip_stack_t *ipst)
15154 {
15155         netid_t id;
15156 
15157         id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15158 
15159         ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15160         VERIFY(ipst->ips_ip4_observe_pr != NULL);
15161 
15162         ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15163         VERIFY(ipst->ips_ip6_observe_pr != NULL);
15164 }
15165 
15166 static void
15167 ipobs_fini(ip_stack_t *ipst)
15168 {
15169 
15170         VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15171         VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15172 }
15173 
15174 /*
15175  * hook_pkt_observe_t is composed in network byte order so that the
15176  * entire mblk_t chain handed into hook_run can be used as-is.
15177  * The caveat is that use of the fields, such as the zone fields,
15178  * requires conversion into host byte order first.
15179  */
15180 void
15181 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15182     const ill_t *ill, ip_stack_t *ipst)
15183 {
15184         hook_pkt_observe_t *hdr;
15185         uint64_t grifindex;
15186         mblk_t *imp;
15187 
15188         imp = allocb(sizeof (*hdr), BPRI_HI);
15189         if (imp == NULL)
15190                 return;
15191 
15192         hdr = (hook_pkt_observe_t *)imp->b_rptr;
15193         /*
15194          * b_wptr is set to make the apparent size of the data in the mblk_t
15195          * to exclude the pointers at the end of hook_pkt_observer_t.
15196          */
15197         imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15198         imp->b_cont = mp;
15199 
15200         ASSERT(DB_TYPE(mp) == M_DATA);
15201 
15202         if (IS_UNDER_IPMP(ill))
15203                 grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15204         else
15205                 grifindex = 0;
15206 
15207         hdr->hpo_version = 1;
15208         hdr->hpo_htype = htons(htype);
15209         hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15210         hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15211         hdr->hpo_grifindex = htonl(grifindex);
15212         hdr->hpo_zsrc = htonl(zsrc);
15213         hdr->hpo_zdst = htonl(zdst);
15214         hdr->hpo_pkt = imp;
15215         hdr->hpo_ctx = ipst->ips_netstack;
15216 
15217         if (ill->ill_isv6) {
15218                 hdr->hpo_family = AF_INET6;
15219                 (void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15220                     ipst->ips_ipv6observing, (hook_data_t)hdr);
15221         } else {
15222                 hdr->hpo_family = AF_INET;
15223                 (void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15224                     ipst->ips_ipv4observing, (hook_data_t)hdr);
15225         }
15226 
15227         imp->b_cont = NULL;
15228         freemsg(imp);
15229 }
15230 
15231 /*
15232  * Utility routine that checks if `v4srcp' is a valid address on underlying
15233  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15234  * associated with `v4srcp' on success.  NOTE: if this is not called from
15235  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15236  * group during or after this lookup.
15237  */
15238 boolean_t
15239 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15240 {
15241         ipif_t *ipif;
15242 
15243         ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15244         if (ipif != NULL) {
15245                 if (ipifp != NULL)
15246                         *ipifp = ipif;
15247                 else
15248                         ipif_refrele(ipif);
15249                 return (B_TRUE);
15250         }
15251 
15252         ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15253             *v4srcp));
15254         return (B_FALSE);
15255 }
15256 
15257 /*
15258  * Transport protocol call back function for CPU state change.
15259  */
15260 /* ARGSUSED */
15261 static int
15262 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15263 {
15264         processorid_t cpu_seqid;
15265         netstack_handle_t nh;
15266         netstack_t *ns;
15267 
15268         ASSERT(MUTEX_HELD(&cpu_lock));
15269 
15270         switch (what) {
15271         case CPU_CONFIG:
15272         case CPU_ON:
15273         case CPU_INIT:
15274         case CPU_CPUPART_IN:
15275                 cpu_seqid = cpu[id]->cpu_seqid;
15276                 netstack_next_init(&nh);
15277                 while ((ns = netstack_next(&nh)) != NULL) {
15278                         tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15279                         sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15280                         udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15281                         netstack_rele(ns);
15282                 }
15283                 netstack_next_fini(&nh);
15284                 break;
15285         case CPU_UNCONFIG:
15286         case CPU_OFF:
15287         case CPU_CPUPART_OUT:
15288                 /*
15289                  * Nothing to do.  We don't remove the per CPU stats from
15290                  * the IP stack even when the CPU goes offline.
15291                  */
15292                 break;
15293         default:
15294                 break;
15295         }
15296         return (0);
15297 }