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) 2012 Joyent, Inc. All rights reserved.
  26  * Copyright (c) 2014, OmniTI Computer Consulting, Inc. All rights reserved.
  27  */
  28 
  29 #include <sys/types.h>
  30 #include <sys/stream.h>
  31 #include <sys/dlpi.h>
  32 #include <sys/stropts.h>
  33 #include <sys/sysmacros.h>
  34 #include <sys/strsubr.h>
  35 #include <sys/strlog.h>
  36 #include <sys/strsun.h>
  37 #include <sys/zone.h>
  38 #define _SUN_TPI_VERSION 2
  39 #include <sys/tihdr.h>
  40 #include <sys/xti_inet.h>
  41 #include <sys/ddi.h>
  42 #include <sys/suntpi.h>
  43 #include <sys/cmn_err.h>
  44 #include <sys/debug.h>
  45 #include <sys/kobj.h>
  46 #include <sys/modctl.h>
  47 #include <sys/atomic.h>
  48 #include <sys/policy.h>
  49 #include <sys/priv.h>
  50 #include <sys/taskq.h>
  51 
  52 #include <sys/systm.h>
  53 #include <sys/param.h>
  54 #include <sys/kmem.h>
  55 #include <sys/sdt.h>
  56 #include <sys/socket.h>
  57 #include <sys/vtrace.h>
  58 #include <sys/isa_defs.h>
  59 #include <sys/mac.h>
  60 #include <net/if.h>
  61 #include <net/if_arp.h>
  62 #include <net/route.h>
  63 #include <sys/sockio.h>
  64 #include <netinet/in.h>
  65 #include <net/if_dl.h>
  66 
  67 #include <inet/common.h>
  68 #include <inet/mi.h>
  69 #include <inet/mib2.h>
  70 #include <inet/nd.h>
  71 #include <inet/arp.h>
  72 #include <inet/snmpcom.h>
  73 #include <inet/optcom.h>
  74 #include <inet/kstatcom.h>
  75 
  76 #include <netinet/igmp_var.h>
  77 #include <netinet/ip6.h>
  78 #include <netinet/icmp6.h>
  79 #include <netinet/sctp.h>
  80 
  81 #include <inet/ip.h>
  82 #include <inet/ip_impl.h>
  83 #include <inet/ip6.h>
  84 #include <inet/ip6_asp.h>
  85 #include <inet/tcp.h>
  86 #include <inet/tcp_impl.h>
  87 #include <inet/ip_multi.h>
  88 #include <inet/ip_if.h>
  89 #include <inet/ip_ire.h>
  90 #include <inet/ip_ftable.h>
  91 #include <inet/ip_rts.h>
  92 #include <inet/ip_ndp.h>
  93 #include <inet/ip_listutils.h>
  94 #include <netinet/igmp.h>
  95 #include <netinet/ip_mroute.h>
  96 #include <inet/ipp_common.h>
  97 
  98 #include <net/pfkeyv2.h>
  99 #include <inet/sadb.h>
 100 #include <inet/ipsec_impl.h>
 101 #include <inet/iptun/iptun_impl.h>
 102 #include <inet/ipdrop.h>
 103 #include <inet/ip_netinfo.h>
 104 #include <inet/ilb_ip.h>
 105 
 106 #include <sys/ethernet.h>
 107 #include <net/if_types.h>
 108 #include <sys/cpuvar.h>
 109 
 110 #include <ipp/ipp.h>
 111 #include <ipp/ipp_impl.h>
 112 #include <ipp/ipgpc/ipgpc.h>
 113 
 114 #include <sys/pattr.h>
 115 #include <inet/ipclassifier.h>
 116 #include <inet/sctp_ip.h>
 117 #include <inet/sctp/sctp_impl.h>
 118 #include <inet/udp_impl.h>
 119 #include <inet/rawip_impl.h>
 120 #include <inet/rts_impl.h>
 121 
 122 #include <sys/tsol/label.h>
 123 #include <sys/tsol/tnet.h>
 124 
 125 #include <sys/squeue_impl.h>
 126 #include <inet/ip_arp.h>
 127 
 128 #include <sys/clock_impl.h>       /* For LBOLT_FASTPATH{,64} */
 129 
 130 /*
 131  * Values for squeue switch:
 132  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
 133  * IP_SQUEUE_ENTER: SQ_PROCESS
 134  * IP_SQUEUE_FILL: SQ_FILL
 135  */
 136 int ip_squeue_enter = IP_SQUEUE_ENTER;  /* Setable in /etc/system */
 137 
 138 int ip_squeue_flag;
 139 
 140 /*
 141  * Setable in /etc/system
 142  */
 143 int ip_poll_normal_ms = 100;
 144 int ip_poll_normal_ticks = 0;
 145 int ip_modclose_ackwait_ms = 3000;
 146 
 147 /*
 148  * It would be nice to have these present only in DEBUG systems, but the
 149  * current design of the global symbol checking logic requires them to be
 150  * unconditionally present.
 151  */
 152 uint_t ip_thread_data;                  /* TSD key for debug support */
 153 krwlock_t ip_thread_rwlock;
 154 list_t  ip_thread_list;
 155 
 156 /*
 157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
 158  */
 159 
 160 struct listptr_s {
 161         mblk_t  *lp_head;       /* pointer to the head of the list */
 162         mblk_t  *lp_tail;       /* pointer to the tail of the list */
 163 };
 164 
 165 typedef struct listptr_s listptr_t;
 166 
 167 /*
 168  * This is used by ip_snmp_get_mib2_ip_route_media and
 169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
 170  */
 171 typedef struct iproutedata_s {
 172         uint_t          ird_idx;
 173         uint_t          ird_flags;      /* see below */
 174         listptr_t       ird_route;      /* ipRouteEntryTable */
 175         listptr_t       ird_netmedia;   /* ipNetToMediaEntryTable */
 176         listptr_t       ird_attrs;      /* ipRouteAttributeTable */
 177 } iproutedata_t;
 178 
 179 /* Include ire_testhidden and IRE_IF_CLONE routes */
 180 #define IRD_REPORT_ALL  0x01
 181 
 182 /*
 183  * Cluster specific hooks. These should be NULL when booted as a non-cluster
 184  */
 185 
 186 /*
 187  * Hook functions to enable cluster networking
 188  * On non-clustered systems these vectors must always be NULL.
 189  *
 190  * Hook function to Check ip specified ip address is a shared ip address
 191  * in the cluster
 192  *
 193  */
 194 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
 195     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
 196 
 197 /*
 198  * Hook function to generate cluster wide ip fragment identifier
 199  */
 200 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
 201     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
 202     void *args) = NULL;
 203 
 204 /*
 205  * Hook function to generate cluster wide SPI.
 206  */
 207 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
 208     void *) = NULL;
 209 
 210 /*
 211  * Hook function to verify if the SPI is already utlized.
 212  */
 213 
 214 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
 215 
 216 /*
 217  * Hook function to delete the SPI from the cluster wide repository.
 218  */
 219 
 220 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
 221 
 222 /*
 223  * Hook function to inform the cluster when packet received on an IDLE SA
 224  */
 225 
 226 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
 227     in6_addr_t, in6_addr_t, void *) = NULL;
 228 
 229 /*
 230  * Synchronization notes:
 231  *
 232  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
 233  * MT level protection given by STREAMS. IP uses a combination of its own
 234  * internal serialization mechanism and standard Solaris locking techniques.
 235  * The internal serialization is per phyint.  This is used to serialize
 236  * plumbing operations, IPMP operations, most set ioctls, etc.
 237  *
 238  * Plumbing is a long sequence of operations involving message
 239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
 240  * involved in plumbing operations. A natural model is to serialize these
 241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
 242  * parallel without any interference. But various set ioctls on hme0 are best
 243  * serialized, along with IPMP operations and processing of DLPI control
 244  * messages received from drivers on a per phyint basis. This serialization is
 245  * provided by the ipsq_t and primitives operating on this. Details can
 246  * be found in ip_if.c above the core primitives operating on ipsq_t.
 247  *
 248  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
 249  * Simiarly lookup of an ire by a thread also returns a refheld ire.
 250  * In addition ipif's and ill's referenced by the ire are also indirectly
 251  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
 252  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
 253  * address of an ipif has to go through the ipsq_t. This ensures that only
 254  * one such exclusive operation proceeds at any time on the ipif. It then
 255  * waits for all refcnts
 256  * associated with this ipif to come down to zero. The address is changed
 257  * only after the ipif has been quiesced. Then the ipif is brought up again.
 258  * More details are described above the comment in ip_sioctl_flags.
 259  *
 260  * Packet processing is based mostly on IREs and are fully multi-threaded
 261  * using standard Solaris MT techniques.
 262  *
 263  * There are explicit locks in IP to handle:
 264  * - The ip_g_head list maintained by mi_open_link() and friends.
 265  *
 266  * - The reassembly data structures (one lock per hash bucket)
 267  *
 268  * - conn_lock is meant to protect conn_t fields. The fields actually
 269  *   protected by conn_lock are documented in the conn_t definition.
 270  *
 271  * - ire_lock to protect some of the fields of the ire, IRE tables
 272  *   (one lock per hash bucket). Refer to ip_ire.c for details.
 273  *
 274  * - ndp_g_lock and ncec_lock for protecting NCEs.
 275  *
 276  * - ill_lock protects fields of the ill and ipif. Details in ip.h
 277  *
 278  * - ill_g_lock: This is a global reader/writer lock. Protects the following
 279  *      * The AVL tree based global multi list of all ills.
 280  *      * The linked list of all ipifs of an ill
 281  *      * The <ipsq-xop> mapping
 282  *      * <ill-phyint> association
 283  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
 284  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
 285  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
 286  *   writer for the actual duration of the insertion/deletion/change.
 287  *
 288  * - ill_lock:  This is a per ill mutex.
 289  *   It protects some members of the ill_t struct; see ip.h for details.
 290  *   It also protects the <ill-phyint> assoc.
 291  *   It also protects the list of ipifs hanging off the ill.
 292  *
 293  * - ipsq_lock: This is a per ipsq_t mutex lock.
 294  *   This protects some members of the ipsq_t struct; see ip.h for details.
 295  *   It also protects the <ipsq-ipxop> mapping
 296  *
 297  * - ipx_lock: This is a per ipxop_t mutex lock.
 298  *   This protects some members of the ipxop_t struct; see ip.h for details.
 299  *
 300  * - phyint_lock: This is a per phyint mutex lock. Protects just the
 301  *   phyint_flags
 302  *
 303  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
 304  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
 305  *   uniqueness check also done atomically.
 306  *
 307  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
 308  *   group list linked by ill_usesrc_grp_next. It also protects the
 309  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
 310  *   group is being added or deleted.  This lock is taken as a reader when
 311  *   walking the list/group(eg: to get the number of members in a usesrc group).
 312  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
 313  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
 314  *   example, it is not necessary to take this lock in the initial portion
 315  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
 316  *   operations are executed exclusively and that ensures that the "usesrc
 317  *   group state" cannot change. The "usesrc group state" change can happen
 318  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
 319  *
 320  * Changing <ill-phyint>, <ipsq-xop> assocications:
 321  *
 322  * To change the <ill-phyint> association, the ill_g_lock must be held
 323  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
 324  * must be held.
 325  *
 326  * To change the <ipsq-xop> association, the ill_g_lock must be held as
 327  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
 328  * This is only done when ills are added or removed from IPMP groups.
 329  *
 330  * To add or delete an ipif from the list of ipifs hanging off the ill,
 331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
 332  * a writer on the associated ipsq.
 333  *
 334  * To add or delete an ill to the system, the ill_g_lock must be held as
 335  * writer and the thread must be a writer on the associated ipsq.
 336  *
 337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
 338  * must be a writer on the associated ipsq.
 339  *
 340  * Lock hierarchy
 341  *
 342  * Some lock hierarchy scenarios are listed below.
 343  *
 344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
 345  * ill_g_lock -> ill_lock(s) -> phyint_lock
 346  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
 347  * ill_g_lock -> ip_addr_avail_lock
 348  * conn_lock -> irb_lock -> ill_lock -> ire_lock
 349  * ill_g_lock -> ip_g_nd_lock
 350  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
 351  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
 352  * arl_lock -> ill_lock
 353  * ips_ire_dep_lock -> irb_lock
 354  *
 355  * When more than 1 ill lock is needed to be held, all ill lock addresses
 356  * are sorted on address and locked starting from highest addressed lock
 357  * downward.
 358  *
 359  * Multicast scenarios
 360  * ips_ill_g_lock -> ill_mcast_lock
 361  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
 362  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
 363  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
 364  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
 365  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
 366  *
 367  * IPsec scenarios
 368  *
 369  * ipsa_lock -> ill_g_lock -> ill_lock
 370  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
 371  *
 372  * Trusted Solaris scenarios
 373  *
 374  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
 375  * igsa_lock -> gcdb_lock
 376  * gcgrp_rwlock -> ire_lock
 377  * gcgrp_rwlock -> gcdb_lock
 378  *
 379  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
 380  *
 381  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
 382  * sq_lock -> conn_lock -> QLOCK(q)
 383  * ill_lock -> ft_lock -> fe_lock
 384  *
 385  * Routing/forwarding table locking notes:
 386  *
 387  * Lock acquisition order: Radix tree lock, irb_lock.
 388  * Requirements:
 389  * i.  Walker must not hold any locks during the walker callback.
 390  * ii  Walker must not see a truncated tree during the walk because of any node
 391  *     deletion.
 392  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
 393  *     in many places in the code to walk the irb list. Thus even if all the
 394  *     ires in a bucket have been deleted, we still can't free the radix node
 395  *     until the ires have actually been inactive'd (freed).
 396  *
 397  * Tree traversal - Need to hold the global tree lock in read mode.
 398  * Before dropping the global tree lock, need to either increment the ire_refcnt
 399  * to ensure that the radix node can't be deleted.
 400  *
 401  * Tree add - Need to hold the global tree lock in write mode to add a
 402  * radix node. To prevent the node from being deleted, increment the
 403  * irb_refcnt, after the node is added to the tree. The ire itself is
 404  * added later while holding the irb_lock, but not the tree lock.
 405  *
 406  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
 407  * All associated ires must be inactive (i.e. freed), and irb_refcnt
 408  * must be zero.
 409  *
 410  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
 411  * global tree lock (read mode) for traversal.
 412  *
 413  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
 414  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
 415  *
 416  * IPsec notes :
 417  *
 418  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
 419  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
 420  * ip_xmit_attr_t has the
 421  * information used by the IPsec code for applying the right level of
 422  * protection. The information initialized by IP in the ip_xmit_attr_t
 423  * is determined by the per-socket policy or global policy in the system.
 424  * For inbound datagrams, the ip_recv_attr_t
 425  * starts out with nothing in it. It gets filled
 426  * with the right information if it goes through the AH/ESP code, which
 427  * happens if the incoming packet is secure. The information initialized
 428  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
 429  * the policy requirements needed by per-socket policy or global policy
 430  * is met or not.
 431  *
 432  * For fully connected sockets i.e dst, src [addr, port] is known,
 433  * conn_policy_cached is set indicating that policy has been cached.
 434  * conn_in_enforce_policy may or may not be set depending on whether
 435  * there is a global policy match or per-socket policy match.
 436  * Policy inheriting happpens in ip_policy_set once the destination is known.
 437  * Once the right policy is set on the conn_t, policy cannot change for
 438  * this socket. This makes life simpler for TCP (UDP ?) where
 439  * re-transmissions go out with the same policy. For symmetry, policy
 440  * is cached for fully connected UDP sockets also. Thus if policy is cached,
 441  * it also implies that policy is latched i.e policy cannot change
 442  * on these sockets. As we have the right policy on the conn, we don't
 443  * have to lookup global policy for every outbound and inbound datagram
 444  * and thus serving as an optimization. Note that a global policy change
 445  * does not affect fully connected sockets if they have policy. If fully
 446  * connected sockets did not have any policy associated with it, global
 447  * policy change may affect them.
 448  *
 449  * IP Flow control notes:
 450  * ---------------------
 451  * Non-TCP streams are flow controlled by IP. The way this is accomplished
 452  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
 453  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
 454  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
 455  * functions.
 456  *
 457  * Per Tx ring udp flow control:
 458  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
 459  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
 460  *
 461  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
 462  * To achieve best performance, outgoing traffic need to be fanned out among
 463  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
 464  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
 465  * the address of connp as fanout hint to mac_tx(). Under flow controlled
 466  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
 467  * cookie points to a specific Tx ring that is blocked. The cookie is used to
 468  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
 469  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
 470  * connp's. The drain list is not a single list but a configurable number of
 471  * lists.
 472  *
 473  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
 474  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
 475  * which is equal to 128. This array in turn contains a pointer to idl_t[],
 476  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
 477  * list will point to the list of connp's that are flow controlled.
 478  *
 479  *                      ---------------   -------   -------   -------
 480  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 481  *                   |  ---------------   -------   -------   -------
 482  *                   |  ---------------   -------   -------   -------
 483  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 484  * ----------------  |  ---------------   -------   -------   -------
 485  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
 486  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
 487  *                   |  ---------------   -------   -------   -------
 488  *                   .        .              .         .         .
 489  *                   |  ---------------   -------   -------   -------
 490  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 491  *                      ---------------   -------   -------   -------
 492  *                      ---------------   -------   -------   -------
 493  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 494  *                   |  ---------------   -------   -------   -------
 495  *                   |  ---------------   -------   -------   -------
 496  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 497  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
 498  * ----------------  |        .              .         .         .
 499  *                   |  ---------------   -------   -------   -------
 500  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 501  *                      ---------------   -------   -------   -------
 502  *     .....
 503  * ----------------
 504  * |idl_tx_list[n]|-> ...
 505  * ----------------
 506  *
 507  * When mac_tx() returns a cookie, the cookie is hashed into an index into
 508  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
 509  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
 510  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
 511  * Further, conn_blocked is set to indicate that the conn is blocked.
 512  *
 513  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
 514  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
 515  * is again hashed to locate the appropriate idl_tx_list, which is then
 516  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
 517  * the drain list and calls conn_drain_remove() to clear flow control (via
 518  * calling su_txq_full() or clearing QFULL), and remove the conn from the
 519  * drain list.
 520  *
 521  * Note that the drain list is not a single list but a (configurable) array of
 522  * lists (8 elements by default).  Synchronization between drain insertion and
 523  * flow control wakeup is handled by using idl_txl->txl_lock, and only
 524  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
 525  *
 526  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
 527  * On the send side, if the packet cannot be sent down to the driver by IP
 528  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
 529  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
 530  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
 531  * control has been relieved, the blocked conns in the 0'th drain list are
 532  * drained as in the non-STREAMS case.
 533  *
 534  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
 535  * is done when the conn is inserted into the drain list (conn_drain_insert())
 536  * and cleared when the conn is removed from the it (conn_drain_remove()).
 537  *
 538  * IPQOS notes:
 539  *
 540  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
 541  * and IPQoS modules. IPPF includes hooks in IP at different control points
 542  * (callout positions) which direct packets to IPQoS modules for policy
 543  * processing. Policies, if present, are global.
 544  *
 545  * The callout positions are located in the following paths:
 546  *              o local_in (packets destined for this host)
 547  *              o local_out (packets orginating from this host )
 548  *              o fwd_in  (packets forwarded by this m/c - inbound)
 549  *              o fwd_out (packets forwarded by this m/c - outbound)
 550  * Hooks at these callout points can be enabled/disabled using the ndd variable
 551  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
 552  * By default all the callout positions are enabled.
 553  *
 554  * Outbound (local_out)
 555  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
 556  *
 557  * Inbound (local_in)
 558  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
 559  *
 560  * Forwarding (in and out)
 561  * Hooks are placed in ire_recv_forward_v4/v6.
 562  *
 563  * IP Policy Framework processing (IPPF processing)
 564  * Policy processing for a packet is initiated by ip_process, which ascertains
 565  * that the classifier (ipgpc) is loaded and configured, failing which the
 566  * packet resumes normal processing in IP. If the clasifier is present, the
 567  * packet is acted upon by one or more IPQoS modules (action instances), per
 568  * filters configured in ipgpc and resumes normal IP processing thereafter.
 569  * An action instance can drop a packet in course of its processing.
 570  *
 571  * Zones notes:
 572  *
 573  * The partitioning rules for networking are as follows:
 574  * 1) Packets coming from a zone must have a source address belonging to that
 575  * zone.
 576  * 2) Packets coming from a zone can only be sent on a physical interface on
 577  * which the zone has an IP address.
 578  * 3) Between two zones on the same machine, packet delivery is only allowed if
 579  * there's a matching route for the destination and zone in the forwarding
 580  * table.
 581  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
 582  * different zones can bind to the same port with the wildcard address
 583  * (INADDR_ANY).
 584  *
 585  * The granularity of interface partitioning is at the logical interface level.
 586  * Therefore, every zone has its own IP addresses, and incoming packets can be
 587  * attributed to a zone unambiguously. A logical interface is placed into a zone
 588  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
 589  * structure. Rule (1) is implemented by modifying the source address selection
 590  * algorithm so that the list of eligible addresses is filtered based on the
 591  * sending process zone.
 592  *
 593  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
 594  * across all zones, depending on their type. Here is the break-up:
 595  *
 596  * IRE type                             Shared/exclusive
 597  * --------                             ----------------
 598  * IRE_BROADCAST                        Exclusive
 599  * IRE_DEFAULT (default routes)         Shared (*)
 600  * IRE_LOCAL                            Exclusive (x)
 601  * IRE_LOOPBACK                         Exclusive
 602  * IRE_PREFIX (net routes)              Shared (*)
 603  * IRE_IF_NORESOLVER (interface routes) Exclusive
 604  * IRE_IF_RESOLVER (interface routes)   Exclusive
 605  * IRE_IF_CLONE (interface routes)      Exclusive
 606  * IRE_HOST (host routes)               Shared (*)
 607  *
 608  * (*) A zone can only use a default or off-subnet route if the gateway is
 609  * directly reachable from the zone, that is, if the gateway's address matches
 610  * one of the zone's logical interfaces.
 611  *
 612  * (x) IRE_LOCAL are handled a bit differently.
 613  * When ip_restrict_interzone_loopback is set (the default),
 614  * ire_route_recursive restricts loopback using an IRE_LOCAL
 615  * between zone to the case when L2 would have conceptually looped the packet
 616  * back, i.e. the loopback which is required since neither Ethernet drivers
 617  * nor Ethernet hardware loops them back. This is the case when the normal
 618  * routes (ignoring IREs with different zoneids) would send out the packet on
 619  * the same ill as the ill with which is IRE_LOCAL is associated.
 620  *
 621  * Multiple zones can share a common broadcast address; typically all zones
 622  * share the 255.255.255.255 address. Incoming as well as locally originated
 623  * broadcast packets must be dispatched to all the zones on the broadcast
 624  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
 625  * since some zones may not be on the 10.16.72/24 network. To handle this, each
 626  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
 627  * sent to every zone that has an IRE_BROADCAST entry for the destination
 628  * address on the input ill, see ip_input_broadcast().
 629  *
 630  * Applications in different zones can join the same multicast group address.
 631  * The same logic applies for multicast as for broadcast. ip_input_multicast
 632  * dispatches packets to all zones that have members on the physical interface.
 633  */
 634 
 635 /*
 636  * Squeue Fanout flags:
 637  *      0: No fanout.
 638  *      1: Fanout across all squeues
 639  */
 640 boolean_t       ip_squeue_fanout = 0;
 641 
 642 /*
 643  * Maximum dups allowed per packet.
 644  */
 645 uint_t ip_max_frag_dups = 10;
 646 
 647 static int      ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
 648                     cred_t *credp, boolean_t isv6);
 649 static mblk_t   *ip_xmit_attach_llhdr(mblk_t *, nce_t *);
 650 
 651 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
 652 static void     icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
 653 static void     icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
 654     ip_recv_attr_t *);
 655 static void     icmp_options_update(ipha_t *);
 656 static void     icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
 657 static void     icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
 658 static mblk_t   *icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
 659 static void     icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
 660     ip_recv_attr_t *);
 661 static void     icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
 662 static void     icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
 663     ip_recv_attr_t *);
 664 
 665 mblk_t          *ip_dlpi_alloc(size_t, t_uscalar_t);
 666 char            *ip_dot_addr(ipaddr_t, char *);
 667 mblk_t          *ip_carve_mp(mblk_t **, ssize_t);
 668 int             ip_close(queue_t *, int);
 669 static char     *ip_dot_saddr(uchar_t *, char *);
 670 static void     ip_lrput(queue_t *, mblk_t *);
 671 ipaddr_t        ip_net_mask(ipaddr_t);
 672 char            *ip_nv_lookup(nv_t *, int);
 673 void    ip_rput(queue_t *, mblk_t *);
 674 static void     ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
 675                     void *dummy_arg);
 676 int             ip_snmp_get(queue_t *, mblk_t *, int, boolean_t);
 677 static mblk_t   *ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
 678                     mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
 679 static mblk_t   *ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
 680                     ip_stack_t *, boolean_t);
 681 static mblk_t   *ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
 682                     boolean_t);
 683 static mblk_t   *ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
 684 static mblk_t   *ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
 685 static mblk_t   *ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
 686 static mblk_t   *ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
 687 static mblk_t   *ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
 688                     ip_stack_t *ipst, boolean_t);
 689 static mblk_t   *ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
 690                     ip_stack_t *ipst, boolean_t);
 691 static mblk_t   *ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
 692                     ip_stack_t *ipst);
 693 static mblk_t   *ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
 694                     ip_stack_t *ipst);
 695 static mblk_t   *ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
 696                     ip_stack_t *ipst);
 697 static mblk_t   *ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
 698                     ip_stack_t *ipst);
 699 static mblk_t   *ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
 700                     ip_stack_t *ipst);
 701 static mblk_t   *ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
 702                     ip_stack_t *ipst);
 703 static mblk_t   *ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
 704                     ip_stack_t *ipst);
 705 static mblk_t   *ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
 706                     ip_stack_t *ipst);
 707 static void     ip_snmp_get2_v4(ire_t *, iproutedata_t *);
 708 static void     ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
 709 static int      ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
 710 static int      ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
 711 int             ip_snmp_set(queue_t *, int, int, uchar_t *, int);
 712 
 713 static mblk_t   *ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
 714                     mblk_t *);
 715 
 716 static void     conn_drain_init(ip_stack_t *);
 717 static void     conn_drain_fini(ip_stack_t *);
 718 static void     conn_drain(conn_t *connp, boolean_t closing);
 719 
 720 static void     conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
 721 static void     conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
 722 
 723 static void     *ip_stack_init(netstackid_t stackid, netstack_t *ns);
 724 static void     ip_stack_shutdown(netstackid_t stackid, void *arg);
 725 static void     ip_stack_fini(netstackid_t stackid, void *arg);
 726 
 727 static int      ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
 728     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
 729     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
 730     const in6_addr_t *);
 731 
 732 static int      ip_squeue_switch(int);
 733 
 734 static void     *ip_kstat_init(netstackid_t, ip_stack_t *);
 735 static void     ip_kstat_fini(netstackid_t, kstat_t *);
 736 static int      ip_kstat_update(kstat_t *kp, int rw);
 737 static void     *icmp_kstat_init(netstackid_t);
 738 static void     icmp_kstat_fini(netstackid_t, kstat_t *);
 739 static int      icmp_kstat_update(kstat_t *kp, int rw);
 740 static void     *ip_kstat2_init(netstackid_t, ip_stat_t *);
 741 static void     ip_kstat2_fini(netstackid_t, kstat_t *);
 742 
 743 static void     ipobs_init(ip_stack_t *);
 744 static void     ipobs_fini(ip_stack_t *);
 745 
 746 static int      ip_tp_cpu_update(cpu_setup_t, int, void *);
 747 
 748 ipaddr_t        ip_g_all_ones = IP_HOST_MASK;
 749 
 750 static long ip_rput_pullups;
 751 int     dohwcksum = 1;  /* use h/w cksum if supported by the hardware */
 752 
 753 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
 754 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
 755 
 756 int     ip_debug;
 757 
 758 /*
 759  * Multirouting/CGTP stuff
 760  */
 761 int     ip_cgtp_filter_rev = CGTP_FILTER_REV;   /* CGTP hooks version */
 762 
 763 /*
 764  * IP tunables related declarations. Definitions are in ip_tunables.c
 765  */
 766 extern mod_prop_info_t ip_propinfo_tbl[];
 767 extern int ip_propinfo_count;
 768 
 769 /*
 770  * Table of IP ioctls encoding the various properties of the ioctl and
 771  * indexed based on the last byte of the ioctl command. Occasionally there
 772  * is a clash, and there is more than 1 ioctl with the same last byte.
 773  * In such a case 1 ioctl is encoded in the ndx table and the remaining
 774  * ioctls are encoded in the misc table. An entry in the ndx table is
 775  * retrieved by indexing on the last byte of the ioctl command and comparing
 776  * the ioctl command with the value in the ndx table. In the event of a
 777  * mismatch the misc table is then searched sequentially for the desired
 778  * ioctl command.
 779  *
 780  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
 781  */
 782 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
 783         /* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 784         /* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 785         /* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 786         /* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 787         /* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 788         /* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 789         /* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 790         /* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 791         /* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 792         /* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 793 
 794         /* 010 */ { SIOCADDRT,  sizeof (struct rtentry), IPI_PRIV,
 795                         MISC_CMD, ip_siocaddrt, NULL },
 796         /* 011 */ { SIOCDELRT,  sizeof (struct rtentry), IPI_PRIV,
 797                         MISC_CMD, ip_siocdelrt, NULL },
 798 
 799         /* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 800                         IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
 801         /* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
 802                         IF_CMD, ip_sioctl_get_addr, NULL },
 803 
 804         /* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 805                         IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
 806         /* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
 807                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
 808 
 809         /* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
 810                         IPI_PRIV | IPI_WR,
 811                         IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
 812         /* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
 813                         IPI_MODOK | IPI_GET_CMD,
 814                         IF_CMD, ip_sioctl_get_flags, NULL },
 815 
 816         /* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 817         /* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 818 
 819         /* copyin size cannot be coded for SIOCGIFCONF */
 820         /* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
 821                         MISC_CMD, ip_sioctl_get_ifconf, NULL },
 822 
 823         /* 021 */ { SIOCSIFMTU, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 824                         IF_CMD, ip_sioctl_mtu, NULL },
 825         /* 022 */ { SIOCGIFMTU, sizeof (struct ifreq), IPI_GET_CMD,
 826                         IF_CMD, ip_sioctl_get_mtu, NULL },
 827         /* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
 828                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
 829         /* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 830                         IF_CMD, ip_sioctl_brdaddr, NULL },
 831         /* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
 832                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
 833         /* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
 834                         IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
 835         /* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
 836                         IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
 837         /* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
 838                         IF_CMD, ip_sioctl_metric, NULL },
 839         /* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 840 
 841         /* See 166-168 below for extended SIOC*XARP ioctls */
 842         /* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
 843                         ARP_CMD, ip_sioctl_arp, NULL },
 844         /* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
 845                         ARP_CMD, ip_sioctl_arp, NULL },
 846         /* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
 847                         ARP_CMD, ip_sioctl_arp, NULL },
 848 
 849         /* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 850         /* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 851         /* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 852         /* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 853         /* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 854         /* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 855         /* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 856         /* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 857         /* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 858         /* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 859         /* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 860         /* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 861         /* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 862         /* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 863         /* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 864         /* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 865         /* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 866         /* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 867         /* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 868         /* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 869         /* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 870 
 871         /* 054 */ { IF_UNITSEL, sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
 872                         MISC_CMD, if_unitsel, if_unitsel_restart },
 873 
 874         /* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 875         /* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 876         /* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 877         /* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 878         /* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 879         /* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 880         /* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 881         /* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 882         /* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 883         /* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 884         /* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 885         /* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 886         /* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 887         /* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 888         /* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 889         /* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 890         /* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 891         /* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 892 
 893         /* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
 894                         IPI_PRIV | IPI_WR | IPI_MODOK,
 895                         IF_CMD, ip_sioctl_sifname, NULL },
 896 
 897         /* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 898         /* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 899         /* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 900         /* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 901         /* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 902         /* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 903         /* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 904         /* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 905         /* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 906         /* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 907         /* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 908         /* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 909         /* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 910 
 911         /* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
 912                         MISC_CMD, ip_sioctl_get_ifnum, NULL },
 913         /* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
 914                         IF_CMD, ip_sioctl_get_muxid, NULL },
 915         /* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
 916                         IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
 917 
 918         /* Both if and lif variants share same func */
 919         /* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
 920                         IF_CMD, ip_sioctl_get_lifindex, NULL },
 921         /* Both if and lif variants share same func */
 922         /* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
 923                         IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
 924 
 925         /* copyin size cannot be coded for SIOCGIFCONF */
 926         /* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
 927                         MISC_CMD, ip_sioctl_get_ifconf, NULL },
 928         /* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 929         /* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 930         /* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 931         /* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 932         /* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 933         /* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 934         /* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 935         /* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 936         /* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 937         /* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 938         /* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 939         /* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 940         /* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 941         /* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 942         /* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 943         /* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 944         /* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 945 
 946         /* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
 947                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
 948                         ip_sioctl_removeif_restart },
 949         /* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
 950                         IPI_GET_CMD | IPI_PRIV | IPI_WR,
 951                         LIF_CMD, ip_sioctl_addif, NULL },
 952 #define SIOCLIFADDR_NDX 112
 953         /* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 954                         LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
 955         /* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
 956                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
 957         /* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 958                         LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
 959         /* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
 960                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
 961         /* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
 962                         IPI_PRIV | IPI_WR,
 963                         LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
 964         /* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
 965                         IPI_GET_CMD | IPI_MODOK,
 966                         LIF_CMD, ip_sioctl_get_flags, NULL },
 967 
 968         /* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 969         /* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
 970 
 971         /* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
 972                         ip_sioctl_get_lifconf, NULL },
 973         /* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 974                         LIF_CMD, ip_sioctl_mtu, NULL },
 975         /* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
 976                         LIF_CMD, ip_sioctl_get_mtu, NULL },
 977         /* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
 978                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
 979         /* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 980                         LIF_CMD, ip_sioctl_brdaddr, NULL },
 981         /* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
 982                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
 983         /* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 984                         LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
 985         /* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
 986                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
 987         /* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
 988                         LIF_CMD, ip_sioctl_metric, NULL },
 989         /* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
 990                         IPI_PRIV | IPI_WR | IPI_MODOK,
 991                         LIF_CMD, ip_sioctl_slifname,
 992                         ip_sioctl_slifname_restart },
 993 
 994         /* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
 995                         MISC_CMD, ip_sioctl_get_lifnum, NULL },
 996         /* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
 997                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
 998         /* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
 999                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1000         /* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1001                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1002         /* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1003                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1004         /* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1005                         LIF_CMD, ip_sioctl_token, NULL },
1006         /* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1007                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1008         /* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1009                         LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1010         /* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1011                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1012         /* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1013                         LIF_CMD, ip_sioctl_lnkinfo, NULL },
1014 
1015         /* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1016                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1017         /* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1018                         LIF_CMD, ip_siocdelndp_v6, NULL },
1019         /* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1020                         LIF_CMD, ip_siocqueryndp_v6, NULL },
1021         /* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1022                         LIF_CMD, ip_siocsetndp_v6, NULL },
1023         /* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1024                         MISC_CMD, ip_sioctl_tmyaddr, NULL },
1025         /* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1026                         MISC_CMD, ip_sioctl_tonlink, NULL },
1027         /* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1028                         MISC_CMD, ip_sioctl_tmysite, NULL },
1029         /* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030         /* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 
1032         /* Old *IPSECONFIG ioctls are now deprecated, now see spdsock.c */
1033         /* 149 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034         /* 150 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035         /* 151 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036         /* 152 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 
1038         /* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 
1040         /* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1041                         LIF_CMD, ip_sioctl_get_binding, NULL },
1042         /* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1043                         IPI_PRIV | IPI_WR,
1044                         LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1045         /* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1046                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1047         /* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1048                         IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1049 
1050         /* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1051         /* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052         /* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053         /* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 
1055         /* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 
1057         /* These are handled in ip_sioctl_copyin_setup itself */
1058         /* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1059                         MISC_CMD, NULL, NULL },
1060         /* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1061                         MISC_CMD, NULL, NULL },
1062         /* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1063 
1064         /* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1065                         ip_sioctl_get_lifconf, NULL },
1066 
1067         /* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1068                         XARP_CMD, ip_sioctl_arp, NULL },
1069         /* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1070                         XARP_CMD, ip_sioctl_arp, NULL },
1071         /* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1072                         XARP_CMD, ip_sioctl_arp, NULL },
1073 
1074         /* SIOCPOPSOCKFS is not handled by IP */
1075         /* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1076 
1077         /* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1078                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1079         /* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1080                         IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1081                         ip_sioctl_slifzone_restart },
1082         /* 172-174 are SCTP ioctls and not handled by IP */
1083         /* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084         /* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085         /* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086         /* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1087                         IPI_GET_CMD, LIF_CMD,
1088                         ip_sioctl_get_lifusesrc, 0 },
1089         /* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1090                         IPI_PRIV | IPI_WR,
1091                         LIF_CMD, ip_sioctl_slifusesrc,
1092                         NULL },
1093         /* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1094                         ip_sioctl_get_lifsrcof, NULL },
1095         /* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1096                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1097         /* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1098                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1099         /* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1100                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1101         /* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1102                         MSFILT_CMD, ip_sioctl_msfilter, NULL },
1103         /* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104         /* SIOCSENABLESDP is handled by SDP */
1105         /* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1106         /* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1107         /* 185 */ { SIOCGIFHWADDR, sizeof (struct ifreq), IPI_GET_CMD,
1108                         IF_CMD, ip_sioctl_get_ifhwaddr, NULL },
1109         /* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1110         /* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1111                         ip_sioctl_ilb_cmd, NULL },
1112         /* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1113         /* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1114         /* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1115                         IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1116         /* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1117                         LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart },
1118         /* 192 */ { SIOCGLIFHWADDR, sizeof (struct lifreq), IPI_GET_CMD,
1119                         LIF_CMD, ip_sioctl_get_lifhwaddr, NULL }
1120 };
1121 
1122 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1123 
1124 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1125         { I_LINK,       0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1126         { I_UNLINK,     0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1127         { I_PLINK,      0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1128         { I_PUNLINK,    0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1129         { ND_GET,       0, 0, 0, NULL, NULL },
1130         { ND_SET,       0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1131         { IP_IOCTL,     0, 0, 0, NULL, NULL },
1132         { SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1133                 MISC_CMD, mrt_ioctl},
1134         { SIOCGETSGCNT, sizeof (struct sioc_sg_req), IPI_GET_CMD,
1135                 MISC_CMD, mrt_ioctl},
1136         { SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1137                 MISC_CMD, mrt_ioctl}
1138 };
1139 
1140 int ip_misc_ioctl_count =
1141     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1142 
1143 int     conn_drain_nthreads;            /* Number of drainers reqd. */
1144                                         /* Settable in /etc/system */
1145 /* Defined in ip_ire.c */
1146 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1147 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1148 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1149 
1150 static nv_t     ire_nv_arr[] = {
1151         { IRE_BROADCAST, "BROADCAST" },
1152         { IRE_LOCAL, "LOCAL" },
1153         { IRE_LOOPBACK, "LOOPBACK" },
1154         { IRE_DEFAULT, "DEFAULT" },
1155         { IRE_PREFIX, "PREFIX" },
1156         { IRE_IF_NORESOLVER, "IF_NORESOL" },
1157         { IRE_IF_RESOLVER, "IF_RESOLV" },
1158         { IRE_IF_CLONE, "IF_CLONE" },
1159         { IRE_HOST, "HOST" },
1160         { IRE_MULTICAST, "MULTICAST" },
1161         { IRE_NOROUTE, "NOROUTE" },
1162         { 0 }
1163 };
1164 
1165 nv_t    *ire_nv_tbl = ire_nv_arr;
1166 
1167 /* Simple ICMP IP Header Template */
1168 static ipha_t icmp_ipha = {
1169         IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1170 };
1171 
1172 struct module_info ip_mod_info = {
1173         IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1174         IP_MOD_LOWAT
1175 };
1176 
1177 /*
1178  * Duplicate static symbols within a module confuses mdb; so we avoid the
1179  * problem by making the symbols here distinct from those in udp.c.
1180  */
1181 
1182 /*
1183  * Entry points for IP as a device and as a module.
1184  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1185  */
1186 static struct qinit iprinitv4 = {
1187         (pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1188         &ip_mod_info
1189 };
1190 
1191 struct qinit iprinitv6 = {
1192         (pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1193         &ip_mod_info
1194 };
1195 
1196 static struct qinit ipwinit = {
1197         (pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1198         &ip_mod_info
1199 };
1200 
1201 static struct qinit iplrinit = {
1202         (pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1203         &ip_mod_info
1204 };
1205 
1206 static struct qinit iplwinit = {
1207         (pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1208         &ip_mod_info
1209 };
1210 
1211 /* For AF_INET aka /dev/ip */
1212 struct streamtab ipinfov4 = {
1213         &iprinitv4, &ipwinit, &iplrinit, &iplwinit
1214 };
1215 
1216 /* For AF_INET6 aka /dev/ip6 */
1217 struct streamtab ipinfov6 = {
1218         &iprinitv6, &ipwinit, &iplrinit, &iplwinit
1219 };
1220 
1221 #ifdef  DEBUG
1222 boolean_t skip_sctp_cksum = B_FALSE;
1223 #endif
1224 
1225 /*
1226  * Generate an ICMP fragmentation needed message.
1227  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1228  * constructed by the caller.
1229  */
1230 void
1231 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1232 {
1233         icmph_t icmph;
1234         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
1235 
1236         mp = icmp_pkt_err_ok(mp, ira);
1237         if (mp == NULL)
1238                 return;
1239 
1240         bzero(&icmph, sizeof (icmph_t));
1241         icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1242         icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1243         icmph.icmph_du_mtu = htons((uint16_t)mtu);
1244         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1245         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1246 
1247         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1248 }
1249 
1250 /*
1251  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1252  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1253  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1254  * Likewise, if the ICMP error is misformed (too short, etc), then it
1255  * returns NULL. The caller uses this to determine whether or not to send
1256  * to raw sockets.
1257  *
1258  * All error messages are passed to the matching transport stream.
1259  *
1260  * The following cases are handled by icmp_inbound:
1261  * 1) It needs to send a reply back and possibly delivering it
1262  *    to the "interested" upper clients.
1263  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1264  * 3) It needs to change some values in IP only.
1265  * 4) It needs to change some values in IP and upper layers e.g TCP
1266  *    by delivering an error to the upper layers.
1267  *
1268  * We handle the above three cases in the context of IPsec in the
1269  * following way :
1270  *
1271  * 1) Send the reply back in the same way as the request came in.
1272  *    If it came in encrypted, it goes out encrypted. If it came in
1273  *    clear, it goes out in clear. Thus, this will prevent chosen
1274  *    plain text attack.
1275  * 2) The client may or may not expect things to come in secure.
1276  *    If it comes in secure, the policy constraints are checked
1277  *    before delivering it to the upper layers. If it comes in
1278  *    clear, ipsec_inbound_accept_clear will decide whether to
1279  *    accept this in clear or not. In both the cases, if the returned
1280  *    message (IP header + 8 bytes) that caused the icmp message has
1281  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1282  *    sending up. If there are only 8 bytes of returned message, then
1283  *    upper client will not be notified.
1284  * 3) Check with global policy to see whether it matches the constaints.
1285  *    But this will be done only if icmp_accept_messages_in_clear is
1286  *    zero.
1287  * 4) If we need to change both in IP and ULP, then the decision taken
1288  *    while affecting the values in IP and while delivering up to TCP
1289  *    should be the same.
1290  *
1291  *      There are two cases.
1292  *
1293  *      a) If we reject data at the IP layer (ipsec_check_global_policy()
1294  *         failed), we will not deliver it to the ULP, even though they
1295  *         are *willing* to accept in *clear*. This is fine as our global
1296  *         disposition to icmp messages asks us reject the datagram.
1297  *
1298  *      b) If we accept data at the IP layer (ipsec_check_global_policy()
1299  *         succeeded or icmp_accept_messages_in_clear is 1), and not able
1300  *         to deliver it to ULP (policy failed), it can lead to
1301  *         consistency problems. The cases known at this time are
1302  *         ICMP_DESTINATION_UNREACHABLE  messages with following code
1303  *         values :
1304  *
1305  *         - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1306  *           and Upper layer rejects. Then the communication will
1307  *           come to a stop. This is solved by making similar decisions
1308  *           at both levels. Currently, when we are unable to deliver
1309  *           to the Upper Layer (due to policy failures) while IP has
1310  *           adjusted dce_pmtu, the next outbound datagram would
1311  *           generate a local ICMP_FRAGMENTATION_NEEDED message - which
1312  *           will be with the right level of protection. Thus the right
1313  *           value will be communicated even if we are not able to
1314  *           communicate when we get from the wire initially. But this
1315  *           assumes there would be at least one outbound datagram after
1316  *           IP has adjusted its dce_pmtu value. To make things
1317  *           simpler, we accept in clear after the validation of
1318  *           AH/ESP headers.
1319  *
1320  *         - Other ICMP ERRORS : We may not be able to deliver it to the
1321  *           upper layer depending on the level of protection the upper
1322  *           layer expects and the disposition in ipsec_inbound_accept_clear().
1323  *           ipsec_inbound_accept_clear() decides whether a given ICMP error
1324  *           should be accepted in clear when the Upper layer expects secure.
1325  *           Thus the communication may get aborted by some bad ICMP
1326  *           packets.
1327  */
1328 mblk_t *
1329 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1330 {
1331         icmph_t         *icmph;
1332         ipha_t          *ipha;          /* Outer header */
1333         int             ip_hdr_length;  /* Outer header length */
1334         boolean_t       interested;
1335         ipif_t          *ipif;
1336         uint32_t        ts;
1337         uint32_t        *tsp;
1338         timestruc_t     now;
1339         ill_t           *ill = ira->ira_ill;
1340         ip_stack_t      *ipst = ill->ill_ipst;
1341         zoneid_t        zoneid = ira->ira_zoneid;
1342         int             len_needed;
1343         mblk_t          *mp_ret = NULL;
1344 
1345         ipha = (ipha_t *)mp->b_rptr;
1346 
1347         BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1348 
1349         ip_hdr_length = ira->ira_ip_hdr_length;
1350         if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1351                 if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1352                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1353                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1354                         freemsg(mp);
1355                         return (NULL);
1356                 }
1357                 /* Last chance to get real. */
1358                 ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1359                 if (ipha == NULL) {
1360                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1361                         freemsg(mp);
1362                         return (NULL);
1363                 }
1364         }
1365 
1366         /* The IP header will always be a multiple of four bytes */
1367         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1368         ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1369             icmph->icmph_code));
1370 
1371         /*
1372          * We will set "interested" to "true" if we should pass a copy to
1373          * the transport or if we handle the packet locally.
1374          */
1375         interested = B_FALSE;
1376         switch (icmph->icmph_type) {
1377         case ICMP_ECHO_REPLY:
1378                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1379                 break;
1380         case ICMP_DEST_UNREACHABLE:
1381                 if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1382                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1383                 interested = B_TRUE;    /* Pass up to transport */
1384                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1385                 break;
1386         case ICMP_SOURCE_QUENCH:
1387                 interested = B_TRUE;    /* Pass up to transport */
1388                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1389                 break;
1390         case ICMP_REDIRECT:
1391                 if (!ipst->ips_ip_ignore_redirect)
1392                         interested = B_TRUE;
1393                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1394                 break;
1395         case ICMP_ECHO_REQUEST:
1396                 /*
1397                  * Whether to respond to echo requests that come in as IP
1398                  * broadcasts or as IP multicast is subject to debate
1399                  * (what isn't?).  We aim to please, you pick it.
1400                  * Default is do it.
1401                  */
1402                 if (ira->ira_flags & IRAF_MULTICAST) {
1403                         /* multicast: respond based on tunable */
1404                         interested = ipst->ips_ip_g_resp_to_echo_mcast;
1405                 } else if (ira->ira_flags & IRAF_BROADCAST) {
1406                         /* broadcast: respond based on tunable */
1407                         interested = ipst->ips_ip_g_resp_to_echo_bcast;
1408                 } else {
1409                         /* unicast: always respond */
1410                         interested = B_TRUE;
1411                 }
1412                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1413                 if (!interested) {
1414                         /* We never pass these to RAW sockets */
1415                         freemsg(mp);
1416                         return (NULL);
1417                 }
1418 
1419                 /* Check db_ref to make sure we can modify the packet. */
1420                 if (mp->b_datap->db_ref > 1) {
1421                         mblk_t  *mp1;
1422 
1423                         mp1 = copymsg(mp);
1424                         freemsg(mp);
1425                         if (!mp1) {
1426                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1427                                 return (NULL);
1428                         }
1429                         mp = mp1;
1430                         ipha = (ipha_t *)mp->b_rptr;
1431                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1432                 }
1433                 icmph->icmph_type = ICMP_ECHO_REPLY;
1434                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1435                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1436                 return (NULL);
1437 
1438         case ICMP_ROUTER_ADVERTISEMENT:
1439         case ICMP_ROUTER_SOLICITATION:
1440                 break;
1441         case ICMP_TIME_EXCEEDED:
1442                 interested = B_TRUE;    /* Pass up to transport */
1443                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1444                 break;
1445         case ICMP_PARAM_PROBLEM:
1446                 interested = B_TRUE;    /* Pass up to transport */
1447                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1448                 break;
1449         case ICMP_TIME_STAMP_REQUEST:
1450                 /* Response to Time Stamp Requests is local policy. */
1451                 if (ipst->ips_ip_g_resp_to_timestamp) {
1452                         if (ira->ira_flags & IRAF_MULTIBROADCAST)
1453                                 interested =
1454                                     ipst->ips_ip_g_resp_to_timestamp_bcast;
1455                         else
1456                                 interested = B_TRUE;
1457                 }
1458                 if (!interested) {
1459                         /* We never pass these to RAW sockets */
1460                         freemsg(mp);
1461                         return (NULL);
1462                 }
1463 
1464                 /* Make sure we have enough of the packet */
1465                 len_needed = ip_hdr_length + ICMPH_SIZE +
1466                     3 * sizeof (uint32_t);
1467 
1468                 if (mp->b_wptr - mp->b_rptr < len_needed) {
1469                         ipha = ip_pullup(mp, len_needed, ira);
1470                         if (ipha == NULL) {
1471                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1472                                 ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1473                                     mp, ill);
1474                                 freemsg(mp);
1475                                 return (NULL);
1476                         }
1477                         /* Refresh following the pullup. */
1478                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1479                 }
1480                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1481                 /* Check db_ref to make sure we can modify the packet. */
1482                 if (mp->b_datap->db_ref > 1) {
1483                         mblk_t  *mp1;
1484 
1485                         mp1 = copymsg(mp);
1486                         freemsg(mp);
1487                         if (!mp1) {
1488                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1489                                 return (NULL);
1490                         }
1491                         mp = mp1;
1492                         ipha = (ipha_t *)mp->b_rptr;
1493                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1494                 }
1495                 icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1496                 tsp = (uint32_t *)&icmph[1];
1497                 tsp++;          /* Skip past 'originate time' */
1498                 /* Compute # of milliseconds since midnight */
1499                 gethrestime(&now);
1500                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1501                     NSEC2MSEC(now.tv_nsec);
1502                 *tsp++ = htonl(ts);     /* Lay in 'receive time' */
1503                 *tsp++ = htonl(ts);     /* Lay in 'send time' */
1504                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1505                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1506                 return (NULL);
1507 
1508         case ICMP_TIME_STAMP_REPLY:
1509                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1510                 break;
1511         case ICMP_INFO_REQUEST:
1512                 /* Per RFC 1122 3.2.2.7, ignore this. */
1513         case ICMP_INFO_REPLY:
1514                 break;
1515         case ICMP_ADDRESS_MASK_REQUEST:
1516                 if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1517                         interested =
1518                             ipst->ips_ip_respond_to_address_mask_broadcast;
1519                 } else {
1520                         interested = B_TRUE;
1521                 }
1522                 if (!interested) {
1523                         /* We never pass these to RAW sockets */
1524                         freemsg(mp);
1525                         return (NULL);
1526                 }
1527                 len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1528                 if (mp->b_wptr - mp->b_rptr < len_needed) {
1529                         ipha = ip_pullup(mp, len_needed, ira);
1530                         if (ipha == NULL) {
1531                                 BUMP_MIB(ill->ill_ip_mib,
1532                                     ipIfStatsInTruncatedPkts);
1533                                 ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1534                                     ill);
1535                                 freemsg(mp);
1536                                 return (NULL);
1537                         }
1538                         /* Refresh following the pullup. */
1539                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1540                 }
1541                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1542                 /* Check db_ref to make sure we can modify the packet. */
1543                 if (mp->b_datap->db_ref > 1) {
1544                         mblk_t  *mp1;
1545 
1546                         mp1 = copymsg(mp);
1547                         freemsg(mp);
1548                         if (!mp1) {
1549                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1550                                 return (NULL);
1551                         }
1552                         mp = mp1;
1553                         ipha = (ipha_t *)mp->b_rptr;
1554                         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1555                 }
1556                 /*
1557                  * Need the ipif with the mask be the same as the source
1558                  * address of the mask reply. For unicast we have a specific
1559                  * ipif. For multicast/broadcast we only handle onlink
1560                  * senders, and use the source address to pick an ipif.
1561                  */
1562                 ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1563                 if (ipif == NULL) {
1564                         /* Broadcast or multicast */
1565                         ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1566                         if (ipif == NULL) {
1567                                 freemsg(mp);
1568                                 return (NULL);
1569                         }
1570                 }
1571                 icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1572                 bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1573                 ipif_refrele(ipif);
1574                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1575                 icmp_send_reply_v4(mp, ipha, icmph, ira);
1576                 return (NULL);
1577 
1578         case ICMP_ADDRESS_MASK_REPLY:
1579                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1580                 break;
1581         default:
1582                 interested = B_TRUE;    /* Pass up to transport */
1583                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1584                 break;
1585         }
1586         /*
1587          * See if there is an ICMP client to avoid an extra copymsg/freemsg
1588          * if there isn't one.
1589          */
1590         if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1591                 /* If there is an ICMP client and we want one too, copy it. */
1592 
1593                 if (!interested) {
1594                         /* Caller will deliver to RAW sockets */
1595                         return (mp);
1596                 }
1597                 mp_ret = copymsg(mp);
1598                 if (mp_ret == NULL) {
1599                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1600                         ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1601                 }
1602         } else if (!interested) {
1603                 /* Neither we nor raw sockets are interested. Drop packet now */
1604                 freemsg(mp);
1605                 return (NULL);
1606         }
1607 
1608         /*
1609          * ICMP error or redirect packet. Make sure we have enough of
1610          * the header and that db_ref == 1 since we might end up modifying
1611          * the packet.
1612          */
1613         if (mp->b_cont != NULL) {
1614                 if (ip_pullup(mp, -1, ira) == NULL) {
1615                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1616                         ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1617                             mp, ill);
1618                         freemsg(mp);
1619                         return (mp_ret);
1620                 }
1621         }
1622 
1623         if (mp->b_datap->db_ref > 1) {
1624                 mblk_t  *mp1;
1625 
1626                 mp1 = copymsg(mp);
1627                 if (mp1 == NULL) {
1628                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1629                         ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1630                         freemsg(mp);
1631                         return (mp_ret);
1632                 }
1633                 freemsg(mp);
1634                 mp = mp1;
1635         }
1636 
1637         /*
1638          * In case mp has changed, verify the message before any further
1639          * processes.
1640          */
1641         ipha = (ipha_t *)mp->b_rptr;
1642         icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1643         if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1644                 freemsg(mp);
1645                 return (mp_ret);
1646         }
1647 
1648         switch (icmph->icmph_type) {
1649         case ICMP_REDIRECT:
1650                 icmp_redirect_v4(mp, ipha, icmph, ira);
1651                 break;
1652         case ICMP_DEST_UNREACHABLE:
1653                 if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1654                         /* Update DCE and adjust MTU is icmp header if needed */
1655                         icmp_inbound_too_big_v4(icmph, ira);
1656                 }
1657                 /* FALLTHRU */
1658         default:
1659                 icmp_inbound_error_fanout_v4(mp, icmph, ira);
1660                 break;
1661         }
1662         return (mp_ret);
1663 }
1664 
1665 /*
1666  * Send an ICMP echo, timestamp or address mask reply.
1667  * The caller has already updated the payload part of the packet.
1668  * We handle the ICMP checksum, IP source address selection and feed
1669  * the packet into ip_output_simple.
1670  */
1671 static void
1672 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1673     ip_recv_attr_t *ira)
1674 {
1675         uint_t          ip_hdr_length = ira->ira_ip_hdr_length;
1676         ill_t           *ill = ira->ira_ill;
1677         ip_stack_t      *ipst = ill->ill_ipst;
1678         ip_xmit_attr_t  ixas;
1679 
1680         /* Send out an ICMP packet */
1681         icmph->icmph_checksum = 0;
1682         icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1683         /* Reset time to live. */
1684         ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1685         {
1686                 /* Swap source and destination addresses */
1687                 ipaddr_t tmp;
1688 
1689                 tmp = ipha->ipha_src;
1690                 ipha->ipha_src = ipha->ipha_dst;
1691                 ipha->ipha_dst = tmp;
1692         }
1693         ipha->ipha_ident = 0;
1694         if (!IS_SIMPLE_IPH(ipha))
1695                 icmp_options_update(ipha);
1696 
1697         bzero(&ixas, sizeof (ixas));
1698         ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1699         ixas.ixa_zoneid = ira->ira_zoneid;
1700         ixas.ixa_cred = kcred;
1701         ixas.ixa_cpid = NOPID;
1702         ixas.ixa_tsl = ira->ira_tsl; /* Behave as a multi-level responder */
1703         ixas.ixa_ifindex = 0;
1704         ixas.ixa_ipst = ipst;
1705         ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1706 
1707         if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1708                 /*
1709                  * This packet should go out the same way as it
1710                  * came in i.e in clear, independent of the IPsec policy
1711                  * for transmitting packets.
1712                  */
1713                 ixas.ixa_flags |= IXAF_NO_IPSEC;
1714         } else {
1715                 if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1716                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1717                         /* Note: mp already consumed and ip_drop_packet done */
1718                         return;
1719                 }
1720         }
1721         if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1722                 /*
1723                  * Not one or our addresses (IRE_LOCALs), thus we let
1724                  * ip_output_simple pick the source.
1725                  */
1726                 ipha->ipha_src = INADDR_ANY;
1727                 ixas.ixa_flags |= IXAF_SET_SOURCE;
1728         }
1729         /* Should we send with DF and use dce_pmtu? */
1730         if (ipst->ips_ipv4_icmp_return_pmtu) {
1731                 ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1732                 ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1733         }
1734 
1735         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1736 
1737         (void) ip_output_simple(mp, &ixas);
1738         ixa_cleanup(&ixas);
1739 }
1740 
1741 /*
1742  * Verify the ICMP messages for either for ICMP error or redirect packet.
1743  * The caller should have fully pulled up the message. If it's a redirect
1744  * packet, only basic checks on IP header will be done; otherwise, verify
1745  * the packet by looking at the included ULP header.
1746  *
1747  * Called before icmp_inbound_error_fanout_v4 is called.
1748  */
1749 static boolean_t
1750 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1751 {
1752         ill_t           *ill = ira->ira_ill;
1753         int             hdr_length;
1754         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
1755         conn_t          *connp;
1756         ipha_t          *ipha;  /* Inner IP header */
1757 
1758         ipha = (ipha_t *)&icmph[1];
1759         if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1760                 goto truncated;
1761 
1762         hdr_length = IPH_HDR_LENGTH(ipha);
1763 
1764         if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1765                 goto discard_pkt;
1766 
1767         if (hdr_length < sizeof (ipha_t))
1768                 goto truncated;
1769 
1770         if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1771                 goto truncated;
1772 
1773         /*
1774          * Stop here for ICMP_REDIRECT.
1775          */
1776         if (icmph->icmph_type == ICMP_REDIRECT)
1777                 return (B_TRUE);
1778 
1779         /*
1780          * ICMP errors only.
1781          */
1782         switch (ipha->ipha_protocol) {
1783         case IPPROTO_UDP:
1784                 /*
1785                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1786                  * transport header.
1787                  */
1788                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1789                     mp->b_wptr)
1790                         goto truncated;
1791                 break;
1792         case IPPROTO_TCP: {
1793                 tcpha_t         *tcpha;
1794 
1795                 /*
1796                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1797                  * transport header.
1798                  */
1799                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1800                     mp->b_wptr)
1801                         goto truncated;
1802 
1803                 tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1804                 connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1805                     ipst);
1806                 if (connp == NULL)
1807                         goto discard_pkt;
1808 
1809                 if ((connp->conn_verifyicmp != NULL) &&
1810                     !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1811                         CONN_DEC_REF(connp);
1812                         goto discard_pkt;
1813                 }
1814                 CONN_DEC_REF(connp);
1815                 break;
1816         }
1817         case IPPROTO_SCTP:
1818                 /*
1819                  * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1820                  * transport header.
1821                  */
1822                 if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1823                     mp->b_wptr)
1824                         goto truncated;
1825                 break;
1826         case IPPROTO_ESP:
1827         case IPPROTO_AH:
1828                 break;
1829         case IPPROTO_ENCAP:
1830                 if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1831                     mp->b_wptr)
1832                         goto truncated;
1833                 break;
1834         default:
1835                 break;
1836         }
1837 
1838         return (B_TRUE);
1839 
1840 discard_pkt:
1841         /* Bogus ICMP error. */
1842         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1843         return (B_FALSE);
1844 
1845 truncated:
1846         /* We pulled up everthing already. Must be truncated */
1847         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1848         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1849         return (B_FALSE);
1850 }
1851 
1852 /* Table from RFC 1191 */
1853 static int icmp_frag_size_table[] =
1854 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1855 
1856 /*
1857  * Process received ICMP Packet too big.
1858  * Just handles the DCE create/update, including using the above table of
1859  * PMTU guesses. The caller is responsible for validating the packet before
1860  * passing it in and also to fanout the ICMP error to any matching transport
1861  * conns. Assumes the message has been fully pulled up and verified.
1862  *
1863  * Before getting here, the caller has called icmp_inbound_verify_v4()
1864  * that should have verified with ULP to prevent undoing the changes we're
1865  * going to make to DCE. For example, TCP might have verified that the packet
1866  * which generated error is in the send window.
1867  *
1868  * In some cases modified this MTU in the ICMP header packet; the caller
1869  * should pass to the matching ULP after this returns.
1870  */
1871 static void
1872 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1873 {
1874         dce_t           *dce;
1875         int             old_mtu;
1876         int             mtu, orig_mtu;
1877         ipaddr_t        dst;
1878         boolean_t       disable_pmtud;
1879         ill_t           *ill = ira->ira_ill;
1880         ip_stack_t      *ipst = ill->ill_ipst;
1881         uint_t          hdr_length;
1882         ipha_t          *ipha;
1883 
1884         /* Caller already pulled up everything. */
1885         ipha = (ipha_t *)&icmph[1];
1886         ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1887             icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1888         ASSERT(ill != NULL);
1889 
1890         hdr_length = IPH_HDR_LENGTH(ipha);
1891 
1892         /*
1893          * We handle path MTU for source routed packets since the DCE
1894          * is looked up using the final destination.
1895          */
1896         dst = ip_get_dst(ipha);
1897 
1898         dce = dce_lookup_and_add_v4(dst, ipst);
1899         if (dce == NULL) {
1900                 /* Couldn't add a unique one - ENOMEM */
1901                 ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1902                     ntohl(dst)));
1903                 return;
1904         }
1905 
1906         /* Check for MTU discovery advice as described in RFC 1191 */
1907         mtu = ntohs(icmph->icmph_du_mtu);
1908         orig_mtu = mtu;
1909         disable_pmtud = B_FALSE;
1910 
1911         mutex_enter(&dce->dce_lock);
1912         if (dce->dce_flags & DCEF_PMTU)
1913                 old_mtu = dce->dce_pmtu;
1914         else
1915                 old_mtu = ill->ill_mtu;
1916 
1917         if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1918                 uint32_t length;
1919                 int     i;
1920 
1921                 /*
1922                  * Use the table from RFC 1191 to figure out
1923                  * the next "plateau" based on the length in
1924                  * the original IP packet.
1925                  */
1926                 length = ntohs(ipha->ipha_length);
1927                 DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1928                     uint32_t, length);
1929                 if (old_mtu <= length &&
1930                     old_mtu >= length - hdr_length) {
1931                         /*
1932                          * Handle broken BSD 4.2 systems that
1933                          * return the wrong ipha_length in ICMP
1934                          * errors.
1935                          */
1936                         ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1937                             length, old_mtu));
1938                         length -= hdr_length;
1939                 }
1940                 for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1941                         if (length > icmp_frag_size_table[i])
1942                                 break;
1943                 }
1944                 if (i == A_CNT(icmp_frag_size_table)) {
1945                         /* Smaller than IP_MIN_MTU! */
1946                         ip1dbg(("Too big for packet size %d\n",
1947                             length));
1948                         disable_pmtud = B_TRUE;
1949                         mtu = ipst->ips_ip_pmtu_min;
1950                 } else {
1951                         mtu = icmp_frag_size_table[i];
1952                         ip1dbg(("Calculated mtu %d, packet size %d, "
1953                             "before %d\n", mtu, length, old_mtu));
1954                         if (mtu < ipst->ips_ip_pmtu_min) {
1955                                 mtu = ipst->ips_ip_pmtu_min;
1956                                 disable_pmtud = B_TRUE;
1957                         }
1958                 }
1959         }
1960         if (disable_pmtud)
1961                 dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1962         else
1963                 dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1964 
1965         dce->dce_pmtu = MIN(old_mtu, mtu);
1966         /* Prepare to send the new max frag size for the ULP. */
1967         icmph->icmph_du_zero = 0;
1968         icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1969         DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1970             dce, int, orig_mtu, int, mtu);
1971 
1972         /* We now have a PMTU for sure */
1973         dce->dce_flags |= DCEF_PMTU;
1974         dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1975         mutex_exit(&dce->dce_lock);
1976         /*
1977          * After dropping the lock the new value is visible to everyone.
1978          * Then we bump the generation number so any cached values reinspect
1979          * the dce_t.
1980          */
1981         dce_increment_generation(dce);
1982         dce_refrele(dce);
1983 }
1984 
1985 /*
1986  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1987  * calls this function.
1988  */
1989 static mblk_t *
1990 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1991 {
1992         int length;
1993 
1994         ASSERT(mp->b_datap->db_type == M_DATA);
1995 
1996         /* icmp_inbound_v4 has already pulled up the whole error packet */
1997         ASSERT(mp->b_cont == NULL);
1998 
1999         /*
2000          * The length that we want to overlay is the inner header
2001          * and what follows it.
2002          */
2003         length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2004 
2005         /*
2006          * Overlay the inner header and whatever follows it over the
2007          * outer header.
2008          */
2009         bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2010 
2011         /* Adjust for what we removed */
2012         mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2013         return (mp);
2014 }
2015 
2016 /*
2017  * Try to pass the ICMP message upstream in case the ULP cares.
2018  *
2019  * If the packet that caused the ICMP error is secure, we send
2020  * it to AH/ESP to make sure that the attached packet has a
2021  * valid association. ipha in the code below points to the
2022  * IP header of the packet that caused the error.
2023  *
2024  * For IPsec cases, we let the next-layer-up (which has access to
2025  * cached policy on the conn_t, or can query the SPD directly)
2026  * subtract out any IPsec overhead if they must.  We therefore make no
2027  * adjustments here for IPsec overhead.
2028  *
2029  * IFN could have been generated locally or by some router.
2030  *
2031  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2032  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2033  *          This happens because IP adjusted its value of MTU on an
2034  *          earlier IFN message and could not tell the upper layer,
2035  *          the new adjusted value of MTU e.g. Packet was encrypted
2036  *          or there was not enough information to fanout to upper
2037  *          layers. Thus on the next outbound datagram, ire_send_wire
2038  *          generates the IFN, where IPsec processing has *not* been
2039  *          done.
2040  *
2041  *          Note that we retain ixa_fragsize across IPsec thus once
2042  *          we have picking ixa_fragsize and entered ipsec_out_process we do
2043  *          no change the fragsize even if the path MTU changes before
2044  *          we reach ip_output_post_ipsec.
2045  *
2046  *          In the local case, IRAF_LOOPBACK will be set indicating
2047  *          that IFN was generated locally.
2048  *
2049  * ROUTER : IFN could be secure or non-secure.
2050  *
2051  *          * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2052  *            packet in error has AH/ESP headers to validate the AH/ESP
2053  *            headers. AH/ESP will verify whether there is a valid SA or
2054  *            not and send it back. We will fanout again if we have more
2055  *            data in the packet.
2056  *
2057  *            If the packet in error does not have AH/ESP, we handle it
2058  *            like any other case.
2059  *
2060  *          * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2061  *            up to AH/ESP for validation. AH/ESP will verify whether there is a
2062  *            valid SA or not and send it back. We will fanout again if
2063  *            we have more data in the packet.
2064  *
2065  *            If the packet in error does not have AH/ESP, we handle it
2066  *            like any other case.
2067  *
2068  * The caller must have called icmp_inbound_verify_v4.
2069  */
2070 static void
2071 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2072 {
2073         uint16_t        *up;    /* Pointer to ports in ULP header */
2074         uint32_t        ports;  /* reversed ports for fanout */
2075         ipha_t          ripha;  /* With reversed addresses */
2076         ipha_t          *ipha;  /* Inner IP header */
2077         uint_t          hdr_length; /* Inner IP header length */
2078         tcpha_t         *tcpha;
2079         conn_t          *connp;
2080         ill_t           *ill = ira->ira_ill;
2081         ip_stack_t      *ipst = ill->ill_ipst;
2082         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
2083         ill_t           *rill = ira->ira_rill;
2084 
2085         /* Caller already pulled up everything. */
2086         ipha = (ipha_t *)&icmph[1];
2087         ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2088         ASSERT(mp->b_cont == NULL);
2089 
2090         hdr_length = IPH_HDR_LENGTH(ipha);
2091         ira->ira_protocol = ipha->ipha_protocol;
2092 
2093         /*
2094          * We need a separate IP header with the source and destination
2095          * addresses reversed to do fanout/classification because the ipha in
2096          * the ICMP error is in the form we sent it out.
2097          */
2098         ripha.ipha_src = ipha->ipha_dst;
2099         ripha.ipha_dst = ipha->ipha_src;
2100         ripha.ipha_protocol = ipha->ipha_protocol;
2101         ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2102 
2103         ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2104             ripha.ipha_protocol, ntohl(ipha->ipha_src),
2105             ntohl(ipha->ipha_dst),
2106             icmph->icmph_type, icmph->icmph_code));
2107 
2108         switch (ipha->ipha_protocol) {
2109         case IPPROTO_UDP:
2110                 up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2111 
2112                 /* Attempt to find a client stream based on port. */
2113                 ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2114                     ntohs(up[0]), ntohs(up[1])));
2115 
2116                 /* Note that we send error to all matches. */
2117                 ira->ira_flags |= IRAF_ICMP_ERROR;
2118                 ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2119                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2120                 return;
2121 
2122         case IPPROTO_TCP:
2123                 /*
2124                  * Find a TCP client stream for this packet.
2125                  * Note that we do a reverse lookup since the header is
2126                  * in the form we sent it out.
2127                  */
2128                 tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2129                 connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2130                     ipst);
2131                 if (connp == NULL)
2132                         goto discard_pkt;
2133 
2134                 if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2135                     (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2136                         mp = ipsec_check_inbound_policy(mp, connp,
2137                             ipha, NULL, ira);
2138                         if (mp == NULL) {
2139                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2140                                 /* Note that mp is NULL */
2141                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
2142                                 CONN_DEC_REF(connp);
2143                                 return;
2144                         }
2145                 }
2146 
2147                 ira->ira_flags |= IRAF_ICMP_ERROR;
2148                 ira->ira_ill = ira->ira_rill = NULL;
2149                 if (IPCL_IS_TCP(connp)) {
2150                         SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2151                             connp->conn_recvicmp, connp, ira, SQ_FILL,
2152                             SQTAG_TCP_INPUT_ICMP_ERR);
2153                 } else {
2154                         /* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2155                         (connp->conn_recv)(connp, mp, NULL, ira);
2156                         CONN_DEC_REF(connp);
2157                 }
2158                 ira->ira_ill = ill;
2159                 ira->ira_rill = rill;
2160                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2161                 return;
2162 
2163         case IPPROTO_SCTP:
2164                 up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2165                 /* Find a SCTP client stream for this packet. */
2166                 ((uint16_t *)&ports)[0] = up[1];
2167                 ((uint16_t *)&ports)[1] = up[0];
2168 
2169                 ira->ira_flags |= IRAF_ICMP_ERROR;
2170                 ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2171                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2172                 return;
2173 
2174         case IPPROTO_ESP:
2175         case IPPROTO_AH:
2176                 if (!ipsec_loaded(ipss)) {
2177                         ip_proto_not_sup(mp, ira);
2178                         return;
2179                 }
2180 
2181                 if (ipha->ipha_protocol == IPPROTO_ESP)
2182                         mp = ipsecesp_icmp_error(mp, ira);
2183                 else
2184                         mp = ipsecah_icmp_error(mp, ira);
2185                 if (mp == NULL)
2186                         return;
2187 
2188                 /* Just in case ipsec didn't preserve the NULL b_cont */
2189                 if (mp->b_cont != NULL) {
2190                         if (!pullupmsg(mp, -1))
2191                                 goto discard_pkt;
2192                 }
2193 
2194                 /*
2195                  * Note that ira_pktlen and ira_ip_hdr_length are no longer
2196                  * correct, but we don't use them any more here.
2197                  *
2198                  * If succesful, the mp has been modified to not include
2199                  * the ESP/AH header so we can fanout to the ULP's icmp
2200                  * error handler.
2201                  */
2202                 if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2203                         goto truncated;
2204 
2205                 /* Verify the modified message before any further processes. */
2206                 ipha = (ipha_t *)mp->b_rptr;
2207                 hdr_length = IPH_HDR_LENGTH(ipha);
2208                 icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2209                 if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2210                         freemsg(mp);
2211                         return;
2212                 }
2213 
2214                 icmp_inbound_error_fanout_v4(mp, icmph, ira);
2215                 return;
2216 
2217         case IPPROTO_ENCAP: {
2218                 /* Look for self-encapsulated packets that caused an error */
2219                 ipha_t *in_ipha;
2220 
2221                 /*
2222                  * Caller has verified that length has to be
2223                  * at least the size of IP header.
2224                  */
2225                 ASSERT(hdr_length >= sizeof (ipha_t));
2226                 /*
2227                  * Check the sanity of the inner IP header like
2228                  * we did for the outer header.
2229                  */
2230                 in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2231                 if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2232                         goto discard_pkt;
2233                 }
2234                 if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2235                         goto discard_pkt;
2236                 }
2237                 /* Check for Self-encapsulated tunnels */
2238                 if (in_ipha->ipha_src == ipha->ipha_src &&
2239                     in_ipha->ipha_dst == ipha->ipha_dst) {
2240 
2241                         mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2242                             in_ipha);
2243                         if (mp == NULL)
2244                                 goto discard_pkt;
2245 
2246                         /*
2247                          * Just in case self_encap didn't preserve the NULL
2248                          * b_cont
2249                          */
2250                         if (mp->b_cont != NULL) {
2251                                 if (!pullupmsg(mp, -1))
2252                                         goto discard_pkt;
2253                         }
2254                         /*
2255                          * Note that ira_pktlen and ira_ip_hdr_length are no
2256                          * longer correct, but we don't use them any more here.
2257                          */
2258                         if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2259                                 goto truncated;
2260 
2261                         /*
2262                          * Verify the modified message before any further
2263                          * processes.
2264                          */
2265                         ipha = (ipha_t *)mp->b_rptr;
2266                         hdr_length = IPH_HDR_LENGTH(ipha);
2267                         icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2268                         if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2269                                 freemsg(mp);
2270                                 return;
2271                         }
2272 
2273                         /*
2274                          * The packet in error is self-encapsualted.
2275                          * And we are finding it further encapsulated
2276                          * which we could not have possibly generated.
2277                          */
2278                         if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2279                                 goto discard_pkt;
2280                         }
2281                         icmp_inbound_error_fanout_v4(mp, icmph, ira);
2282                         return;
2283                 }
2284                 /* No self-encapsulated */
2285                 /* FALLTHRU */
2286         }
2287         case IPPROTO_IPV6:
2288                 if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2289                     &ripha.ipha_dst, ipst)) != NULL) {
2290                         ira->ira_flags |= IRAF_ICMP_ERROR;
2291                         connp->conn_recvicmp(connp, mp, NULL, ira);
2292                         CONN_DEC_REF(connp);
2293                         ira->ira_flags &= ~IRAF_ICMP_ERROR;
2294                         return;
2295                 }
2296                 /*
2297                  * No IP tunnel is interested, fallthrough and see
2298                  * if a raw socket will want it.
2299                  */
2300                 /* FALLTHRU */
2301         default:
2302                 ira->ira_flags |= IRAF_ICMP_ERROR;
2303                 ip_fanout_proto_v4(mp, &ripha, ira);
2304                 ira->ira_flags &= ~IRAF_ICMP_ERROR;
2305                 return;
2306         }
2307         /* NOTREACHED */
2308 discard_pkt:
2309         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2310         ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2311         ip_drop_input("ipIfStatsInDiscards", mp, ill);
2312         freemsg(mp);
2313         return;
2314 
2315 truncated:
2316         /* We pulled up everthing already. Must be truncated */
2317         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2318         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2319         freemsg(mp);
2320 }
2321 
2322 /*
2323  * Common IP options parser.
2324  *
2325  * Setup routine: fill in *optp with options-parsing state, then
2326  * tail-call ipoptp_next to return the first option.
2327  */
2328 uint8_t
2329 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2330 {
2331         uint32_t totallen; /* total length of all options */
2332 
2333         totallen = ipha->ipha_version_and_hdr_length -
2334             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2335         totallen <<= 2;
2336         optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2337         optp->ipoptp_end = optp->ipoptp_next + totallen;
2338         optp->ipoptp_flags = 0;
2339         return (ipoptp_next(optp));
2340 }
2341 
2342 /* Like above but without an ipha_t */
2343 uint8_t
2344 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2345 {
2346         optp->ipoptp_next = opt;
2347         optp->ipoptp_end = optp->ipoptp_next + totallen;
2348         optp->ipoptp_flags = 0;
2349         return (ipoptp_next(optp));
2350 }
2351 
2352 /*
2353  * Common IP options parser: extract next option.
2354  */
2355 uint8_t
2356 ipoptp_next(ipoptp_t *optp)
2357 {
2358         uint8_t *end = optp->ipoptp_end;
2359         uint8_t *cur = optp->ipoptp_next;
2360         uint8_t opt, len, pointer;
2361 
2362         /*
2363          * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2364          * has been corrupted.
2365          */
2366         ASSERT(cur <= end);
2367 
2368         if (cur == end)
2369                 return (IPOPT_EOL);
2370 
2371         opt = cur[IPOPT_OPTVAL];
2372 
2373         /*
2374          * Skip any NOP options.
2375          */
2376         while (opt == IPOPT_NOP) {
2377                 cur++;
2378                 if (cur == end)
2379                         return (IPOPT_EOL);
2380                 opt = cur[IPOPT_OPTVAL];
2381         }
2382 
2383         if (opt == IPOPT_EOL)
2384                 return (IPOPT_EOL);
2385 
2386         /*
2387          * Option requiring a length.
2388          */
2389         if ((cur + 1) >= end) {
2390                 optp->ipoptp_flags |= IPOPTP_ERROR;
2391                 return (IPOPT_EOL);
2392         }
2393         len = cur[IPOPT_OLEN];
2394         if (len < 2) {
2395                 optp->ipoptp_flags |= IPOPTP_ERROR;
2396                 return (IPOPT_EOL);
2397         }
2398         optp->ipoptp_cur = cur;
2399         optp->ipoptp_len = len;
2400         optp->ipoptp_next = cur + len;
2401         if (cur + len > end) {
2402                 optp->ipoptp_flags |= IPOPTP_ERROR;
2403                 return (IPOPT_EOL);
2404         }
2405 
2406         /*
2407          * For the options which require a pointer field, make sure
2408          * its there, and make sure it points to either something
2409          * inside this option, or the end of the option.
2410          */
2411         switch (opt) {
2412         case IPOPT_RR:
2413         case IPOPT_TS:
2414         case IPOPT_LSRR:
2415         case IPOPT_SSRR:
2416                 if (len <= IPOPT_OFFSET) {
2417                         optp->ipoptp_flags |= IPOPTP_ERROR;
2418                         return (opt);
2419                 }
2420                 pointer = cur[IPOPT_OFFSET];
2421                 if (pointer - 1 > len) {
2422                         optp->ipoptp_flags |= IPOPTP_ERROR;
2423                         return (opt);
2424                 }
2425                 break;
2426         }
2427 
2428         /*
2429          * Sanity check the pointer field based on the type of the
2430          * option.
2431          */
2432         switch (opt) {
2433         case IPOPT_RR:
2434         case IPOPT_SSRR:
2435         case IPOPT_LSRR:
2436                 if (pointer < IPOPT_MINOFF_SR)
2437                         optp->ipoptp_flags |= IPOPTP_ERROR;
2438                 break;
2439         case IPOPT_TS:
2440                 if (pointer < IPOPT_MINOFF_IT)
2441                         optp->ipoptp_flags |= IPOPTP_ERROR;
2442                 /*
2443                  * Note that the Internet Timestamp option also
2444                  * contains two four bit fields (the Overflow field,
2445                  * and the Flag field), which follow the pointer
2446                  * field.  We don't need to check that these fields
2447                  * fall within the length of the option because this
2448                  * was implicitely done above.  We've checked that the
2449                  * pointer value is at least IPOPT_MINOFF_IT, and that
2450                  * it falls within the option.  Since IPOPT_MINOFF_IT >
2451                  * IPOPT_POS_OV_FLG, we don't need the explicit check.
2452                  */
2453                 ASSERT(len > IPOPT_POS_OV_FLG);
2454                 break;
2455         }
2456 
2457         return (opt);
2458 }
2459 
2460 /*
2461  * Use the outgoing IP header to create an IP_OPTIONS option the way
2462  * it was passed down from the application.
2463  *
2464  * This is compatible with BSD in that it returns
2465  * the reverse source route with the final destination
2466  * as the last entry. The first 4 bytes of the option
2467  * will contain the final destination.
2468  */
2469 int
2470 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2471 {
2472         ipoptp_t        opts;
2473         uchar_t         *opt;
2474         uint8_t         optval;
2475         uint8_t         optlen;
2476         uint32_t        len = 0;
2477         uchar_t         *buf1 = buf;
2478         uint32_t        totallen;
2479         ipaddr_t        dst;
2480         ip_pkt_t        *ipp = &connp->conn_xmit_ipp;
2481 
2482         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2483                 return (0);
2484 
2485         totallen = ipp->ipp_ipv4_options_len;
2486         if (totallen & 0x3)
2487                 return (0);
2488 
2489         buf += IP_ADDR_LEN;     /* Leave room for final destination */
2490         len += IP_ADDR_LEN;
2491         bzero(buf1, IP_ADDR_LEN);
2492 
2493         dst = connp->conn_faddr_v4;
2494 
2495         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2496             optval != IPOPT_EOL;
2497             optval = ipoptp_next(&opts)) {
2498                 int     off;
2499 
2500                 opt = opts.ipoptp_cur;
2501                 if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2502                         break;
2503                 }
2504                 optlen = opts.ipoptp_len;
2505 
2506                 switch (optval) {
2507                 case IPOPT_SSRR:
2508                 case IPOPT_LSRR:
2509 
2510                         /*
2511                          * Insert destination as the first entry in the source
2512                          * route and move down the entries on step.
2513                          * The last entry gets placed at buf1.
2514                          */
2515                         buf[IPOPT_OPTVAL] = optval;
2516                         buf[IPOPT_OLEN] = optlen;
2517                         buf[IPOPT_OFFSET] = optlen;
2518 
2519                         off = optlen - IP_ADDR_LEN;
2520                         if (off < 0) {
2521                                 /* No entries in source route */
2522                                 break;
2523                         }
2524                         /* Last entry in source route if not already set */
2525                         if (dst == INADDR_ANY)
2526                                 bcopy(opt + off, buf1, IP_ADDR_LEN);
2527                         off -= IP_ADDR_LEN;
2528 
2529                         while (off > 0) {
2530                                 bcopy(opt + off,
2531                                     buf + off + IP_ADDR_LEN,
2532                                     IP_ADDR_LEN);
2533                                 off -= IP_ADDR_LEN;
2534                         }
2535                         /* ipha_dst into first slot */
2536                         bcopy(&dst, buf + off + IP_ADDR_LEN,
2537                             IP_ADDR_LEN);
2538                         buf += optlen;
2539                         len += optlen;
2540                         break;
2541 
2542                 default:
2543                         bcopy(opt, buf, optlen);
2544                         buf += optlen;
2545                         len += optlen;
2546                         break;
2547                 }
2548         }
2549 done:
2550         /* Pad the resulting options */
2551         while (len & 0x3) {
2552                 *buf++ = IPOPT_EOL;
2553                 len++;
2554         }
2555         return (len);
2556 }
2557 
2558 /*
2559  * Update any record route or timestamp options to include this host.
2560  * Reverse any source route option.
2561  * This routine assumes that the options are well formed i.e. that they
2562  * have already been checked.
2563  */
2564 static void
2565 icmp_options_update(ipha_t *ipha)
2566 {
2567         ipoptp_t        opts;
2568         uchar_t         *opt;
2569         uint8_t         optval;
2570         ipaddr_t        src;            /* Our local address */
2571         ipaddr_t        dst;
2572 
2573         ip2dbg(("icmp_options_update\n"));
2574         src = ipha->ipha_src;
2575         dst = ipha->ipha_dst;
2576 
2577         for (optval = ipoptp_first(&opts, ipha);
2578             optval != IPOPT_EOL;
2579             optval = ipoptp_next(&opts)) {
2580                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2581                 opt = opts.ipoptp_cur;
2582                 ip2dbg(("icmp_options_update: opt %d, len %d\n",
2583                     optval, opts.ipoptp_len));
2584                 switch (optval) {
2585                         int off1, off2;
2586                 case IPOPT_SSRR:
2587                 case IPOPT_LSRR:
2588                         /*
2589                          * Reverse the source route.  The first entry
2590                          * should be the next to last one in the current
2591                          * source route (the last entry is our address).
2592                          * The last entry should be the final destination.
2593                          */
2594                         off1 = IPOPT_MINOFF_SR - 1;
2595                         off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2596                         if (off2 < 0) {
2597                                 /* No entries in source route */
2598                                 ip1dbg((
2599                                     "icmp_options_update: bad src route\n"));
2600                                 break;
2601                         }
2602                         bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2603                         bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2604                         bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2605                         off2 -= IP_ADDR_LEN;
2606 
2607                         while (off1 < off2) {
2608                                 bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2609                                 bcopy((char *)opt + off2, (char *)opt + off1,
2610                                     IP_ADDR_LEN);
2611                                 bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2612                                 off1 += IP_ADDR_LEN;
2613                                 off2 -= IP_ADDR_LEN;
2614                         }
2615                         opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2616                         break;
2617                 }
2618         }
2619 }
2620 
2621 /*
2622  * Process received ICMP Redirect messages.
2623  * Assumes the caller has verified that the headers are in the pulled up mblk.
2624  * Consumes mp.
2625  */
2626 static void
2627 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2628 {
2629         ire_t           *ire, *nire;
2630         ire_t           *prev_ire;
2631         ipaddr_t        src, dst, gateway;
2632         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2633         ipha_t          *inner_ipha;    /* Inner IP header */
2634 
2635         /* Caller already pulled up everything. */
2636         inner_ipha = (ipha_t *)&icmph[1];
2637         src = ipha->ipha_src;
2638         dst = inner_ipha->ipha_dst;
2639         gateway = icmph->icmph_rd_gateway;
2640         /* Make sure the new gateway is reachable somehow. */
2641         ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2642             ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2643         /*
2644          * Make sure we had a route for the dest in question and that
2645          * that route was pointing to the old gateway (the source of the
2646          * redirect packet.)
2647          * We do longest match and then compare ire_gateway_addr below.
2648          */
2649         prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2650             NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2651         /*
2652          * Check that
2653          *      the redirect was not from ourselves
2654          *      the new gateway and the old gateway are directly reachable
2655          */
2656         if (prev_ire == NULL || ire == NULL ||
2657             (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2658             (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2659             !(ire->ire_type & IRE_IF_ALL) ||
2660             prev_ire->ire_gateway_addr != src) {
2661                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2662                 ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2663                 freemsg(mp);
2664                 if (ire != NULL)
2665                         ire_refrele(ire);
2666                 if (prev_ire != NULL)
2667                         ire_refrele(prev_ire);
2668                 return;
2669         }
2670 
2671         ire_refrele(prev_ire);
2672         ire_refrele(ire);
2673 
2674         /*
2675          * TODO: more precise handling for cases 0, 2, 3, the latter two
2676          * require TOS routing
2677          */
2678         switch (icmph->icmph_code) {
2679         case 0:
2680         case 1:
2681                 /* TODO: TOS specificity for cases 2 and 3 */
2682         case 2:
2683         case 3:
2684                 break;
2685         default:
2686                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2687                 ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2688                 freemsg(mp);
2689                 return;
2690         }
2691         /*
2692          * Create a Route Association.  This will allow us to remember that
2693          * someone we believe told us to use the particular gateway.
2694          */
2695         ire = ire_create(
2696             (uchar_t *)&dst,                        /* dest addr */
2697             (uchar_t *)&ip_g_all_ones,              /* mask */
2698             (uchar_t *)&gateway,            /* gateway addr */
2699             IRE_HOST,
2700             NULL,                               /* ill */
2701             ALL_ZONES,
2702             (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2703             NULL,                               /* tsol_gc_t */
2704             ipst);
2705 
2706         if (ire == NULL) {
2707                 freemsg(mp);
2708                 return;
2709         }
2710         nire = ire_add(ire);
2711         /* Check if it was a duplicate entry */
2712         if (nire != NULL && nire != ire) {
2713                 ASSERT(nire->ire_identical_ref > 1);
2714                 ire_delete(nire);
2715                 ire_refrele(nire);
2716                 nire = NULL;
2717         }
2718         ire = nire;
2719         if (ire != NULL) {
2720                 ire_refrele(ire);               /* Held in ire_add */
2721 
2722                 /* tell routing sockets that we received a redirect */
2723                 ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2724                     (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2725                     (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2726         }
2727 
2728         /*
2729          * Delete any existing IRE_HOST type redirect ires for this destination.
2730          * This together with the added IRE has the effect of
2731          * modifying an existing redirect.
2732          */
2733         prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2734             ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2735         if (prev_ire != NULL) {
2736                 if (prev_ire ->ire_flags & RTF_DYNAMIC)
2737                         ire_delete(prev_ire);
2738                 ire_refrele(prev_ire);
2739         }
2740 
2741         freemsg(mp);
2742 }
2743 
2744 /*
2745  * Generate an ICMP parameter problem message.
2746  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2747  * constructed by the caller.
2748  */
2749 static void
2750 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2751 {
2752         icmph_t icmph;
2753         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2754 
2755         mp = icmp_pkt_err_ok(mp, ira);
2756         if (mp == NULL)
2757                 return;
2758 
2759         bzero(&icmph, sizeof (icmph_t));
2760         icmph.icmph_type = ICMP_PARAM_PROBLEM;
2761         icmph.icmph_pp_ptr = ptr;
2762         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2763         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2764 }
2765 
2766 /*
2767  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2768  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2769  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2770  * an icmp error packet can be sent.
2771  * Assigns an appropriate source address to the packet. If ipha_dst is
2772  * one of our addresses use it for source. Otherwise let ip_output_simple
2773  * pick the source address.
2774  */
2775 static void
2776 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2777 {
2778         ipaddr_t dst;
2779         icmph_t *icmph;
2780         ipha_t  *ipha;
2781         uint_t  len_needed;
2782         size_t  msg_len;
2783         mblk_t  *mp1;
2784         ipaddr_t src;
2785         ire_t   *ire;
2786         ip_xmit_attr_t ixas;
2787         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2788 
2789         ipha = (ipha_t *)mp->b_rptr;
2790 
2791         bzero(&ixas, sizeof (ixas));
2792         ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2793         ixas.ixa_zoneid = ira->ira_zoneid;
2794         ixas.ixa_ifindex = 0;
2795         ixas.ixa_ipst = ipst;
2796         ixas.ixa_cred = kcred;
2797         ixas.ixa_cpid = NOPID;
2798         ixas.ixa_tsl = ira->ira_tsl; /* Behave as a multi-level responder */
2799         ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2800 
2801         if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2802                 /*
2803                  * Apply IPsec based on how IPsec was applied to
2804                  * the packet that had the error.
2805                  *
2806                  * If it was an outbound packet that caused the ICMP
2807                  * error, then the caller will have setup the IRA
2808                  * appropriately.
2809                  */
2810                 if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2811                         BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2812                         /* Note: mp already consumed and ip_drop_packet done */
2813                         return;
2814                 }
2815         } else {
2816                 /*
2817                  * This is in clear. The icmp message we are building
2818                  * here should go out in clear, independent of our policy.
2819                  */
2820                 ixas.ixa_flags |= IXAF_NO_IPSEC;
2821         }
2822 
2823         /* Remember our eventual destination */
2824         dst = ipha->ipha_src;
2825 
2826         /*
2827          * If the packet was for one of our unicast addresses, make
2828          * sure we respond with that as the source. Otherwise
2829          * have ip_output_simple pick the source address.
2830          */
2831         ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2832             (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2833             MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2834         if (ire != NULL) {
2835                 ire_refrele(ire);
2836                 src = ipha->ipha_dst;
2837         } else {
2838                 src = INADDR_ANY;
2839                 ixas.ixa_flags |= IXAF_SET_SOURCE;
2840         }
2841 
2842         /*
2843          * Check if we can send back more then 8 bytes in addition to
2844          * the IP header.  We try to send 64 bytes of data and the internal
2845          * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2846          */
2847         len_needed = IPH_HDR_LENGTH(ipha);
2848         if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2849             ipha->ipha_protocol == IPPROTO_IPV6) {
2850                 if (!pullupmsg(mp, -1)) {
2851                         BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2852                         ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2853                         freemsg(mp);
2854                         return;
2855                 }
2856                 ipha = (ipha_t *)mp->b_rptr;
2857 
2858                 if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2859                         len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2860                             len_needed));
2861                 } else {
2862                         ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2863 
2864                         ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2865                         len_needed += ip_hdr_length_v6(mp, ip6h);
2866                 }
2867         }
2868         len_needed += ipst->ips_ip_icmp_return;
2869         msg_len = msgdsize(mp);
2870         if (msg_len > len_needed) {
2871                 (void) adjmsg(mp, len_needed - msg_len);
2872                 msg_len = len_needed;
2873         }
2874         mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2875         if (mp1 == NULL) {
2876                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2877                 freemsg(mp);
2878                 return;
2879         }
2880         mp1->b_cont = mp;
2881         mp = mp1;
2882 
2883         /*
2884          * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2885          * node generates be accepted in peace by all on-host destinations.
2886          * If we do NOT assume that all on-host destinations trust
2887          * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2888          * (Look for IXAF_TRUSTED_ICMP).
2889          */
2890         ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2891 
2892         ipha = (ipha_t *)mp->b_rptr;
2893         mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2894         *ipha = icmp_ipha;
2895         ipha->ipha_src = src;
2896         ipha->ipha_dst = dst;
2897         ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2898         msg_len += sizeof (icmp_ipha) + len;
2899         if (msg_len > IP_MAXPACKET) {
2900                 (void) adjmsg(mp, IP_MAXPACKET - msg_len);
2901                 msg_len = IP_MAXPACKET;
2902         }
2903         ipha->ipha_length = htons((uint16_t)msg_len);
2904         icmph = (icmph_t *)&ipha[1];
2905         bcopy(stuff, icmph, len);
2906         icmph->icmph_checksum = 0;
2907         icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2908         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2909 
2910         (void) ip_output_simple(mp, &ixas);
2911         ixa_cleanup(&ixas);
2912 }
2913 
2914 /*
2915  * Determine if an ICMP error packet can be sent given the rate limit.
2916  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2917  * in milliseconds) and a burst size. Burst size number of packets can
2918  * be sent arbitrarely closely spaced.
2919  * The state is tracked using two variables to implement an approximate
2920  * token bucket filter:
2921  *      icmp_pkt_err_last - lbolt value when the last burst started
2922  *      icmp_pkt_err_sent - number of packets sent in current burst
2923  */
2924 boolean_t
2925 icmp_err_rate_limit(ip_stack_t *ipst)
2926 {
2927         clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2928         uint_t refilled; /* Number of packets refilled in tbf since last */
2929         /* Guard against changes by loading into local variable */
2930         uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2931 
2932         if (err_interval == 0)
2933                 return (B_FALSE);
2934 
2935         if (ipst->ips_icmp_pkt_err_last > now) {
2936                 /* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2937                 ipst->ips_icmp_pkt_err_last = 0;
2938                 ipst->ips_icmp_pkt_err_sent = 0;
2939         }
2940         /*
2941          * If we are in a burst update the token bucket filter.
2942          * Update the "last" time to be close to "now" but make sure
2943          * we don't loose precision.
2944          */
2945         if (ipst->ips_icmp_pkt_err_sent != 0) {
2946                 refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2947                 if (refilled > ipst->ips_icmp_pkt_err_sent) {
2948                         ipst->ips_icmp_pkt_err_sent = 0;
2949                 } else {
2950                         ipst->ips_icmp_pkt_err_sent -= refilled;
2951                         ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2952                 }
2953         }
2954         if (ipst->ips_icmp_pkt_err_sent == 0) {
2955                 /* Start of new burst */
2956                 ipst->ips_icmp_pkt_err_last = now;
2957         }
2958         if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2959                 ipst->ips_icmp_pkt_err_sent++;
2960                 ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2961                     ipst->ips_icmp_pkt_err_sent));
2962                 return (B_FALSE);
2963         }
2964         ip1dbg(("icmp_err_rate_limit: dropped\n"));
2965         return (B_TRUE);
2966 }
2967 
2968 /*
2969  * Check if it is ok to send an IPv4 ICMP error packet in
2970  * response to the IPv4 packet in mp.
2971  * Free the message and return null if no
2972  * ICMP error packet should be sent.
2973  */
2974 static mblk_t *
2975 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2976 {
2977         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
2978         icmph_t *icmph;
2979         ipha_t  *ipha;
2980         uint_t  len_needed;
2981 
2982         if (!mp)
2983                 return (NULL);
2984         ipha = (ipha_t *)mp->b_rptr;
2985         if (ip_csum_hdr(ipha)) {
2986                 BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2987                 ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2988                 freemsg(mp);
2989                 return (NULL);
2990         }
2991         if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2992             ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2993             CLASSD(ipha->ipha_dst) ||
2994             CLASSD(ipha->ipha_src) ||
2995             (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2996                 /* Note: only errors to the fragment with offset 0 */
2997                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2998                 freemsg(mp);
2999                 return (NULL);
3000         }
3001         if (ipha->ipha_protocol == IPPROTO_ICMP) {
3002                 /*
3003                  * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3004                  * errors in response to any ICMP errors.
3005                  */
3006                 len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3007                 if (mp->b_wptr - mp->b_rptr < len_needed) {
3008                         if (!pullupmsg(mp, len_needed)) {
3009                                 BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3010                                 freemsg(mp);
3011                                 return (NULL);
3012                         }
3013                         ipha = (ipha_t *)mp->b_rptr;
3014                 }
3015                 icmph = (icmph_t *)
3016                     (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3017                 switch (icmph->icmph_type) {
3018                 case ICMP_DEST_UNREACHABLE:
3019                 case ICMP_SOURCE_QUENCH:
3020                 case ICMP_TIME_EXCEEDED:
3021                 case ICMP_PARAM_PROBLEM:
3022                 case ICMP_REDIRECT:
3023                         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3024                         freemsg(mp);
3025                         return (NULL);
3026                 default:
3027                         break;
3028                 }
3029         }
3030         /*
3031          * If this is a labeled system, then check to see if we're allowed to
3032          * send a response to this particular sender.  If not, then just drop.
3033          */
3034         if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3035                 ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3036                 BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3037                 freemsg(mp);
3038                 return (NULL);
3039         }
3040         if (icmp_err_rate_limit(ipst)) {
3041                 /*
3042                  * Only send ICMP error packets every so often.
3043                  * This should be done on a per port/source basis,
3044                  * but for now this will suffice.
3045                  */
3046                 freemsg(mp);
3047                 return (NULL);
3048         }
3049         return (mp);
3050 }
3051 
3052 /*
3053  * Called when a packet was sent out the same link that it arrived on.
3054  * Check if it is ok to send a redirect and then send it.
3055  */
3056 void
3057 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3058     ip_recv_attr_t *ira)
3059 {
3060         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
3061         ipaddr_t        src, nhop;
3062         mblk_t          *mp1;
3063         ire_t           *nhop_ire;
3064 
3065         /*
3066          * Check the source address to see if it originated
3067          * on the same logical subnet it is going back out on.
3068          * If so, we should be able to send it a redirect.
3069          * Avoid sending a redirect if the destination
3070          * is directly connected (i.e., we matched an IRE_ONLINK),
3071          * or if the packet was source routed out this interface.
3072          *
3073          * We avoid sending a redirect if the
3074          * destination is directly connected
3075          * because it is possible that multiple
3076          * IP subnets may have been configured on
3077          * the link, and the source may not
3078          * be on the same subnet as ip destination,
3079          * even though they are on the same
3080          * physical link.
3081          */
3082         if ((ire->ire_type & IRE_ONLINK) ||
3083             ip_source_routed(ipha, ipst))
3084                 return;
3085 
3086         nhop_ire = ire_nexthop(ire);
3087         if (nhop_ire == NULL)
3088                 return;
3089 
3090         nhop = nhop_ire->ire_addr;
3091 
3092         if (nhop_ire->ire_type & IRE_IF_CLONE) {
3093                 ire_t   *ire2;
3094 
3095                 /* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3096                 mutex_enter(&nhop_ire->ire_lock);
3097                 ire2 = nhop_ire->ire_dep_parent;
3098                 if (ire2 != NULL)
3099                         ire_refhold(ire2);
3100                 mutex_exit(&nhop_ire->ire_lock);
3101                 ire_refrele(nhop_ire);
3102                 nhop_ire = ire2;
3103         }
3104         if (nhop_ire == NULL)
3105                 return;
3106 
3107         ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3108 
3109         src = ipha->ipha_src;
3110 
3111         /*
3112          * We look at the interface ire for the nexthop,
3113          * to see if ipha_src is in the same subnet
3114          * as the nexthop.
3115          */
3116         if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3117                 /*
3118                  * The source is directly connected.
3119                  */
3120                 mp1 = copymsg(mp);
3121                 if (mp1 != NULL) {
3122                         icmp_send_redirect(mp1, nhop, ira);
3123                 }
3124         }
3125         ire_refrele(nhop_ire);
3126 }
3127 
3128 /*
3129  * Generate an ICMP redirect message.
3130  */
3131 static void
3132 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3133 {
3134         icmph_t icmph;
3135         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3136 
3137         mp = icmp_pkt_err_ok(mp, ira);
3138         if (mp == NULL)
3139                 return;
3140 
3141         bzero(&icmph, sizeof (icmph_t));
3142         icmph.icmph_type = ICMP_REDIRECT;
3143         icmph.icmph_code = 1;
3144         icmph.icmph_rd_gateway = gateway;
3145         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3146         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3147 }
3148 
3149 /*
3150  * Generate an ICMP time exceeded message.
3151  */
3152 void
3153 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3154 {
3155         icmph_t icmph;
3156         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3157 
3158         mp = icmp_pkt_err_ok(mp, ira);
3159         if (mp == NULL)
3160                 return;
3161 
3162         bzero(&icmph, sizeof (icmph_t));
3163         icmph.icmph_type = ICMP_TIME_EXCEEDED;
3164         icmph.icmph_code = code;
3165         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3166         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3167 }
3168 
3169 /*
3170  * Generate an ICMP unreachable message.
3171  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3172  * constructed by the caller.
3173  */
3174 void
3175 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3176 {
3177         icmph_t icmph;
3178         ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3179 
3180         mp = icmp_pkt_err_ok(mp, ira);
3181         if (mp == NULL)
3182                 return;
3183 
3184         bzero(&icmph, sizeof (icmph_t));
3185         icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3186         icmph.icmph_code = code;
3187         BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3188         icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3189 }
3190 
3191 /*
3192  * Latch in the IPsec state for a stream based the policy in the listener
3193  * and the actions in the ip_recv_attr_t.
3194  * Called directly from TCP and SCTP.
3195  */
3196 boolean_t
3197 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3198 {
3199         ASSERT(lconnp->conn_policy != NULL);
3200         ASSERT(connp->conn_policy == NULL);
3201 
3202         IPPH_REFHOLD(lconnp->conn_policy);
3203         connp->conn_policy = lconnp->conn_policy;
3204 
3205         if (ira->ira_ipsec_action != NULL) {
3206                 if (connp->conn_latch == NULL) {
3207                         connp->conn_latch = iplatch_create();
3208                         if (connp->conn_latch == NULL)
3209                                 return (B_FALSE);
3210                 }
3211                 ipsec_latch_inbound(connp, ira);
3212         }
3213         return (B_TRUE);
3214 }
3215 
3216 /*
3217  * Verify whether or not the IP address is a valid local address.
3218  * Could be a unicast, including one for a down interface.
3219  * If allow_mcbc then a multicast or broadcast address is also
3220  * acceptable.
3221  *
3222  * In the case of a broadcast/multicast address, however, the
3223  * upper protocol is expected to reset the src address
3224  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3225  * no packets are emitted with broadcast/multicast address as
3226  * source address (that violates hosts requirements RFC 1122)
3227  * The addresses valid for bind are:
3228  *      (1) - INADDR_ANY (0)
3229  *      (2) - IP address of an UP interface
3230  *      (3) - IP address of a DOWN interface
3231  *      (4) - valid local IP broadcast addresses. In this case
3232  *      the conn will only receive packets destined to
3233  *      the specified broadcast address.
3234  *      (5) - a multicast address. In this case
3235  *      the conn will only receive packets destined to
3236  *      the specified multicast address. Note: the
3237  *      application still has to issue an
3238  *      IP_ADD_MEMBERSHIP socket option.
3239  *
3240  * In all the above cases, the bound address must be valid in the current zone.
3241  * When the address is loopback, multicast or broadcast, there might be many
3242  * matching IREs so bind has to look up based on the zone.
3243  */
3244 ip_laddr_t
3245 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3246     ip_stack_t *ipst, boolean_t allow_mcbc)
3247 {
3248         ire_t *src_ire;
3249 
3250         ASSERT(src_addr != INADDR_ANY);
3251 
3252         src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3253             NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3254 
3255         /*
3256          * If an address other than in6addr_any is requested,
3257          * we verify that it is a valid address for bind
3258          * Note: Following code is in if-else-if form for
3259          * readability compared to a condition check.
3260          */
3261         if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3262                 /*
3263                  * (2) Bind to address of local UP interface
3264                  */
3265                 ire_refrele(src_ire);
3266                 return (IPVL_UNICAST_UP);
3267         } else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3268                 /*
3269                  * (4) Bind to broadcast address
3270                  */
3271                 ire_refrele(src_ire);
3272                 if (allow_mcbc)
3273                         return (IPVL_BCAST);
3274                 else
3275                         return (IPVL_BAD);
3276         } else if (CLASSD(src_addr)) {
3277                 /* (5) bind to multicast address. */
3278                 if (src_ire != NULL)
3279                         ire_refrele(src_ire);
3280 
3281                 if (allow_mcbc)
3282                         return (IPVL_MCAST);
3283                 else
3284                         return (IPVL_BAD);
3285         } else {
3286                 ipif_t *ipif;
3287 
3288                 /*
3289                  * (3) Bind to address of local DOWN interface?
3290                  * (ipif_lookup_addr() looks up all interfaces
3291                  * but we do not get here for UP interfaces
3292                  * - case (2) above)
3293                  */
3294                 if (src_ire != NULL)
3295                         ire_refrele(src_ire);
3296 
3297                 ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3298                 if (ipif == NULL)
3299                         return (IPVL_BAD);
3300 
3301                 /* Not a useful source? */
3302                 if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3303                         ipif_refrele(ipif);
3304                         return (IPVL_BAD);
3305                 }
3306                 ipif_refrele(ipif);
3307                 return (IPVL_UNICAST_DOWN);
3308         }
3309 }
3310 
3311 /*
3312  * Insert in the bind fanout for IPv4 and IPv6.
3313  * The caller should already have used ip_laddr_verify_v*() before calling
3314  * this.
3315  */
3316 int
3317 ip_laddr_fanout_insert(conn_t *connp)
3318 {
3319         int             error;
3320 
3321         /*
3322          * Allow setting new policies. For example, disconnects result
3323          * in us being called. As we would have set conn_policy_cached
3324          * to B_TRUE before, we should set it to B_FALSE, so that policy
3325          * can change after the disconnect.
3326          */
3327         connp->conn_policy_cached = B_FALSE;
3328 
3329         error = ipcl_bind_insert(connp);
3330         if (error != 0) {
3331                 if (connp->conn_anon_port) {
3332                         (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3333                             connp->conn_mlp_type, connp->conn_proto,
3334                             ntohs(connp->conn_lport), B_FALSE);
3335                 }
3336                 connp->conn_mlp_type = mlptSingle;
3337         }
3338         return (error);
3339 }
3340 
3341 /*
3342  * Verify that both the source and destination addresses are valid. If
3343  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3344  * i.e. have no route to it.  Protocols like TCP want to verify destination
3345  * reachability, while tunnels do not.
3346  *
3347  * Determine the route, the interface, and (optionally) the source address
3348  * to use to reach a given destination.
3349  * Note that we allow connect to broadcast and multicast addresses when
3350  * IPDF_ALLOW_MCBC is set.
3351  * first_hop and dst_addr are normally the same, but if source routing
3352  * they will differ; in that case the first_hop is what we'll use for the
3353  * routing lookup but the dce and label checks will be done on dst_addr,
3354  *
3355  * If uinfo is set, then we fill in the best available information
3356  * we have for the destination. This is based on (in priority order) any
3357  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3358  * ill_mtu/ill_mc_mtu.
3359  *
3360  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3361  * always do the label check on dst_addr.
3362  */
3363 int
3364 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3365     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3366 {
3367         ire_t           *ire = NULL;
3368         int             error = 0;
3369         ipaddr_t        setsrc;                         /* RTF_SETSRC */
3370         zoneid_t        zoneid = ixa->ixa_zoneid;    /* Honors SO_ALLZONES */
3371         ip_stack_t      *ipst = ixa->ixa_ipst;
3372         dce_t           *dce;
3373         uint_t          pmtu;
3374         uint_t          generation;
3375         nce_t           *nce;
3376         ill_t           *ill = NULL;
3377         boolean_t       multirt = B_FALSE;
3378 
3379         ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3380 
3381         /*
3382          * We never send to zero; the ULPs map it to the loopback address.
3383          * We can't allow it since we use zero to mean unitialized in some
3384          * places.
3385          */
3386         ASSERT(dst_addr != INADDR_ANY);
3387 
3388         if (is_system_labeled()) {
3389                 ts_label_t *tsl = NULL;
3390 
3391                 error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3392                     mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3393                 if (error != 0)
3394                         return (error);
3395                 if (tsl != NULL) {
3396                         /* Update the label */
3397                         ip_xmit_attr_replace_tsl(ixa, tsl);
3398                 }
3399         }
3400 
3401         setsrc = INADDR_ANY;
3402         /*
3403          * Select a route; For IPMP interfaces, we would only select
3404          * a "hidden" route (i.e., going through a specific under_ill)
3405          * if ixa_ifindex has been specified.
3406          */
3407         ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3408             &generation, &setsrc, &error, &multirt);
3409         ASSERT(ire != NULL);    /* IRE_NOROUTE if none found */
3410         if (error != 0)
3411                 goto bad_addr;
3412 
3413         /*
3414          * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3415          * If IPDF_VERIFY_DST is set, the destination must be reachable;
3416          * Otherwise the destination needn't be reachable.
3417          *
3418          * If we match on a reject or black hole, then we've got a
3419          * local failure.  May as well fail out the connect() attempt,
3420          * since it's never going to succeed.
3421          */
3422         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3423                 /*
3424                  * If we're verifying destination reachability, we always want
3425                  * to complain here.
3426                  *
3427                  * If we're not verifying destination reachability but the
3428                  * destination has a route, we still want to fail on the
3429                  * temporary address and broadcast address tests.
3430                  *
3431                  * In both cases do we let the code continue so some reasonable
3432                  * information is returned to the caller. That enables the
3433                  * caller to use (and even cache) the IRE. conn_ip_ouput will
3434                  * use the generation mismatch path to check for the unreachable
3435                  * case thereby avoiding any specific check in the main path.
3436                  */
3437                 ASSERT(generation == IRE_GENERATION_VERIFY);
3438                 if (flags & IPDF_VERIFY_DST) {
3439                         /*
3440                          * Set errno but continue to set up ixa_ire to be
3441                          * the RTF_REJECT|RTF_BLACKHOLE IRE.
3442                          * That allows callers to use ip_output to get an
3443                          * ICMP error back.
3444                          */
3445                         if (!(ire->ire_type & IRE_HOST))
3446                                 error = ENETUNREACH;
3447                         else
3448                                 error = EHOSTUNREACH;
3449                 }
3450         }
3451 
3452         if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3453             !(flags & IPDF_ALLOW_MCBC)) {
3454                 ire_refrele(ire);
3455                 ire = ire_reject(ipst, B_FALSE);
3456                 generation = IRE_GENERATION_VERIFY;
3457                 error = ENETUNREACH;
3458         }
3459 
3460         /* Cache things */
3461         if (ixa->ixa_ire != NULL)
3462                 ire_refrele_notr(ixa->ixa_ire);
3463 #ifdef DEBUG
3464         ire_refhold_notr(ire);
3465         ire_refrele(ire);
3466 #endif
3467         ixa->ixa_ire = ire;
3468         ixa->ixa_ire_generation = generation;
3469 
3470         /*
3471          * Ensure that ixa_dce is always set any time that ixa_ire is set,
3472          * since some callers will send a packet to conn_ip_output() even if
3473          * there's an error.
3474          */
3475         if (flags & IPDF_UNIQUE_DCE) {
3476                 /* Fallback to the default dce if allocation fails */
3477                 dce = dce_lookup_and_add_v4(dst_addr, ipst);
3478                 if (dce != NULL)
3479                         generation = dce->dce_generation;
3480                 else
3481                         dce = dce_lookup_v4(dst_addr, ipst, &generation);
3482         } else {
3483                 dce = dce_lookup_v4(dst_addr, ipst, &generation);
3484         }
3485         ASSERT(dce != NULL);
3486         if (ixa->ixa_dce != NULL)
3487                 dce_refrele_notr(ixa->ixa_dce);
3488 #ifdef DEBUG
3489         dce_refhold_notr(dce);
3490         dce_refrele(dce);
3491 #endif
3492         ixa->ixa_dce = dce;
3493         ixa->ixa_dce_generation = generation;
3494 
3495         /*
3496          * For multicast with multirt we have a flag passed back from
3497          * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3498          * possible multicast address.
3499          * We also need a flag for multicast since we can't check
3500          * whether RTF_MULTIRT is set in ixa_ire for multicast.
3501          */
3502         if (multirt) {
3503                 ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3504                 ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3505         } else {
3506                 ixa->ixa_postfragfn = ire->ire_postfragfn;
3507                 ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3508         }
3509         if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3510                 /* Get an nce to cache. */
3511                 nce = ire_to_nce(ire, firsthop, NULL);
3512                 if (nce == NULL) {
3513                         /* Allocation failure? */
3514                         ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3515                 } else {
3516                         if (ixa->ixa_nce != NULL)
3517                                 nce_refrele(ixa->ixa_nce);
3518                         ixa->ixa_nce = nce;
3519                 }
3520         }
3521 
3522         /*
3523          * If the source address is a loopback address, the
3524          * destination had best be local or multicast.
3525          * If we are sending to an IRE_LOCAL using a loopback source then
3526          * it had better be the same zoneid.
3527          */
3528         if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3529                 if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3530                         ire = NULL;     /* Stored in ixa_ire */
3531                         error = EADDRNOTAVAIL;
3532                         goto bad_addr;
3533                 }
3534                 if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3535                         ire = NULL;     /* Stored in ixa_ire */
3536                         error = EADDRNOTAVAIL;
3537                         goto bad_addr;
3538                 }
3539         }
3540         if (ire->ire_type & IRE_BROADCAST) {
3541                 /*
3542                  * If the ULP didn't have a specified source, then we
3543                  * make sure we reselect the source when sending
3544                  * broadcasts out different interfaces.
3545                  */
3546                 if (flags & IPDF_SELECT_SRC)
3547                         ixa->ixa_flags |= IXAF_SET_SOURCE;
3548                 else
3549                         ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3550         }
3551 
3552         /*
3553          * Does the caller want us to pick a source address?
3554          */
3555         if (flags & IPDF_SELECT_SRC) {
3556                 ipaddr_t        src_addr;
3557 
3558                 /*
3559                  * We use use ire_nexthop_ill to avoid the under ipmp
3560                  * interface for source address selection. Note that for ipmp
3561                  * probe packets, ixa_ifindex would have been specified, and
3562                  * the ip_select_route() invocation would have picked an ire
3563                  * will ire_ill pointing at an under interface.
3564                  */
3565                 ill = ire_nexthop_ill(ire);
3566 
3567                 /* If unreachable we have no ill but need some source */
3568                 if (ill == NULL) {
3569                         src_addr = htonl(INADDR_LOOPBACK);
3570                         /* Make sure we look for a better source address */
3571                         generation = SRC_GENERATION_VERIFY;
3572                 } else {
3573                         error = ip_select_source_v4(ill, setsrc, dst_addr,
3574                             ixa->ixa_multicast_ifaddr, zoneid,
3575                             ipst, &src_addr, &generation, NULL);
3576                         if (error != 0) {
3577                                 ire = NULL;     /* Stored in ixa_ire */
3578                                 goto bad_addr;
3579                         }
3580                 }
3581 
3582                 /*
3583                  * We allow the source address to to down.
3584                  * However, we check that we don't use the loopback address
3585                  * as a source when sending out on the wire.
3586                  */
3587                 if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3588                     !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3589                     !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3590                         ire = NULL;     /* Stored in ixa_ire */
3591                         error = EADDRNOTAVAIL;
3592                         goto bad_addr;
3593                 }
3594 
3595                 *src_addrp = src_addr;
3596                 ixa->ixa_src_generation = generation;
3597         }
3598 
3599         /*
3600          * Make sure we don't leave an unreachable ixa_nce in place
3601          * since ip_select_route is used when we unplumb i.e., remove
3602          * references on ixa_ire, ixa_nce, and ixa_dce.
3603          */
3604         nce = ixa->ixa_nce;
3605         if (nce != NULL && nce->nce_is_condemned) {
3606                 nce_refrele(nce);
3607                 ixa->ixa_nce = NULL;
3608                 ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3609         }
3610 
3611         /*
3612          * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3613          * However, we can't do it for IPv4 multicast or broadcast.
3614          */
3615         if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3616                 ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3617 
3618         /*
3619          * Set initial value for fragmentation limit. Either conn_ip_output
3620          * or ULP might updates it when there are routing changes.
3621          * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3622          */
3623         pmtu = ip_get_pmtu(ixa);
3624         ixa->ixa_fragsize = pmtu;
3625         /* Make sure ixa_fragsize and ixa_pmtu remain identical */
3626         if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3627                 ixa->ixa_pmtu = pmtu;
3628 
3629         /*
3630          * Extract information useful for some transports.
3631          * First we look for DCE metrics. Then we take what we have in
3632          * the metrics in the route, where the offlink is used if we have
3633          * one.
3634          */
3635         if (uinfo != NULL) {
3636                 bzero(uinfo, sizeof (*uinfo));
3637 
3638                 if (dce->dce_flags & DCEF_UINFO)
3639                         *uinfo = dce->dce_uinfo;
3640 
3641                 rts_merge_metrics(uinfo, &ire->ire_metrics);
3642 
3643                 /* Allow ire_metrics to decrease the path MTU from above */
3644                 if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3645                         uinfo->iulp_mtu = pmtu;
3646 
3647                 uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3648                 uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3649                 uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3650         }
3651 
3652         if (ill != NULL)
3653                 ill_refrele(ill);
3654 
3655         return (error);
3656 
3657 bad_addr:
3658         if (ire != NULL)
3659                 ire_refrele(ire);
3660 
3661         if (ill != NULL)
3662                 ill_refrele(ill);
3663 
3664         /*
3665          * Make sure we don't leave an unreachable ixa_nce in place
3666          * since ip_select_route is used when we unplumb i.e., remove
3667          * references on ixa_ire, ixa_nce, and ixa_dce.
3668          */
3669         nce = ixa->ixa_nce;
3670         if (nce != NULL && nce->nce_is_condemned) {
3671                 nce_refrele(nce);
3672                 ixa->ixa_nce = NULL;
3673                 ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3674         }
3675 
3676         return (error);
3677 }
3678 
3679 
3680 /*
3681  * Get the base MTU for the case when path MTU discovery is not used.
3682  * Takes the MTU of the IRE into account.
3683  */
3684 uint_t
3685 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3686 {
3687         uint_t mtu;
3688         uint_t iremtu = ire->ire_metrics.iulp_mtu;
3689 
3690         if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST))
3691                 mtu = ill->ill_mc_mtu;
3692         else
3693                 mtu = ill->ill_mtu;
3694 
3695         if (iremtu != 0 && iremtu < mtu)
3696                 mtu = iremtu;
3697 
3698         return (mtu);
3699 }
3700 
3701 /*
3702  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3703  * Assumes that ixa_ire, dce, and nce have already been set up.
3704  *
3705  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3706  * We avoid path MTU discovery if it is disabled with ndd.
3707  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3708  *
3709  * NOTE: We also used to turn it off for source routed packets. That
3710  * is no longer required since the dce is per final destination.
3711  */
3712 uint_t
3713 ip_get_pmtu(ip_xmit_attr_t *ixa)
3714 {
3715         ip_stack_t      *ipst = ixa->ixa_ipst;
3716         dce_t           *dce;
3717         nce_t           *nce;
3718         ire_t           *ire;
3719         uint_t          pmtu;
3720 
3721         ire = ixa->ixa_ire;
3722         dce = ixa->ixa_dce;
3723         nce = ixa->ixa_nce;
3724 
3725         /*
3726          * If path MTU discovery has been turned off by ndd, then we ignore
3727          * any dce_pmtu and for IPv4 we will not set DF.
3728          */
3729         if (!ipst->ips_ip_path_mtu_discovery)
3730                 ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3731 
3732         pmtu = IP_MAXPACKET;
3733         /*
3734          * Decide whether whether IPv4 sets DF
3735          * For IPv6 "no DF" means to use the 1280 mtu
3736          */
3737         if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3738                 ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3739         } else {
3740                 ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3741                 if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3742                         pmtu = IPV6_MIN_MTU;
3743         }
3744 
3745         /* Check if the PMTU is to old before we use it */
3746         if ((dce->dce_flags & DCEF_PMTU) &&
3747             TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3748             ipst->ips_ip_pathmtu_interval) {
3749                 /*
3750                  * Older than 20 minutes. Drop the path MTU information.
3751                  */
3752                 mutex_enter(&dce->dce_lock);
3753                 dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3754                 dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3755                 mutex_exit(&dce->dce_lock);
3756                 dce_increment_generation(dce);
3757         }
3758 
3759         /* The metrics on the route can lower the path MTU */
3760         if (ire->ire_metrics.iulp_mtu != 0 &&
3761             ire->ire_metrics.iulp_mtu < pmtu)
3762                 pmtu = ire->ire_metrics.iulp_mtu;
3763 
3764         /*
3765          * If the path MTU is smaller than some minimum, we still use dce_pmtu
3766          * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3767          * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3768          */
3769         if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3770                 if (dce->dce_flags & DCEF_PMTU) {
3771                         if (dce->dce_pmtu < pmtu)
3772                                 pmtu = dce->dce_pmtu;
3773 
3774                         if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3775                                 ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3776                                 ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3777                         } else {
3778                                 ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3779                                 ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3780                         }
3781                 } else {
3782                         ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3783                         ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3784                 }
3785         }
3786 
3787         /*
3788          * If we have an IRE_LOCAL we use the loopback mtu instead of
3789          * the ill for going out the wire i.e., IRE_LOCAL gets the same
3790          * mtu as IRE_LOOPBACK.
3791          */
3792         if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3793                 uint_t loopback_mtu;
3794 
3795                 loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3796                     ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3797 
3798                 if (loopback_mtu < pmtu)
3799                         pmtu = loopback_mtu;
3800         } else if (nce != NULL) {
3801                 /*
3802                  * Make sure we don't exceed the interface MTU.
3803                  * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3804                  * an ill. We'd use the above IP_MAXPACKET in that case just
3805                  * to tell the transport something larger than zero.
3806                  */
3807                 if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST)) {
3808                         if (nce->nce_common->ncec_ill->ill_mc_mtu < pmtu)
3809                                 pmtu = nce->nce_common->ncec_ill->ill_mc_mtu;
3810                         if (nce->nce_common->ncec_ill != nce->nce_ill &&
3811                             nce->nce_ill->ill_mc_mtu < pmtu) {
3812                                 /*
3813                                  * for interfaces in an IPMP group, the mtu of
3814                                  * the nce_ill (under_ill) could be different
3815                                  * from the mtu of the ncec_ill, so we take the
3816                                  * min of the two.
3817                                  */
3818                                 pmtu = nce->nce_ill->ill_mc_mtu;
3819                         }
3820                 } else {
3821                         if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3822                                 pmtu = nce->nce_common->ncec_ill->ill_mtu;
3823                         if (nce->nce_common->ncec_ill != nce->nce_ill &&
3824                             nce->nce_ill->ill_mtu < pmtu) {
3825                                 /*
3826                                  * for interfaces in an IPMP group, the mtu of
3827                                  * the nce_ill (under_ill) could be different
3828                                  * from the mtu of the ncec_ill, so we take the
3829                                  * min of the two.
3830                                  */
3831                                 pmtu = nce->nce_ill->ill_mtu;
3832                         }
3833                 }
3834         }
3835 
3836         /*
3837          * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3838          * Only applies to IPv6.
3839          */
3840         if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3841                 if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3842                         switch (ixa->ixa_use_min_mtu) {
3843                         case IPV6_USE_MIN_MTU_MULTICAST:
3844                                 if (ire->ire_type & IRE_MULTICAST)
3845                                         pmtu = IPV6_MIN_MTU;
3846                                 break;
3847                         case IPV6_USE_MIN_MTU_ALWAYS:
3848                                 pmtu = IPV6_MIN_MTU;
3849                                 break;
3850                         case IPV6_USE_MIN_MTU_NEVER:
3851                                 break;
3852                         }
3853                 } else {
3854                         /* Default is IPV6_USE_MIN_MTU_MULTICAST */
3855                         if (ire->ire_type & IRE_MULTICAST)
3856                                 pmtu = IPV6_MIN_MTU;
3857                 }
3858         }
3859 
3860         /*
3861          * After receiving an ICMPv6 "packet too big" message with a
3862          * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3863          * will insert a 8-byte fragment header in every packet. We compensate
3864          * for those cases by 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 ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3876                     (ire->ire_flags & RTF_MULTIRT) ||
3877                     (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3878                         pmtu -= sizeof (ip6_frag_t);
3879                         ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3880                 }
3881         }
3882 
3883         return (pmtu);
3884 }
3885 
3886 /*
3887  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3888  * the final piece where we don't.  Return a pointer to the first mblk in the
3889  * result, and update the pointer to the next mblk to chew on.  If anything
3890  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3891  * NULL pointer.
3892  */
3893 mblk_t *
3894 ip_carve_mp(mblk_t **mpp, ssize_t len)
3895 {
3896         mblk_t  *mp0;
3897         mblk_t  *mp1;
3898         mblk_t  *mp2;
3899 
3900         if (!len || !mpp || !(mp0 = *mpp))
3901                 return (NULL);
3902         /* If we aren't going to consume the first mblk, we need a dup. */
3903         if (mp0->b_wptr - mp0->b_rptr > len) {
3904                 mp1 = dupb(mp0);
3905                 if (mp1) {
3906                         /* Partition the data between the two mblks. */
3907                         mp1->b_wptr = mp1->b_rptr + len;
3908                         mp0->b_rptr = mp1->b_wptr;
3909                         /*
3910                          * after adjustments if mblk not consumed is now
3911                          * unaligned, try to align it. If this fails free
3912                          * all messages and let upper layer recover.
3913                          */
3914                         if (!OK_32PTR(mp0->b_rptr)) {
3915                                 if (!pullupmsg(mp0, -1)) {
3916                                         freemsg(mp0);
3917                                         freemsg(mp1);
3918                                         *mpp = NULL;
3919                                         return (NULL);
3920                                 }
3921                         }
3922                 }
3923                 return (mp1);
3924         }
3925         /* Eat through as many mblks as we need to get len bytes. */
3926         len -= mp0->b_wptr - mp0->b_rptr;
3927         for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3928                 if (mp2->b_wptr - mp2->b_rptr > len) {
3929                         /*
3930                          * We won't consume the entire last mblk.  Like
3931                          * above, dup and partition it.
3932                          */
3933                         mp1->b_cont = dupb(mp2);
3934                         mp1 = mp1->b_cont;
3935                         if (!mp1) {
3936                                 /*
3937                                  * Trouble.  Rather than go to a lot of
3938                                  * trouble to clean up, we free the messages.
3939                                  * This won't be any worse than losing it on
3940                                  * the wire.
3941                                  */
3942                                 freemsg(mp0);
3943                                 freemsg(mp2);
3944                                 *mpp = NULL;
3945                                 return (NULL);
3946                         }
3947                         mp1->b_wptr = mp1->b_rptr + len;
3948                         mp2->b_rptr = mp1->b_wptr;
3949                         /*
3950                          * after adjustments if mblk not consumed is now
3951                          * unaligned, try to align it. If this fails free
3952                          * all messages and let upper layer recover.
3953                          */
3954                         if (!OK_32PTR(mp2->b_rptr)) {
3955                                 if (!pullupmsg(mp2, -1)) {
3956                                         freemsg(mp0);
3957                                         freemsg(mp2);
3958                                         *mpp = NULL;
3959                                         return (NULL);
3960                                 }
3961                         }
3962                         *mpp = mp2;
3963                         return (mp0);
3964                 }
3965                 /* Decrement len by the amount we just got. */
3966                 len -= mp2->b_wptr - mp2->b_rptr;
3967         }
3968         /*
3969          * len should be reduced to zero now.  If not our caller has
3970          * screwed up.
3971          */
3972         if (len) {
3973                 /* Shouldn't happen! */
3974                 freemsg(mp0);
3975                 *mpp = NULL;
3976                 return (NULL);
3977         }
3978         /*
3979          * We consumed up to exactly the end of an mblk.  Detach the part
3980          * we are returning from the rest of the chain.
3981          */
3982         mp1->b_cont = NULL;
3983         *mpp = mp2;
3984         return (mp0);
3985 }
3986 
3987 /* The ill stream is being unplumbed. Called from ip_close */
3988 int
3989 ip_modclose(ill_t *ill)
3990 {
3991         boolean_t success;
3992         ipsq_t  *ipsq;
3993         ipif_t  *ipif;
3994         queue_t *q = ill->ill_rq;
3995         ip_stack_t      *ipst = ill->ill_ipst;
3996         int     i;
3997         arl_ill_common_t *ai = ill->ill_common;
3998 
3999         /*
4000          * The punlink prior to this may have initiated a capability
4001          * negotiation. But ipsq_enter will block until that finishes or
4002          * times out.
4003          */
4004         success = ipsq_enter(ill, B_FALSE, NEW_OP);
4005 
4006         /*
4007          * Open/close/push/pop is guaranteed to be single threaded
4008          * per stream by STREAMS. FS guarantees that all references
4009          * from top are gone before close is called. So there can't
4010          * be another close thread that has set CONDEMNED on this ill.
4011          * and cause ipsq_enter to return failure.
4012          */
4013         ASSERT(success);
4014         ipsq = ill->ill_phyint->phyint_ipsq;
4015 
4016         /*
4017          * Mark it condemned. No new reference will be made to this ill.
4018          * Lookup functions will return an error. Threads that try to
4019          * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4020          * that the refcnt will drop down to zero.
4021          */
4022         mutex_enter(&ill->ill_lock);
4023         ill->ill_state_flags |= ILL_CONDEMNED;
4024         for (ipif = ill->ill_ipif; ipif != NULL;
4025             ipif = ipif->ipif_next) {
4026                 ipif->ipif_state_flags |= IPIF_CONDEMNED;
4027         }
4028         /*
4029          * Wake up anybody waiting to enter the ipsq. ipsq_enter
4030          * returns  error if ILL_CONDEMNED is set
4031          */
4032         cv_broadcast(&ill->ill_cv);
4033         mutex_exit(&ill->ill_lock);
4034 
4035         /*
4036          * Send all the deferred DLPI messages downstream which came in
4037          * during the small window right before ipsq_enter(). We do this
4038          * without waiting for the ACKs because all the ACKs for M_PROTO
4039          * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4040          */
4041         ill_dlpi_send_deferred(ill);
4042 
4043         /*
4044          * Shut down fragmentation reassembly.
4045          * ill_frag_timer won't start a timer again.
4046          * Now cancel any existing timer
4047          */
4048         (void) untimeout(ill->ill_frag_timer_id);
4049         (void) ill_frag_timeout(ill, 0);
4050 
4051         /*
4052          * Call ill_delete to bring down the ipifs, ilms and ill on
4053          * this ill. Then wait for the refcnts to drop to zero.
4054          * ill_is_freeable checks whether the ill is really quiescent.
4055          * Then make sure that threads that are waiting to enter the
4056          * ipsq have seen the error returned by ipsq_enter and have
4057          * gone away. Then we call ill_delete_tail which does the
4058          * DL_UNBIND_REQ with the driver and then qprocsoff.
4059          */
4060         ill_delete(ill);
4061         mutex_enter(&ill->ill_lock);
4062         while (!ill_is_freeable(ill))
4063                 cv_wait(&ill->ill_cv, &ill->ill_lock);
4064 
4065         while (ill->ill_waiters)
4066                 cv_wait(&ill->ill_cv, &ill->ill_lock);
4067 
4068         mutex_exit(&ill->ill_lock);
4069 
4070         /*
4071          * ill_delete_tail drops reference on ill_ipst, but we need to keep
4072          * it held until the end of the function since the cleanup
4073          * below needs to be able to use the ip_stack_t.
4074          */
4075         netstack_hold(ipst->ips_netstack);
4076 
4077         /* qprocsoff is done via ill_delete_tail */
4078         ill_delete_tail(ill);
4079         /*
4080          * synchronously wait for arp stream to unbind. After this, we
4081          * cannot get any data packets up from the driver.
4082          */
4083         arp_unbind_complete(ill);
4084         ASSERT(ill->ill_ipst == NULL);
4085 
4086         /*
4087          * Walk through all conns and qenable those that have queued data.
4088          * Close synchronization needs this to
4089          * be done to ensure that all upper layers blocked
4090          * due to flow control to the closing device
4091          * get unblocked.
4092          */
4093         ip1dbg(("ip_wsrv: walking\n"));
4094         for (i = 0; i < TX_FANOUT_SIZE; i++) {
4095                 conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4096         }
4097 
4098         /*
4099          * ai can be null if this is an IPv6 ill, or if the IPv4
4100          * stream is being torn down before ARP was plumbed (e.g.,
4101          * /sbin/ifconfig plumbing a stream twice, and encountering
4102          * an error
4103          */
4104         if (ai != NULL) {
4105                 ASSERT(!ill->ill_isv6);
4106                 mutex_enter(&ai->ai_lock);
4107                 ai->ai_ill = NULL;
4108                 if (ai->ai_arl == NULL) {
4109                         mutex_destroy(&ai->ai_lock);
4110                         kmem_free(ai, sizeof (*ai));
4111                 } else {
4112                         cv_signal(&ai->ai_ill_unplumb_done);
4113                         mutex_exit(&ai->ai_lock);
4114                 }
4115         }
4116 
4117         mutex_enter(&ipst->ips_ip_mi_lock);
4118         mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4119         mutex_exit(&ipst->ips_ip_mi_lock);
4120 
4121         /*
4122          * credp could be null if the open didn't succeed and ip_modopen
4123          * itself calls ip_close.
4124          */
4125         if (ill->ill_credp != NULL)
4126                 crfree(ill->ill_credp);
4127 
4128         mutex_destroy(&ill->ill_saved_ire_lock);
4129         mutex_destroy(&ill->ill_lock);
4130         rw_destroy(&ill->ill_mcast_lock);
4131         mutex_destroy(&ill->ill_mcast_serializer);
4132         list_destroy(&ill->ill_nce);
4133 
4134         /*
4135          * Now we are done with the module close pieces that
4136          * need the netstack_t.
4137          */
4138         netstack_rele(ipst->ips_netstack);
4139 
4140         mi_close_free((IDP)ill);
4141         q->q_ptr = WR(q)->q_ptr = NULL;
4142 
4143         ipsq_exit(ipsq);
4144 
4145         return (0);
4146 }
4147 
4148 /*
4149  * This is called as part of close() for IP, UDP, ICMP, and RTS
4150  * in order to quiesce the conn.
4151  */
4152 void
4153 ip_quiesce_conn(conn_t *connp)
4154 {
4155         boolean_t       drain_cleanup_reqd = B_FALSE;
4156         boolean_t       conn_ioctl_cleanup_reqd = B_FALSE;
4157         boolean_t       ilg_cleanup_reqd = B_FALSE;
4158         ip_stack_t      *ipst;
4159 
4160         ASSERT(!IPCL_IS_TCP(connp));
4161         ipst = connp->conn_netstack->netstack_ip;
4162 
4163         /*
4164          * Mark the conn as closing, and this conn must not be
4165          * inserted in future into any list. Eg. conn_drain_insert(),
4166          * won't insert this conn into the conn_drain_list.
4167          *
4168          * conn_idl, and conn_ilg cannot get set henceforth.
4169          */
4170         mutex_enter(&connp->conn_lock);
4171         ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4172         connp->conn_state_flags |= CONN_CLOSING;
4173         if (connp->conn_idl != NULL)
4174                 drain_cleanup_reqd = B_TRUE;
4175         if (connp->conn_oper_pending_ill != NULL)
4176                 conn_ioctl_cleanup_reqd = B_TRUE;
4177         if (connp->conn_dhcpinit_ill != NULL) {
4178                 ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4179                 atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4180                 ill_set_inputfn(connp->conn_dhcpinit_ill);
4181                 connp->conn_dhcpinit_ill = NULL;
4182         }
4183         if (connp->conn_ilg != NULL)
4184                 ilg_cleanup_reqd = B_TRUE;
4185         mutex_exit(&connp->conn_lock);
4186 
4187         if (conn_ioctl_cleanup_reqd)
4188                 conn_ioctl_cleanup(connp);
4189 
4190         if (is_system_labeled() && connp->conn_anon_port) {
4191                 (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4192                     connp->conn_mlp_type, connp->conn_proto,
4193                     ntohs(connp->conn_lport), B_FALSE);
4194                 connp->conn_anon_port = 0;
4195         }
4196         connp->conn_mlp_type = mlptSingle;
4197 
4198         /*
4199          * Remove this conn from any fanout list it is on.
4200          * and then wait for any threads currently operating
4201          * on this endpoint to finish
4202          */
4203         ipcl_hash_remove(connp);
4204 
4205         /*
4206          * Remove this conn from the drain list, and do any other cleanup that
4207          * may be required.  (TCP conns are never flow controlled, and
4208          * conn_idl will be NULL.)
4209          */
4210         if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4211                 idl_t *idl = connp->conn_idl;
4212 
4213                 mutex_enter(&idl->idl_lock);
4214                 conn_drain(connp, B_TRUE);
4215                 mutex_exit(&idl->idl_lock);
4216         }
4217 
4218         if (connp == ipst->ips_ip_g_mrouter)
4219                 (void) ip_mrouter_done(ipst);
4220 
4221         if (ilg_cleanup_reqd)
4222                 ilg_delete_all(connp);
4223 
4224         /*
4225          * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4226          * callers from write side can't be there now because close
4227          * is in progress. The only other caller is ipcl_walk
4228          * which checks for the condemned flag.
4229          */
4230         mutex_enter(&connp->conn_lock);
4231         connp->conn_state_flags |= CONN_CONDEMNED;
4232         while (connp->conn_ref != 1)
4233                 cv_wait(&connp->conn_cv, &connp->conn_lock);
4234         connp->conn_state_flags |= CONN_QUIESCED;
4235         mutex_exit(&connp->conn_lock);
4236 }
4237 
4238 /* ARGSUSED */
4239 int
4240 ip_close(queue_t *q, int flags)
4241 {
4242         conn_t          *connp;
4243 
4244         /*
4245          * Call the appropriate delete routine depending on whether this is
4246          * a module or device.
4247          */
4248         if (WR(q)->q_next != NULL) {
4249                 /* This is a module close */
4250                 return (ip_modclose((ill_t *)q->q_ptr));
4251         }
4252 
4253         connp = q->q_ptr;
4254         ip_quiesce_conn(connp);
4255 
4256         qprocsoff(q);
4257 
4258         /*
4259          * Now we are truly single threaded on this stream, and can
4260          * delete the things hanging off the connp, and finally the connp.
4261          * We removed this connp from the fanout list, it cannot be
4262          * accessed thru the fanouts, and we already waited for the
4263          * conn_ref to drop to 0. We are already in close, so
4264          * there cannot be any other thread from the top. qprocsoff
4265          * has completed, and service has completed or won't run in
4266          * future.
4267          */
4268         ASSERT(connp->conn_ref == 1);
4269 
4270         inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4271 
4272         connp->conn_ref--;
4273         ipcl_conn_destroy(connp);
4274 
4275         q->q_ptr = WR(q)->q_ptr = NULL;
4276         return (0);
4277 }
4278 
4279 /*
4280  * Wapper around putnext() so that ip_rts_request can merely use
4281  * conn_recv.
4282  */
4283 /*ARGSUSED2*/
4284 static void
4285 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4286 {
4287         conn_t *connp = (conn_t *)arg1;
4288 
4289         putnext(connp->conn_rq, mp);
4290 }
4291 
4292 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4293 /* ARGSUSED */
4294 static void
4295 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4296 {
4297         freemsg(mp);
4298 }
4299 
4300 /*
4301  * Called when the module is about to be unloaded
4302  */
4303 void
4304 ip_ddi_destroy(void)
4305 {
4306         /* This needs to be called before destroying any transports. */
4307         mutex_enter(&cpu_lock);
4308         unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4309         mutex_exit(&cpu_lock);
4310 
4311         tnet_fini();
4312 
4313         icmp_ddi_g_destroy();
4314         rts_ddi_g_destroy();
4315         udp_ddi_g_destroy();
4316         sctp_ddi_g_destroy();
4317         tcp_ddi_g_destroy();
4318         ilb_ddi_g_destroy();
4319         dce_g_destroy();
4320         ipsec_policy_g_destroy();
4321         ipcl_g_destroy();
4322         ip_net_g_destroy();
4323         ip_ire_g_fini();
4324         inet_minor_destroy(ip_minor_arena_sa);
4325 #if defined(_LP64)
4326         inet_minor_destroy(ip_minor_arena_la);
4327 #endif
4328 
4329 #ifdef DEBUG
4330         list_destroy(&ip_thread_list);
4331         rw_destroy(&ip_thread_rwlock);
4332         tsd_destroy(&ip_thread_data);
4333 #endif
4334 
4335         netstack_unregister(NS_IP);
4336 }
4337 
4338 /*
4339  * First step in cleanup.
4340  */
4341 /* ARGSUSED */
4342 static void
4343 ip_stack_shutdown(netstackid_t stackid, void *arg)
4344 {
4345         ip_stack_t *ipst = (ip_stack_t *)arg;
4346         kt_did_t ktid;
4347 
4348 #ifdef NS_DEBUG
4349         printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4350 #endif
4351 
4352         /*
4353          * Perform cleanup for special interfaces (loopback and IPMP).
4354          */
4355         ip_interface_cleanup(ipst);
4356 
4357         /*
4358          * The *_hook_shutdown()s start the process of notifying any
4359          * consumers that things are going away.... nothing is destroyed.
4360          */
4361         ipv4_hook_shutdown(ipst);
4362         ipv6_hook_shutdown(ipst);
4363         arp_hook_shutdown(ipst);
4364 
4365         mutex_enter(&ipst->ips_capab_taskq_lock);
4366         ktid = ipst->ips_capab_taskq_thread->t_did;
4367         ipst->ips_capab_taskq_quit = B_TRUE;
4368         cv_signal(&ipst->ips_capab_taskq_cv);
4369         mutex_exit(&ipst->ips_capab_taskq_lock);
4370 
4371         /*
4372          * In rare occurrences, particularly on virtual hardware where CPUs can
4373          * be de-scheduled, the thread that we just signaled will not run until
4374          * after we have gotten through parts of ip_stack_fini. If that happens
4375          * then we'll try to grab the ips_capab_taskq_lock as part of returning
4376          * from cv_wait which no longer exists.
4377          */
4378         thread_join(ktid);
4379 }
4380 
4381 /*
4382  * Free the IP stack instance.
4383  */
4384 static void
4385 ip_stack_fini(netstackid_t stackid, void *arg)
4386 {
4387         ip_stack_t *ipst = (ip_stack_t *)arg;
4388         int ret;
4389 
4390 #ifdef NS_DEBUG
4391         printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4392 #endif
4393         /*
4394          * At this point, all of the notifications that the events and
4395          * protocols are going away have been run, meaning that we can
4396          * now set about starting to clean things up.
4397          */
4398         ipobs_fini(ipst);
4399         ipv4_hook_destroy(ipst);
4400         ipv6_hook_destroy(ipst);
4401         arp_hook_destroy(ipst);
4402         ip_net_destroy(ipst);
4403 
4404         ipmp_destroy(ipst);
4405 
4406         ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4407         ipst->ips_ip_mibkp = NULL;
4408         icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4409         ipst->ips_icmp_mibkp = NULL;
4410         ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4411         ipst->ips_ip_kstat = NULL;
4412         bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4413         ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4414         ipst->ips_ip6_kstat = NULL;
4415         bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4416 
4417         kmem_free(ipst->ips_propinfo_tbl,
4418             ip_propinfo_count * sizeof (mod_prop_info_t));
4419         ipst->ips_propinfo_tbl = NULL;
4420 
4421         dce_stack_destroy(ipst);
4422         ip_mrouter_stack_destroy(ipst);
4423 
4424         /*
4425          * Quiesce all of our timers. Note we set the quiesce flags before we
4426          * call untimeout. The slowtimers may actually kick off another instance
4427          * of the non-slow timers.
4428          */
4429         mutex_enter(&ipst->ips_igmp_timer_lock);
4430         ipst->ips_igmp_timer_quiesce = B_TRUE;
4431         mutex_exit(&ipst->ips_igmp_timer_lock);
4432 
4433         mutex_enter(&ipst->ips_mld_timer_lock);
4434         ipst->ips_mld_timer_quiesce = B_TRUE;
4435         mutex_exit(&ipst->ips_mld_timer_lock);
4436 
4437         mutex_enter(&ipst->ips_igmp_slowtimeout_lock);
4438         ipst->ips_igmp_slowtimeout_quiesce = B_TRUE;
4439         mutex_exit(&ipst->ips_igmp_slowtimeout_lock);
4440 
4441         mutex_enter(&ipst->ips_mld_slowtimeout_lock);
4442         ipst->ips_mld_slowtimeout_quiesce = B_TRUE;
4443         mutex_exit(&ipst->ips_mld_slowtimeout_lock);
4444 
4445         ret = untimeout(ipst->ips_igmp_timeout_id);
4446         if (ret == -1) {
4447                 ASSERT(ipst->ips_igmp_timeout_id == 0);
4448         } else {
4449                 ASSERT(ipst->ips_igmp_timeout_id != 0);
4450                 ipst->ips_igmp_timeout_id = 0;
4451         }
4452         ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4453         if (ret == -1) {
4454                 ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4455         } else {
4456                 ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4457                 ipst->ips_igmp_slowtimeout_id = 0;
4458         }
4459         ret = untimeout(ipst->ips_mld_timeout_id);
4460         if (ret == -1) {
4461                 ASSERT(ipst->ips_mld_timeout_id == 0);
4462         } else {
4463                 ASSERT(ipst->ips_mld_timeout_id != 0);
4464                 ipst->ips_mld_timeout_id = 0;
4465         }
4466         ret = untimeout(ipst->ips_mld_slowtimeout_id);
4467         if (ret == -1) {
4468                 ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4469         } else {
4470                 ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4471                 ipst->ips_mld_slowtimeout_id = 0;
4472         }
4473 
4474         ip_ire_fini(ipst);
4475         ip6_asp_free(ipst);
4476         conn_drain_fini(ipst);
4477         ipcl_destroy(ipst);
4478 
4479         mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4480         mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4481         kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4482         ipst->ips_ndp4 = NULL;
4483         kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4484         ipst->ips_ndp6 = NULL;
4485 
4486         if (ipst->ips_loopback_ksp != NULL) {
4487                 kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4488                 ipst->ips_loopback_ksp = NULL;
4489         }
4490 
4491         mutex_destroy(&ipst->ips_capab_taskq_lock);
4492         cv_destroy(&ipst->ips_capab_taskq_cv);
4493 
4494         rw_destroy(&ipst->ips_srcid_lock);
4495 
4496         mutex_destroy(&ipst->ips_ip_mi_lock);
4497         rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4498 
4499         mutex_destroy(&ipst->ips_igmp_timer_lock);
4500         mutex_destroy(&ipst->ips_mld_timer_lock);
4501         mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4502         mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4503         mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4504         rw_destroy(&ipst->ips_ill_g_lock);
4505 
4506         kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4507         ipst->ips_phyint_g_list = NULL;
4508         kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4509         ipst->ips_ill_g_heads = NULL;
4510 
4511         ldi_ident_release(ipst->ips_ldi_ident);
4512         kmem_free(ipst, sizeof (*ipst));
4513 }
4514 
4515 /*
4516  * This function is called from the TSD destructor, and is used to debug
4517  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4518  * details.
4519  */
4520 static void
4521 ip_thread_exit(void *phash)
4522 {
4523         th_hash_t *thh = phash;
4524 
4525         rw_enter(&ip_thread_rwlock, RW_WRITER);
4526         list_remove(&ip_thread_list, thh);
4527         rw_exit(&ip_thread_rwlock);
4528         mod_hash_destroy_hash(thh->thh_hash);
4529         kmem_free(thh, sizeof (*thh));
4530 }
4531 
4532 /*
4533  * Called when the IP kernel module is loaded into the kernel
4534  */
4535 void
4536 ip_ddi_init(void)
4537 {
4538         ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4539 
4540         /*
4541          * For IP and TCP the minor numbers should start from 2 since we have 4
4542          * initial devices: ip, ip6, tcp, tcp6.
4543          */
4544         /*
4545          * If this is a 64-bit kernel, then create two separate arenas -
4546          * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4547          * other for socket apps in the range 2^^18 through 2^^32-1.
4548          */
4549         ip_minor_arena_la = NULL;
4550         ip_minor_arena_sa = NULL;
4551 #if defined(_LP64)
4552         if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4553             INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4554                 cmn_err(CE_PANIC,
4555                     "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4556         }
4557         if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4558             MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4559                 cmn_err(CE_PANIC,
4560                     "ip_ddi_init: ip_minor_arena_la creation failed\n");
4561         }
4562 #else
4563         if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4564             INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4565                 cmn_err(CE_PANIC,
4566                     "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4567         }
4568 #endif
4569         ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4570 
4571         ipcl_g_init();
4572         ip_ire_g_init();
4573         ip_net_g_init();
4574 
4575 #ifdef DEBUG
4576         tsd_create(&ip_thread_data, ip_thread_exit);
4577         rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4578         list_create(&ip_thread_list, sizeof (th_hash_t),
4579             offsetof(th_hash_t, thh_link));
4580 #endif
4581         ipsec_policy_g_init();
4582         tcp_ddi_g_init();
4583         sctp_ddi_g_init();
4584         dce_g_init();
4585 
4586         /*
4587          * We want to be informed each time a stack is created or
4588          * destroyed in the kernel, so we can maintain the
4589          * set of udp_stack_t's.
4590          */
4591         netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4592             ip_stack_fini);
4593 
4594         tnet_init();
4595 
4596         udp_ddi_g_init();
4597         rts_ddi_g_init();
4598         icmp_ddi_g_init();
4599         ilb_ddi_g_init();
4600 
4601         /* This needs to be called after all transports are initialized. */
4602         mutex_enter(&cpu_lock);
4603         register_cpu_setup_func(ip_tp_cpu_update, NULL);
4604         mutex_exit(&cpu_lock);
4605 }
4606 
4607 /*
4608  * Initialize the IP stack instance.
4609  */
4610 static void *
4611 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4612 {
4613         ip_stack_t      *ipst;
4614         size_t          arrsz;
4615         major_t         major;
4616 
4617 #ifdef NS_DEBUG
4618         printf("ip_stack_init(stack %d)\n", stackid);
4619 #endif
4620 
4621         ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4622         ipst->ips_netstack = ns;
4623 
4624         ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4625             KM_SLEEP);
4626         ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4627             KM_SLEEP);
4628         ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4629         ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4630         mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4631         mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4632 
4633         mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4634         ipst->ips_igmp_deferred_next = INFINITY;
4635         mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4636         ipst->ips_mld_deferred_next = INFINITY;
4637         mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4638         mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4639         mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4640         mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4641         rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4642         rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4643 
4644         ipcl_init(ipst);
4645         ip_ire_init(ipst);
4646         ip6_asp_init(ipst);
4647         ipif_init(ipst);
4648         conn_drain_init(ipst);
4649         ip_mrouter_stack_init(ipst);
4650         dce_stack_init(ipst);
4651 
4652         ipst->ips_ip_multirt_log_interval = 1000;
4653 
4654         ipst->ips_ill_index = 1;
4655 
4656         ipst->ips_saved_ip_forwarding = -1;
4657         ipst->ips_reg_vif_num = ALL_VIFS;    /* Index to Register vif */
4658 
4659         arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4660         ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4661         bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4662 
4663         ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4664         ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4665         ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4666         ipst->ips_ip6_kstat =
4667             ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4668 
4669         ipst->ips_ip_src_id = 1;
4670         rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4671 
4672         ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4673 
4674         ip_net_init(ipst, ns);
4675         ipv4_hook_init(ipst);
4676         ipv6_hook_init(ipst);
4677         arp_hook_init(ipst);
4678         ipmp_init(ipst);
4679         ipobs_init(ipst);
4680 
4681         /*
4682          * Create the taskq dispatcher thread and initialize related stuff.
4683          */
4684         mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4685         cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4686         ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4687             ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4688 
4689         major = mod_name_to_major(INET_NAME);
4690         (void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4691         return (ipst);
4692 }
4693 
4694 /*
4695  * Allocate and initialize a DLPI template of the specified length.  (May be
4696  * called as writer.)
4697  */
4698 mblk_t *
4699 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4700 {
4701         mblk_t  *mp;
4702 
4703         mp = allocb(len, BPRI_MED);
4704         if (!mp)
4705                 return (NULL);
4706 
4707         /*
4708          * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4709          * of which we don't seem to use) are sent with M_PCPROTO, and
4710          * that other DLPI are M_PROTO.
4711          */
4712         if (prim == DL_INFO_REQ) {
4713                 mp->b_datap->db_type = M_PCPROTO;
4714         } else {
4715                 mp->b_datap->db_type = M_PROTO;
4716         }
4717 
4718         mp->b_wptr = mp->b_rptr + len;
4719         bzero(mp->b_rptr, len);
4720         ((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4721         return (mp);
4722 }
4723 
4724 /*
4725  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4726  */
4727 mblk_t *
4728 ip_dlnotify_alloc(uint_t notification, uint_t data)
4729 {
4730         dl_notify_ind_t *notifyp;
4731         mblk_t          *mp;
4732 
4733         if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4734                 return (NULL);
4735 
4736         notifyp = (dl_notify_ind_t *)mp->b_rptr;
4737         notifyp->dl_notification = notification;
4738         notifyp->dl_data = data;
4739         return (mp);
4740 }
4741 
4742 mblk_t *
4743 ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
4744 {
4745         dl_notify_ind_t *notifyp;
4746         mblk_t          *mp;
4747 
4748         if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4749                 return (NULL);
4750 
4751         notifyp = (dl_notify_ind_t *)mp->b_rptr;
4752         notifyp->dl_notification = notification;
4753         notifyp->dl_data1 = data1;
4754         notifyp->dl_data2 = data2;
4755         return (mp);
4756 }
4757 
4758 /*
4759  * Debug formatting routine.  Returns a character string representation of the
4760  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4761  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4762  *
4763  * Once the ndd table-printing interfaces are removed, this can be changed to
4764  * standard dotted-decimal form.
4765  */
4766 char *
4767 ip_dot_addr(ipaddr_t addr, char *buf)
4768 {
4769         uint8_t *ap = (uint8_t *)&addr;
4770 
4771         (void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4772             ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4773         return (buf);
4774 }
4775 
4776 /*
4777  * Write the given MAC address as a printable string in the usual colon-
4778  * separated format.
4779  */
4780 const char *
4781 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4782 {
4783         char *bp;
4784 
4785         if (alen == 0 || buflen < 4)
4786                 return ("?");
4787         bp = buf;
4788         for (;;) {
4789                 /*
4790                  * If there are more MAC address bytes available, but we won't
4791                  * have any room to print them, then add "..." to the string
4792                  * instead.  See below for the 'magic number' explanation.
4793                  */
4794                 if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4795                         (void) strcpy(bp, "...");
4796                         break;
4797                 }
4798                 (void) sprintf(bp, "%02x", *addr++);
4799                 bp += 2;
4800                 if (--alen == 0)
4801                         break;
4802                 *bp++ = ':';
4803                 buflen -= 3;
4804                 /*
4805                  * At this point, based on the first 'if' statement above,
4806                  * either alen == 1 and buflen >= 3, or alen > 1 and
4807                  * buflen >= 4.  The first case leaves room for the final "xx"
4808                  * number and trailing NUL byte.  The second leaves room for at
4809                  * least "...".  Thus the apparently 'magic' numbers chosen for
4810                  * that statement.
4811                  */
4812         }
4813         return (buf);
4814 }
4815 
4816 /*
4817  * Called when it is conceptually a ULP that would sent the packet
4818  * e.g., port unreachable and protocol unreachable. Check that the packet
4819  * would have passed the IPsec global policy before sending the error.
4820  *
4821  * Send an ICMP error after patching up the packet appropriately.
4822  * Uses ip_drop_input and bumps the appropriate MIB.
4823  */
4824 void
4825 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4826     ip_recv_attr_t *ira)
4827 {
4828         ipha_t          *ipha;
4829         boolean_t       secure;
4830         ill_t           *ill = ira->ira_ill;
4831         ip_stack_t      *ipst = ill->ill_ipst;
4832         netstack_t      *ns = ipst->ips_netstack;
4833         ipsec_stack_t   *ipss = ns->netstack_ipsec;
4834 
4835         secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4836 
4837         /*
4838          * We are generating an icmp error for some inbound packet.
4839          * Called from all ip_fanout_(udp, tcp, proto) functions.
4840          * Before we generate an error, check with global policy
4841          * to see whether this is allowed to enter the system. As
4842          * there is no "conn", we are checking with global policy.
4843          */
4844         ipha = (ipha_t *)mp->b_rptr;
4845         if (secure || ipss->ipsec_inbound_v4_policy_present) {
4846                 mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4847                 if (mp == NULL)
4848                         return;
4849         }
4850 
4851         /* We never send errors for protocols that we do implement */
4852         if (ira->ira_protocol == IPPROTO_ICMP ||
4853             ira->ira_protocol == IPPROTO_IGMP) {
4854                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4855                 ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4856                 freemsg(mp);
4857                 return;
4858         }
4859         /*
4860          * Have to correct checksum since
4861          * the packet might have been
4862          * fragmented and the reassembly code in ip_rput
4863          * does not restore the IP checksum.
4864          */
4865         ipha->ipha_hdr_checksum = 0;
4866         ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4867 
4868         switch (icmp_type) {
4869         case ICMP_DEST_UNREACHABLE:
4870                 switch (icmp_code) {
4871                 case ICMP_PROTOCOL_UNREACHABLE:
4872                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4873                         ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4874                         break;
4875                 case ICMP_PORT_UNREACHABLE:
4876                         BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4877                         ip_drop_input("ipIfStatsNoPorts", mp, ill);
4878                         break;
4879                 }
4880 
4881                 icmp_unreachable(mp, icmp_code, ira);
4882                 break;
4883         default:
4884 #ifdef DEBUG
4885                 panic("ip_fanout_send_icmp_v4: wrong type");
4886                 /*NOTREACHED*/
4887 #else
4888                 freemsg(mp);
4889                 break;
4890 #endif
4891         }
4892 }
4893 
4894 /*
4895  * Used to send an ICMP error message when a packet is received for
4896  * a protocol that is not supported. The mblk passed as argument
4897  * is consumed by this function.
4898  */
4899 void
4900 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4901 {
4902         ipha_t          *ipha;
4903 
4904         ipha = (ipha_t *)mp->b_rptr;
4905         if (ira->ira_flags & IRAF_IS_IPV4) {
4906                 ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4907                 ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4908                     ICMP_PROTOCOL_UNREACHABLE, ira);
4909         } else {
4910                 ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4911                 ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4912                     ICMP6_PARAMPROB_NEXTHEADER, ira);
4913         }
4914 }
4915 
4916 /*
4917  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4918  * Handles IPv4 and IPv6.
4919  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4920  * Caller is responsible for dropping references to the conn.
4921  */
4922 void
4923 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4924     ip_recv_attr_t *ira)
4925 {
4926         ill_t           *ill = ira->ira_ill;
4927         ip_stack_t      *ipst = ill->ill_ipst;
4928         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
4929         boolean_t       secure;
4930         uint_t          protocol = ira->ira_protocol;
4931         iaflags_t       iraflags = ira->ira_flags;
4932         queue_t         *rq;
4933 
4934         secure = iraflags & IRAF_IPSEC_SECURE;
4935 
4936         rq = connp->conn_rq;
4937         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4938                 switch (protocol) {
4939                 case IPPROTO_ICMPV6:
4940                         BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4941                         break;
4942                 case IPPROTO_ICMP:
4943                         BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4944                         break;
4945                 default:
4946                         BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4947                         break;
4948                 }
4949                 freemsg(mp);
4950                 return;
4951         }
4952 
4953         ASSERT(!(IPCL_IS_IPTUN(connp)));
4954 
4955         if (((iraflags & IRAF_IS_IPV4) ?
4956             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4957             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4958             secure) {
4959                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
4960                     ip6h, ira);
4961                 if (mp == NULL) {
4962                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4963                         /* Note that mp is NULL */
4964                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
4965                         return;
4966                 }
4967         }
4968 
4969         if (iraflags & IRAF_ICMP_ERROR) {
4970                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
4971         } else {
4972                 ill_t *rill = ira->ira_rill;
4973 
4974                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4975                 ira->ira_ill = ira->ira_rill = NULL;
4976                 /* Send it upstream */
4977                 (connp->conn_recv)(connp, mp, NULL, ira);
4978                 ira->ira_ill = ill;
4979                 ira->ira_rill = rill;
4980         }
4981 }
4982 
4983 /*
4984  * Handle protocols with which IP is less intimate.  There
4985  * can be more than one stream bound to a particular
4986  * protocol.  When this is the case, normally each one gets a copy
4987  * of any incoming packets.
4988  *
4989  * IPsec NOTE :
4990  *
4991  * Don't allow a secure packet going up a non-secure connection.
4992  * We don't allow this because
4993  *
4994  * 1) Reply might go out in clear which will be dropped at
4995  *    the sending side.
4996  * 2) If the reply goes out in clear it will give the
4997  *    adversary enough information for getting the key in
4998  *    most of the cases.
4999  *
5000  * Moreover getting a secure packet when we expect clear
5001  * implies that SA's were added without checking for
5002  * policy on both ends. This should not happen once ISAKMP
5003  * is used to negotiate SAs as SAs will be added only after
5004  * verifying the policy.
5005  *
5006  * Zones notes:
5007  * Earlier in ip_input on a system with multiple shared-IP zones we
5008  * duplicate the multicast and broadcast packets and send them up
5009  * with each explicit zoneid that exists on that ill.
5010  * This means that here we can match the zoneid with SO_ALLZONES being special.
5011  */
5012 void
5013 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5014 {
5015         mblk_t          *mp1;
5016         ipaddr_t        laddr;
5017         conn_t          *connp, *first_connp, *next_connp;
5018         connf_t         *connfp;
5019         ill_t           *ill = ira->ira_ill;
5020         ip_stack_t      *ipst = ill->ill_ipst;
5021 
5022         laddr = ipha->ipha_dst;
5023 
5024         connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5025         mutex_enter(&connfp->connf_lock);
5026         connp = connfp->connf_head;
5027         for (connp = connfp->connf_head; connp != NULL;
5028             connp = connp->conn_next) {
5029                 /* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5030                 if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5031                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5032                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5033                         break;
5034                 }
5035         }
5036 
5037         if (connp == NULL) {
5038                 /*
5039                  * No one bound to these addresses.  Is
5040                  * there a client that wants all
5041                  * unclaimed datagrams?
5042                  */
5043                 mutex_exit(&connfp->connf_lock);
5044                 ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5045                     ICMP_PROTOCOL_UNREACHABLE, ira);
5046                 return;
5047         }
5048 
5049         ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5050 
5051         CONN_INC_REF(connp);
5052         first_connp = connp;
5053         connp = connp->conn_next;
5054 
5055         for (;;) {
5056                 while (connp != NULL) {
5057                         /* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5058                         if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5059                             (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5060                             tsol_receive_local(mp, &laddr, IPV4_VERSION,
5061                             ira, connp)))
5062                                 break;
5063                         connp = connp->conn_next;
5064                 }
5065 
5066                 if (connp == NULL) {
5067                         /* No more interested clients */
5068                         connp = first_connp;
5069                         break;
5070                 }
5071                 if (((mp1 = dupmsg(mp)) == NULL) &&
5072                     ((mp1 = copymsg(mp)) == NULL)) {
5073                         /* Memory allocation failed */
5074                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5075                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
5076                         connp = first_connp;
5077                         break;
5078                 }
5079 
5080                 CONN_INC_REF(connp);
5081                 mutex_exit(&connfp->connf_lock);
5082 
5083                 ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5084                     ira);
5085 
5086                 mutex_enter(&connfp->connf_lock);
5087                 /* Follow the next pointer before releasing the conn. */
5088                 next_connp = connp->conn_next;
5089                 CONN_DEC_REF(connp);
5090                 connp = next_connp;
5091         }
5092 
5093         /* Last one.  Send it upstream. */
5094         mutex_exit(&connfp->connf_lock);
5095 
5096         ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5097 
5098         CONN_DEC_REF(connp);
5099 }
5100 
5101 /*
5102  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5103  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5104  * is not consumed.
5105  *
5106  * One of three things can happen, all of which affect the passed-in mblk:
5107  *
5108  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5109  *
5110  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5111  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5112  *
5113  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5114  */
5115 mblk_t *
5116 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5117 {
5118         int shift, plen, iph_len;
5119         ipha_t *ipha;
5120         udpha_t *udpha;
5121         uint32_t *spi;
5122         uint32_t esp_ports;
5123         uint8_t *orptr;
5124         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
5125         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
5126 
5127         ipha = (ipha_t *)mp->b_rptr;
5128         iph_len = ira->ira_ip_hdr_length;
5129         plen = ira->ira_pktlen;
5130 
5131         if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5132                 /*
5133                  * Most likely a keepalive for the benefit of an intervening
5134                  * NAT.  These aren't for us, per se, so drop it.
5135                  *
5136                  * RFC 3947/8 doesn't say for sure what to do for 2-3
5137                  * byte packets (keepalives are 1-byte), but we'll drop them
5138                  * also.
5139                  */
5140                 ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5141                     DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5142                 return (NULL);
5143         }
5144 
5145         if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5146                 /* might as well pull it all up - it might be ESP. */
5147                 if (!pullupmsg(mp, -1)) {
5148                         ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5149                             DROPPER(ipss, ipds_esp_nomem),
5150                             &ipss->ipsec_dropper);
5151                         return (NULL);
5152                 }
5153 
5154                 ipha = (ipha_t *)mp->b_rptr;
5155         }
5156         spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5157         if (*spi == 0) {
5158                 /* UDP packet - remove 0-spi. */
5159                 shift = sizeof (uint32_t);
5160         } else {
5161                 /* ESP-in-UDP packet - reduce to ESP. */
5162                 ipha->ipha_protocol = IPPROTO_ESP;
5163                 shift = sizeof (udpha_t);
5164         }
5165 
5166         /* Fix IP header */
5167         ira->ira_pktlen = (plen - shift);
5168         ipha->ipha_length = htons(ira->ira_pktlen);
5169         ipha->ipha_hdr_checksum = 0;
5170 
5171         orptr = mp->b_rptr;
5172         mp->b_rptr += shift;
5173 
5174         udpha = (udpha_t *)(orptr + iph_len);
5175         if (*spi == 0) {
5176                 ASSERT((uint8_t *)ipha == orptr);
5177                 udpha->uha_length = htons(plen - shift - iph_len);
5178                 iph_len += sizeof (udpha_t);    /* For the call to ovbcopy(). */
5179                 esp_ports = 0;
5180         } else {
5181                 esp_ports = *((uint32_t *)udpha);
5182                 ASSERT(esp_ports != 0);
5183         }
5184         ovbcopy(orptr, orptr + shift, iph_len);
5185         if (esp_ports != 0) /* Punt up for ESP processing. */ {
5186                 ipha = (ipha_t *)(orptr + shift);
5187 
5188                 ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5189                 ira->ira_esp_udp_ports = esp_ports;
5190                 ip_fanout_v4(mp, ipha, ira);
5191                 return (NULL);
5192         }
5193         return (mp);
5194 }
5195 
5196 /*
5197  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5198  * Handles IPv4 and IPv6.
5199  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5200  * Caller is responsible for dropping references to the conn.
5201  */
5202 void
5203 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5204     ip_recv_attr_t *ira)
5205 {
5206         ill_t           *ill = ira->ira_ill;
5207         ip_stack_t      *ipst = ill->ill_ipst;
5208         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
5209         boolean_t       secure;
5210         iaflags_t       iraflags = ira->ira_flags;
5211 
5212         secure = iraflags & IRAF_IPSEC_SECURE;
5213 
5214         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5215             !canputnext(connp->conn_rq)) {
5216                 BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5217                 freemsg(mp);
5218                 return;
5219         }
5220 
5221         if (((iraflags & IRAF_IS_IPV4) ?
5222             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5223             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5224             secure) {
5225                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
5226                     ip6h, ira);
5227                 if (mp == NULL) {
5228                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5229                         /* Note that mp is NULL */
5230                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
5231                         return;
5232                 }
5233         }
5234 
5235         /*
5236          * Since this code is not used for UDP unicast we don't need a NAT_T
5237          * check. Only ip_fanout_v4 has that check.
5238          */
5239         if (ira->ira_flags & IRAF_ICMP_ERROR) {
5240                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
5241         } else {
5242                 ill_t *rill = ira->ira_rill;
5243 
5244                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5245                 ira->ira_ill = ira->ira_rill = NULL;
5246                 /* Send it upstream */
5247                 (connp->conn_recv)(connp, mp, NULL, ira);
5248                 ira->ira_ill = ill;
5249                 ira->ira_rill = rill;
5250         }
5251 }
5252 
5253 /*
5254  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5255  * (Unicast fanout is handled in ip_input_v4.)
5256  *
5257  * If SO_REUSEADDR is set all multicast and broadcast packets
5258  * will be delivered to all conns bound to the same port.
5259  *
5260  * If there is at least one matching AF_INET receiver, then we will
5261  * ignore any AF_INET6 receivers.
5262  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5263  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5264  * packets.
5265  *
5266  * Zones notes:
5267  * Earlier in ip_input on a system with multiple shared-IP zones we
5268  * duplicate the multicast and broadcast packets and send them up
5269  * with each explicit zoneid that exists on that ill.
5270  * This means that here we can match the zoneid with SO_ALLZONES being special.
5271  */
5272 void
5273 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5274     ip_recv_attr_t *ira)
5275 {
5276         ipaddr_t        laddr;
5277         in6_addr_t      v6faddr;
5278         conn_t          *connp;
5279         connf_t         *connfp;
5280         ipaddr_t        faddr;
5281         ill_t           *ill = ira->ira_ill;
5282         ip_stack_t      *ipst = ill->ill_ipst;
5283 
5284         ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5285 
5286         laddr = ipha->ipha_dst;
5287         faddr = ipha->ipha_src;
5288 
5289         connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5290         mutex_enter(&connfp->connf_lock);
5291         connp = connfp->connf_head;
5292 
5293         /*
5294          * If SO_REUSEADDR has been set on the first we send the
5295          * packet to all clients that have joined the group and
5296          * match the port.
5297          */
5298         while (connp != NULL) {
5299                 if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5300                     conn_wantpacket(connp, ira, ipha) &&
5301                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5302                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5303                         break;
5304                 connp = connp->conn_next;
5305         }
5306 
5307         if (connp == NULL)
5308                 goto notfound;
5309 
5310         CONN_INC_REF(connp);
5311 
5312         if (connp->conn_reuseaddr) {
5313                 conn_t          *first_connp = connp;
5314                 conn_t          *next_connp;
5315                 mblk_t          *mp1;
5316 
5317                 connp = connp->conn_next;
5318                 for (;;) {
5319                         while (connp != NULL) {
5320                                 if (IPCL_UDP_MATCH(connp, lport, laddr,
5321                                     fport, faddr) &&
5322                                     conn_wantpacket(connp, ira, ipha) &&
5323                                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5324                                     tsol_receive_local(mp, &laddr, IPV4_VERSION,
5325                                     ira, connp)))
5326                                         break;
5327                                 connp = connp->conn_next;
5328                         }
5329                         if (connp == NULL) {
5330                                 /* No more interested clients */
5331                                 connp = first_connp;
5332                                 break;
5333                         }
5334                         if (((mp1 = dupmsg(mp)) == NULL) &&
5335                             ((mp1 = copymsg(mp)) == NULL)) {
5336                                 /* Memory allocation failed */
5337                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5338                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
5339                                 connp = first_connp;
5340                                 break;
5341                         }
5342                         CONN_INC_REF(connp);
5343                         mutex_exit(&connfp->connf_lock);
5344 
5345                         IP_STAT(ipst, ip_udp_fanmb);
5346                         ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5347                             NULL, ira);
5348                         mutex_enter(&connfp->connf_lock);
5349                         /* Follow the next pointer before releasing the conn */
5350                         next_connp = connp->conn_next;
5351                         CONN_DEC_REF(connp);
5352                         connp = next_connp;
5353                 }
5354         }
5355 
5356         /* Last one.  Send it upstream. */
5357         mutex_exit(&connfp->connf_lock);
5358         IP_STAT(ipst, ip_udp_fanmb);
5359         ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5360         CONN_DEC_REF(connp);
5361         return;
5362 
5363 notfound:
5364         mutex_exit(&connfp->connf_lock);
5365         /*
5366          * IPv6 endpoints bound to multicast IPv4-mapped addresses
5367          * have already been matched above, since they live in the IPv4
5368          * fanout tables. This implies we only need to
5369          * check for IPv6 in6addr_any endpoints here.
5370          * Thus we compare using ipv6_all_zeros instead of the destination
5371          * address, except for the multicast group membership lookup which
5372          * uses the IPv4 destination.
5373          */
5374         IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5375         connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5376         mutex_enter(&connfp->connf_lock);
5377         connp = connfp->connf_head;
5378         /*
5379          * IPv4 multicast packet being delivered to an AF_INET6
5380          * in6addr_any endpoint.
5381          * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5382          * and not conn_wantpacket_v6() since any multicast membership is
5383          * for an IPv4-mapped multicast address.
5384          */
5385         while (connp != NULL) {
5386                 if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5387                     fport, v6faddr) &&
5388                     conn_wantpacket(connp, ira, ipha) &&
5389                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5390                     tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5391                         break;
5392                 connp = connp->conn_next;
5393         }
5394 
5395         if (connp == NULL) {
5396                 /*
5397                  * No one bound to this port.  Is
5398                  * there a client that wants all
5399                  * unclaimed datagrams?
5400                  */
5401                 mutex_exit(&connfp->connf_lock);
5402 
5403                 if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5404                     NULL) {
5405                         ASSERT(ira->ira_protocol == IPPROTO_UDP);
5406                         ip_fanout_proto_v4(mp, ipha, ira);
5407                 } else {
5408                         /*
5409                          * We used to attempt to send an icmp error here, but
5410                          * since this is known to be a multicast packet
5411                          * and we don't send icmp errors in response to
5412                          * multicast, just drop the packet and give up sooner.
5413                          */
5414                         BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5415                         freemsg(mp);
5416                 }
5417                 return;
5418         }
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                 CONN_INC_REF(connp);
5432                 connp = connp->conn_next;
5433                 for (;;) {
5434                         while (connp != NULL) {
5435                                 if (IPCL_UDP_MATCH_V6(connp, lport,
5436                                     ipv6_all_zeros, fport, v6faddr) &&
5437                                     conn_wantpacket(connp, ira, ipha) &&
5438                                     (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5439                                     tsol_receive_local(mp, &laddr, IPV4_VERSION,
5440                                     ira, connp)))
5441                                         break;
5442                                 connp = connp->conn_next;
5443                         }
5444                         if (connp == NULL) {
5445                                 /* No more interested clients */
5446                                 connp = first_connp;
5447                                 break;
5448                         }
5449                         if (((mp1 = dupmsg(mp)) == NULL) &&
5450                             ((mp1 = copymsg(mp)) == NULL)) {
5451                                 /* Memory allocation failed */
5452                                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5453                                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
5454                                 connp = first_connp;
5455                                 break;
5456                         }
5457                         CONN_INC_REF(connp);
5458                         mutex_exit(&connfp->connf_lock);
5459 
5460                         IP_STAT(ipst, ip_udp_fanmb);
5461                         ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5462                             NULL, ira);
5463                         mutex_enter(&connfp->connf_lock);
5464                         /* Follow the next pointer before releasing the conn */
5465                         next_connp = connp->conn_next;
5466                         CONN_DEC_REF(connp);
5467                         connp = next_connp;
5468                 }
5469         }
5470 
5471         /* Last one.  Send it upstream. */
5472         mutex_exit(&connfp->connf_lock);
5473         IP_STAT(ipst, ip_udp_fanmb);
5474         ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5475         CONN_DEC_REF(connp);
5476 }
5477 
5478 /*
5479  * Split an incoming packet's IPv4 options into the label and the other options.
5480  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5481  * clearing out any leftover label or options.
5482  * Otherwise it just makes ipp point into the packet.
5483  *
5484  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5485  */
5486 int
5487 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5488 {
5489         uchar_t         *opt;
5490         uint32_t        totallen;
5491         uint32_t        optval;
5492         uint32_t        optlen;
5493 
5494         ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5495         ipp->ipp_hoplimit = ipha->ipha_ttl;
5496         ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5497         IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5498 
5499         /*
5500          * Get length (in 4 byte octets) of IP header options.
5501          */
5502         totallen = ipha->ipha_version_and_hdr_length -
5503             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5504 
5505         if (totallen == 0) {
5506                 if (!allocate)
5507                         return (0);
5508 
5509                 /* Clear out anything from a previous packet */
5510                 if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5511                         kmem_free(ipp->ipp_ipv4_options,
5512                             ipp->ipp_ipv4_options_len);
5513                         ipp->ipp_ipv4_options = NULL;
5514                         ipp->ipp_ipv4_options_len = 0;
5515                         ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5516                 }
5517                 if (ipp->ipp_fields & IPPF_LABEL_V4) {
5518                         kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5519                         ipp->ipp_label_v4 = NULL;
5520                         ipp->ipp_label_len_v4 = 0;
5521                         ipp->ipp_fields &= ~IPPF_LABEL_V4;
5522                 }
5523                 return (0);
5524         }
5525 
5526         totallen <<= 2;
5527         opt = (uchar_t *)&ipha[1];
5528         if (!is_system_labeled()) {
5529 
5530         copyall:
5531                 if (!allocate) {
5532                         if (totallen != 0) {
5533                                 ipp->ipp_ipv4_options = opt;
5534                                 ipp->ipp_ipv4_options_len = totallen;
5535                                 ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5536                         }
5537                         return (0);
5538                 }
5539                 /* Just copy all of options */
5540                 if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5541                         if (totallen == ipp->ipp_ipv4_options_len) {
5542                                 bcopy(opt, ipp->ipp_ipv4_options, totallen);
5543                                 return (0);
5544                         }
5545                         kmem_free(ipp->ipp_ipv4_options,
5546                             ipp->ipp_ipv4_options_len);
5547                         ipp->ipp_ipv4_options = NULL;
5548                         ipp->ipp_ipv4_options_len = 0;
5549                         ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5550                 }
5551                 if (totallen == 0)
5552                         return (0);
5553 
5554                 ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5555                 if (ipp->ipp_ipv4_options == NULL)
5556                         return (ENOMEM);
5557                 ipp->ipp_ipv4_options_len = totallen;
5558                 ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5559                 bcopy(opt, ipp->ipp_ipv4_options, totallen);
5560                 return (0);
5561         }
5562 
5563         if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5564                 kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5565                 ipp->ipp_label_v4 = NULL;
5566                 ipp->ipp_label_len_v4 = 0;
5567                 ipp->ipp_fields &= ~IPPF_LABEL_V4;
5568         }
5569 
5570         /*
5571          * Search for CIPSO option.
5572          * We assume CIPSO is first in options if it is present.
5573          * If it isn't, then ipp_opt_ipv4_options will not include the options
5574          * prior to the CIPSO option.
5575          */
5576         while (totallen != 0) {
5577                 switch (optval = opt[IPOPT_OPTVAL]) {
5578                 case IPOPT_EOL:
5579                         return (0);
5580                 case IPOPT_NOP:
5581                         optlen = 1;
5582                         break;
5583                 default:
5584                         if (totallen <= IPOPT_OLEN)
5585                                 return (EINVAL);
5586                         optlen = opt[IPOPT_OLEN];
5587                         if (optlen < 2)
5588                                 return (EINVAL);
5589                 }
5590                 if (optlen > totallen)
5591                         return (EINVAL);
5592 
5593                 switch (optval) {
5594                 case IPOPT_COMSEC:
5595                         if (!allocate) {
5596                                 ipp->ipp_label_v4 = opt;
5597                                 ipp->ipp_label_len_v4 = optlen;
5598                                 ipp->ipp_fields |= IPPF_LABEL_V4;
5599                         } else {
5600                                 ipp->ipp_label_v4 = kmem_alloc(optlen,
5601                                     KM_NOSLEEP);
5602                                 if (ipp->ipp_label_v4 == NULL)
5603                                         return (ENOMEM);
5604                                 ipp->ipp_label_len_v4 = optlen;
5605                                 ipp->ipp_fields |= IPPF_LABEL_V4;
5606                                 bcopy(opt, ipp->ipp_label_v4, optlen);
5607                         }
5608                         totallen -= optlen;
5609                         opt += optlen;
5610 
5611                         /* Skip padding bytes until we get to a multiple of 4 */
5612                         while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5613                                 totallen--;
5614                                 opt++;
5615                         }
5616                         /* Remaining as ipp_ipv4_options */
5617                         goto copyall;
5618                 }
5619                 totallen -= optlen;
5620                 opt += optlen;
5621         }
5622         /* No CIPSO found; return everything as ipp_ipv4_options */
5623         totallen = ipha->ipha_version_and_hdr_length -
5624             (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5625         totallen <<= 2;
5626         opt = (uchar_t *)&ipha[1];
5627         goto copyall;
5628 }
5629 
5630 /*
5631  * Efficient versions of lookup for an IRE when we only
5632  * match the address.
5633  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5634  * Does not handle multicast addresses.
5635  */
5636 uint_t
5637 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5638 {
5639         ire_t *ire;
5640         uint_t result;
5641 
5642         ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5643         ASSERT(ire != NULL);
5644         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5645                 result = IRE_NOROUTE;
5646         else
5647                 result = ire->ire_type;
5648         ire_refrele(ire);
5649         return (result);
5650 }
5651 
5652 /*
5653  * Efficient versions of lookup for an IRE when we only
5654  * match the address.
5655  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5656  * Does not handle multicast addresses.
5657  */
5658 uint_t
5659 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5660 {
5661         ire_t *ire;
5662         uint_t result;
5663 
5664         ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5665         ASSERT(ire != NULL);
5666         if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5667                 result = IRE_NOROUTE;
5668         else
5669                 result = ire->ire_type;
5670         ire_refrele(ire);
5671         return (result);
5672 }
5673 
5674 /*
5675  * Nobody should be sending
5676  * packets up this stream
5677  */
5678 static void
5679 ip_lrput(queue_t *q, mblk_t *mp)
5680 {
5681         switch (mp->b_datap->db_type) {
5682         case M_FLUSH:
5683                 /* Turn around */
5684                 if (*mp->b_rptr & FLUSHW) {
5685                         *mp->b_rptr &= ~FLUSHR;
5686                         qreply(q, mp);
5687                         return;
5688                 }
5689                 break;
5690         }
5691         freemsg(mp);
5692 }
5693 
5694 /* Nobody should be sending packets down this stream */
5695 /* ARGSUSED */
5696 void
5697 ip_lwput(queue_t *q, mblk_t *mp)
5698 {
5699         freemsg(mp);
5700 }
5701 
5702 /*
5703  * Move the first hop in any source route to ipha_dst and remove that part of
5704  * the source route.  Called by other protocols.  Errors in option formatting
5705  * are ignored - will be handled by ip_output_options. Return the final
5706  * destination (either ipha_dst or the last entry in a source route.)
5707  */
5708 ipaddr_t
5709 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5710 {
5711         ipoptp_t        opts;
5712         uchar_t         *opt;
5713         uint8_t         optval;
5714         uint8_t         optlen;
5715         ipaddr_t        dst;
5716         int             i;
5717         ip_stack_t      *ipst = ns->netstack_ip;
5718 
5719         ip2dbg(("ip_massage_options\n"));
5720         dst = ipha->ipha_dst;
5721         for (optval = ipoptp_first(&opts, ipha);
5722             optval != IPOPT_EOL;
5723             optval = ipoptp_next(&opts)) {
5724                 opt = opts.ipoptp_cur;
5725                 switch (optval) {
5726                         uint8_t off;
5727                 case IPOPT_SSRR:
5728                 case IPOPT_LSRR:
5729                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5730                                 ip1dbg(("ip_massage_options: bad src route\n"));
5731                                 break;
5732                         }
5733                         optlen = opts.ipoptp_len;
5734                         off = opt[IPOPT_OFFSET];
5735                         off--;
5736                 redo_srr:
5737                         if (optlen < IP_ADDR_LEN ||
5738                             off > optlen - IP_ADDR_LEN) {
5739                                 /* End of source route */
5740                                 ip1dbg(("ip_massage_options: end of SR\n"));
5741                                 break;
5742                         }
5743                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5744                         ip1dbg(("ip_massage_options: next hop 0x%x\n",
5745                             ntohl(dst)));
5746                         /*
5747                          * Check if our address is present more than
5748                          * once as consecutive hops in source route.
5749                          * XXX verify per-interface ip_forwarding
5750                          * for source route?
5751                          */
5752                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5753                                 off += IP_ADDR_LEN;
5754                                 goto redo_srr;
5755                         }
5756                         if (dst == htonl(INADDR_LOOPBACK)) {
5757                                 ip1dbg(("ip_massage_options: loopback addr in "
5758                                     "source route!\n"));
5759                                 break;
5760                         }
5761                         /*
5762                          * Update ipha_dst to be the first hop and remove the
5763                          * first hop from the source route (by overwriting
5764                          * part of the option with NOP options).
5765                          */
5766                         ipha->ipha_dst = dst;
5767                         /* Put the last entry in dst */
5768                         off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5769                             3;
5770                         bcopy(&opt[off], &dst, IP_ADDR_LEN);
5771 
5772                         ip1dbg(("ip_massage_options: last hop 0x%x\n",
5773                             ntohl(dst)));
5774                         /* Move down and overwrite */
5775                         opt[IP_ADDR_LEN] = opt[0];
5776                         opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5777                         opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5778                         for (i = 0; i < IP_ADDR_LEN; i++)
5779                                 opt[i] = IPOPT_NOP;
5780                         break;
5781                 }
5782         }
5783         return (dst);
5784 }
5785 
5786 /*
5787  * Return the network mask
5788  * associated with the specified address.
5789  */
5790 ipaddr_t
5791 ip_net_mask(ipaddr_t addr)
5792 {
5793         uchar_t *up = (uchar_t *)&addr;
5794         ipaddr_t mask = 0;
5795         uchar_t *maskp = (uchar_t *)&mask;
5796 
5797 #if defined(__i386) || defined(__amd64)
5798 #define TOTALLY_BRAIN_DAMAGED_C_COMPILER
5799 #endif
5800 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5801         maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5802 #endif
5803         if (CLASSD(addr)) {
5804                 maskp[0] = 0xF0;
5805                 return (mask);
5806         }
5807 
5808         /* We assume Class E default netmask to be 32 */
5809         if (CLASSE(addr))
5810                 return (0xffffffffU);
5811 
5812         if (addr == 0)
5813                 return (0);
5814         maskp[0] = 0xFF;
5815         if ((up[0] & 0x80) == 0)
5816                 return (mask);
5817 
5818         maskp[1] = 0xFF;
5819         if ((up[0] & 0xC0) == 0x80)
5820                 return (mask);
5821 
5822         maskp[2] = 0xFF;
5823         if ((up[0] & 0xE0) == 0xC0)
5824                 return (mask);
5825 
5826         /* Otherwise return no mask */
5827         return ((ipaddr_t)0);
5828 }
5829 
5830 /* Name/Value Table Lookup Routine */
5831 char *
5832 ip_nv_lookup(nv_t *nv, int value)
5833 {
5834         if (!nv)
5835                 return (NULL);
5836         for (; nv->nv_name; nv++) {
5837                 if (nv->nv_value == value)
5838                         return (nv->nv_name);
5839         }
5840         return ("unknown");
5841 }
5842 
5843 static int
5844 ip_wait_for_info_ack(ill_t *ill)
5845 {
5846         int err;
5847 
5848         mutex_enter(&ill->ill_lock);
5849         while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5850                 /*
5851                  * Return value of 0 indicates a pending signal.
5852                  */
5853                 err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5854                 if (err == 0) {
5855                         mutex_exit(&ill->ill_lock);
5856                         return (EINTR);
5857                 }
5858         }
5859         mutex_exit(&ill->ill_lock);
5860         /*
5861          * ip_rput_other could have set an error  in ill_error on
5862          * receipt of M_ERROR.
5863          */
5864         return (ill->ill_error);
5865 }
5866 
5867 /*
5868  * This is a module open, i.e. this is a control stream for access
5869  * to a DLPI device.  We allocate an ill_t as the instance data in
5870  * this case.
5871  */
5872 static int
5873 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5874 {
5875         ill_t   *ill;
5876         int     err;
5877         zoneid_t zoneid;
5878         netstack_t *ns;
5879         ip_stack_t *ipst;
5880 
5881         /*
5882          * Prevent unprivileged processes from pushing IP so that
5883          * they can't send raw IP.
5884          */
5885         if (secpolicy_net_rawaccess(credp) != 0)
5886                 return (EPERM);
5887 
5888         ns = netstack_find_by_cred(credp);
5889         ASSERT(ns != NULL);
5890         ipst = ns->netstack_ip;
5891         ASSERT(ipst != NULL);
5892 
5893         /*
5894          * For exclusive stacks we set the zoneid to zero
5895          * to make IP operate as if in the global zone.
5896          */
5897         if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5898                 zoneid = GLOBAL_ZONEID;
5899         else
5900                 zoneid = crgetzoneid(credp);
5901 
5902         ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5903         q->q_ptr = WR(q)->q_ptr = ill;
5904         ill->ill_ipst = ipst;
5905         ill->ill_zoneid = zoneid;
5906 
5907         /*
5908          * ill_init initializes the ill fields and then sends down
5909          * down a DL_INFO_REQ after calling qprocson.
5910          */
5911         err = ill_init(q, ill);
5912 
5913         if (err != 0) {
5914                 mi_free(ill);
5915                 netstack_rele(ipst->ips_netstack);
5916                 q->q_ptr = NULL;
5917                 WR(q)->q_ptr = NULL;
5918                 return (err);
5919         }
5920 
5921         /*
5922          * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5923          *
5924          * ill_init initializes the ipsq marking this thread as
5925          * writer
5926          */
5927         ipsq_exit(ill->ill_phyint->phyint_ipsq);
5928         err = ip_wait_for_info_ack(ill);
5929         if (err == 0)
5930                 ill->ill_credp = credp;
5931         else
5932                 goto fail;
5933 
5934         crhold(credp);
5935 
5936         mutex_enter(&ipst->ips_ip_mi_lock);
5937         err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5938             sflag, credp);
5939         mutex_exit(&ipst->ips_ip_mi_lock);
5940 fail:
5941         if (err) {
5942                 (void) ip_close(q, 0);
5943                 return (err);
5944         }
5945         return (0);
5946 }
5947 
5948 /* For /dev/ip aka AF_INET open */
5949 int
5950 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5951 {
5952         return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5953 }
5954 
5955 /* For /dev/ip6 aka AF_INET6 open */
5956 int
5957 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5958 {
5959         return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5960 }
5961 
5962 /* IP open routine. */
5963 int
5964 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5965     boolean_t isv6)
5966 {
5967         conn_t          *connp;
5968         major_t         maj;
5969         zoneid_t        zoneid;
5970         netstack_t      *ns;
5971         ip_stack_t      *ipst;
5972 
5973         /* Allow reopen. */
5974         if (q->q_ptr != NULL)
5975                 return (0);
5976 
5977         if (sflag & MODOPEN) {
5978                 /* This is a module open */
5979                 return (ip_modopen(q, devp, flag, sflag, credp));
5980         }
5981 
5982         if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5983                 /*
5984                  * Non streams based socket looking for a stream
5985                  * to access IP
5986                  */
5987                 return (ip_helper_stream_setup(q, devp, flag, sflag,
5988                     credp, isv6));
5989         }
5990 
5991         ns = netstack_find_by_cred(credp);
5992         ASSERT(ns != NULL);
5993         ipst = ns->netstack_ip;
5994         ASSERT(ipst != NULL);
5995 
5996         /*
5997          * For exclusive stacks we set the zoneid to zero
5998          * to make IP operate as if in the global zone.
5999          */
6000         if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
6001                 zoneid = GLOBAL_ZONEID;
6002         else
6003                 zoneid = crgetzoneid(credp);
6004 
6005         /*
6006          * We are opening as a device. This is an IP client stream, and we
6007          * allocate an conn_t as the instance data.
6008          */
6009         connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6010 
6011         /*
6012          * ipcl_conn_create did a netstack_hold. Undo the hold that was
6013          * done by netstack_find_by_cred()
6014          */
6015         netstack_rele(ipst->ips_netstack);
6016 
6017         connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6018         /* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6019         connp->conn_ixa->ixa_zoneid = zoneid;
6020         connp->conn_zoneid = zoneid;
6021 
6022         connp->conn_rq = q;
6023         q->q_ptr = WR(q)->q_ptr = connp;
6024 
6025         /* Minor tells us which /dev entry was opened */
6026         if (isv6) {
6027                 connp->conn_family = AF_INET6;
6028                 connp->conn_ipversion = IPV6_VERSION;
6029                 connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6030                 connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6031         } else {
6032                 connp->conn_family = AF_INET;
6033                 connp->conn_ipversion = IPV4_VERSION;
6034                 connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6035         }
6036 
6037         if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6038             ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6039                 connp->conn_minor_arena = ip_minor_arena_la;
6040         } else {
6041                 /*
6042                  * Either minor numbers in the large arena were exhausted
6043                  * or a non socket application is doing the open.
6044                  * Try to allocate from the small arena.
6045                  */
6046                 if ((connp->conn_dev =
6047                     inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6048                         /* CONN_DEC_REF takes care of netstack_rele() */
6049                         q->q_ptr = WR(q)->q_ptr = NULL;
6050                         CONN_DEC_REF(connp);
6051                         return (EBUSY);
6052                 }
6053                 connp->conn_minor_arena = ip_minor_arena_sa;
6054         }
6055 
6056         maj = getemajor(*devp);
6057         *devp = makedevice(maj, (minor_t)connp->conn_dev);
6058 
6059         /*
6060          * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6061          */
6062         connp->conn_cred = credp;
6063         connp->conn_cpid = curproc->p_pid;
6064         /* Cache things in ixa without an extra refhold */
6065         ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6066         connp->conn_ixa->ixa_cred = connp->conn_cred;
6067         connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6068         if (is_system_labeled())
6069                 connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6070 
6071         /*
6072          * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6073          */
6074         connp->conn_recv = ip_conn_input;
6075         connp->conn_recvicmp = ip_conn_input_icmp;
6076 
6077         crhold(connp->conn_cred);
6078 
6079         /*
6080          * If the caller has the process-wide flag set, then default to MAC
6081          * exempt mode.  This allows read-down to unlabeled hosts.
6082          */
6083         if (getpflags(NET_MAC_AWARE, credp) != 0)
6084                 connp->conn_mac_mode = CONN_MAC_AWARE;
6085 
6086         connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6087 
6088         connp->conn_rq = q;
6089         connp->conn_wq = WR(q);
6090 
6091         /* Non-zero default values */
6092         connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6093 
6094         /*
6095          * Make the conn globally visible to walkers
6096          */
6097         ASSERT(connp->conn_ref == 1);
6098         mutex_enter(&connp->conn_lock);
6099         connp->conn_state_flags &= ~CONN_INCIPIENT;
6100         mutex_exit(&connp->conn_lock);
6101 
6102         qprocson(q);
6103 
6104         return (0);
6105 }
6106 
6107 /*
6108  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6109  * all of them are copied to the conn_t. If the req is "zero", the policy is
6110  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6111  * fields.
6112  * We keep only the latest setting of the policy and thus policy setting
6113  * is not incremental/cumulative.
6114  *
6115  * Requests to set policies with multiple alternative actions will
6116  * go through a different API.
6117  */
6118 int
6119 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6120 {
6121         uint_t ah_req = 0;
6122         uint_t esp_req = 0;
6123         uint_t se_req = 0;
6124         ipsec_act_t *actp = NULL;
6125         uint_t nact;
6126         ipsec_policy_head_t *ph;
6127         boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6128         int error = 0;
6129         netstack_t      *ns = connp->conn_netstack;
6130         ip_stack_t      *ipst = ns->netstack_ip;
6131         ipsec_stack_t   *ipss = ns->netstack_ipsec;
6132 
6133 #define REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6134 
6135         /*
6136          * The IP_SEC_OPT option does not allow variable length parameters,
6137          * hence a request cannot be NULL.
6138          */
6139         if (req == NULL)
6140                 return (EINVAL);
6141 
6142         ah_req = req->ipsr_ah_req;
6143         esp_req = req->ipsr_esp_req;
6144         se_req = req->ipsr_self_encap_req;
6145 
6146         /* Don't allow setting self-encap without one or more of AH/ESP. */
6147         if (se_req != 0 && esp_req == 0 && ah_req == 0)
6148                 return (EINVAL);
6149 
6150         /*
6151          * Are we dealing with a request to reset the policy (i.e.
6152          * zero requests).
6153          */
6154         is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6155             (esp_req & REQ_MASK) == 0 &&
6156             (se_req & REQ_MASK) == 0);
6157 
6158         if (!is_pol_reset) {
6159                 /*
6160                  * If we couldn't load IPsec, fail with "protocol
6161                  * not supported".
6162                  * IPsec may not have been loaded for a request with zero
6163                  * policies, so we don't fail in this case.
6164                  */
6165                 mutex_enter(&ipss->ipsec_loader_lock);
6166                 if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6167                         mutex_exit(&ipss->ipsec_loader_lock);
6168                         return (EPROTONOSUPPORT);
6169                 }
6170                 mutex_exit(&ipss->ipsec_loader_lock);
6171 
6172                 /*
6173                  * Test for valid requests. Invalid algorithms
6174                  * need to be tested by IPsec code because new
6175                  * algorithms can be added dynamically.
6176                  */
6177                 if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6178                     (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6179                     (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6180                         return (EINVAL);
6181                 }
6182 
6183                 /*
6184                  * Only privileged users can issue these
6185                  * requests.
6186                  */
6187                 if (((ah_req & IPSEC_PREF_NEVER) ||
6188                     (esp_req & IPSEC_PREF_NEVER) ||
6189                     (se_req & IPSEC_PREF_NEVER)) &&
6190                     secpolicy_ip_config(cr, B_FALSE) != 0) {
6191                         return (EPERM);
6192                 }
6193 
6194                 /*
6195                  * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6196                  * are mutually exclusive.
6197                  */
6198                 if (((ah_req & REQ_MASK) == REQ_MASK) ||
6199                     ((esp_req & REQ_MASK) == REQ_MASK) ||
6200                     ((se_req & REQ_MASK) == REQ_MASK)) {
6201                         /* Both of them are set */
6202                         return (EINVAL);
6203                 }
6204         }
6205 
6206         ASSERT(MUTEX_HELD(&connp->conn_lock));
6207 
6208         /*
6209          * If we have already cached policies in conn_connect(), don't
6210          * let them change now. We cache policies for connections
6211          * whose src,dst [addr, port] is known.
6212          */
6213         if (connp->conn_policy_cached) {
6214                 return (EINVAL);
6215         }
6216 
6217         /*
6218          * We have a zero policies, reset the connection policy if already
6219          * set. This will cause the connection to inherit the
6220          * global policy, if any.
6221          */
6222         if (is_pol_reset) {
6223                 if (connp->conn_policy != NULL) {
6224                         IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6225                         connp->conn_policy = NULL;
6226                 }
6227                 connp->conn_in_enforce_policy = B_FALSE;
6228                 connp->conn_out_enforce_policy = B_FALSE;
6229                 return (0);
6230         }
6231 
6232         ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6233             ipst->ips_netstack);
6234         if (ph == NULL)
6235                 goto enomem;
6236 
6237         ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6238         if (actp == NULL)
6239                 goto enomem;
6240 
6241         /*
6242          * Always insert IPv4 policy entries, since they can also apply to
6243          * ipv6 sockets being used in ipv4-compat mode.
6244          */
6245         if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6246             IPSEC_TYPE_INBOUND, ns))
6247                 goto enomem;
6248         is_pol_inserted = B_TRUE;
6249         if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6250             IPSEC_TYPE_OUTBOUND, ns))
6251                 goto enomem;
6252 
6253         /*
6254          * We're looking at a v6 socket, also insert the v6-specific
6255          * entries.
6256          */
6257         if (connp->conn_family == AF_INET6) {
6258                 if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6259                     IPSEC_TYPE_INBOUND, ns))
6260                         goto enomem;
6261                 if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6262                     IPSEC_TYPE_OUTBOUND, ns))
6263                         goto enomem;
6264         }
6265 
6266         ipsec_actvec_free(actp, nact);
6267 
6268         /*
6269          * If the requests need security, set enforce_policy.
6270          * If the requests are IPSEC_PREF_NEVER, one should
6271          * still set conn_out_enforce_policy so that ip_set_destination
6272          * marks the ip_xmit_attr_t appropriatly. This is needed so that
6273          * for connections that we don't cache policy in at connect time,
6274          * if global policy matches in ip_output_attach_policy, we
6275          * don't wrongly inherit global policy. Similarly, we need
6276          * to set conn_in_enforce_policy also so that we don't verify
6277          * policy wrongly.
6278          */
6279         if ((ah_req & REQ_MASK) != 0 ||
6280             (esp_req & REQ_MASK) != 0 ||
6281             (se_req & REQ_MASK) != 0) {
6282                 connp->conn_in_enforce_policy = B_TRUE;
6283                 connp->conn_out_enforce_policy = B_TRUE;
6284         }
6285 
6286         return (error);
6287 #undef REQ_MASK
6288 
6289         /*
6290          * Common memory-allocation-failure exit path.
6291          */
6292 enomem:
6293         if (actp != NULL)
6294                 ipsec_actvec_free(actp, nact);
6295         if (is_pol_inserted)
6296                 ipsec_polhead_flush(ph, ns);
6297         return (ENOMEM);
6298 }
6299 
6300 /*
6301  * Set socket options for joining and leaving multicast groups.
6302  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6303  * The caller has already check that the option name is consistent with
6304  * the address family of the socket.
6305  */
6306 int
6307 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6308     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6309 {
6310         int             *i1 = (int *)invalp;
6311         int             error = 0;
6312         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
6313         struct ip_mreq  *v4_mreqp;
6314         struct ipv6_mreq *v6_mreqp;
6315         struct group_req *greqp;
6316         ire_t *ire;
6317         boolean_t done = B_FALSE;
6318         ipaddr_t ifaddr;
6319         in6_addr_t v6group;
6320         uint_t ifindex;
6321         boolean_t mcast_opt = B_TRUE;
6322         mcast_record_t fmode;
6323         int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6324             ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6325 
6326         switch (name) {
6327         case IP_ADD_MEMBERSHIP:
6328         case IPV6_JOIN_GROUP:
6329                 mcast_opt = B_FALSE;
6330                 /* FALLTHRU */
6331         case MCAST_JOIN_GROUP:
6332                 fmode = MODE_IS_EXCLUDE;
6333                 optfn = ip_opt_add_group;
6334                 break;
6335 
6336         case IP_DROP_MEMBERSHIP:
6337         case IPV6_LEAVE_GROUP:
6338                 mcast_opt = B_FALSE;
6339                 /* FALLTHRU */
6340         case MCAST_LEAVE_GROUP:
6341                 fmode = MODE_IS_INCLUDE;
6342                 optfn = ip_opt_delete_group;
6343                 break;
6344         default:
6345                 ASSERT(0);
6346         }
6347 
6348         if (mcast_opt) {
6349                 struct sockaddr_in *sin;
6350                 struct sockaddr_in6 *sin6;
6351 
6352                 greqp = (struct group_req *)i1;
6353                 if (greqp->gr_group.ss_family == AF_INET) {
6354                         sin = (struct sockaddr_in *)&(greqp->gr_group);
6355                         IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6356                 } else {
6357                         if (!inet6)
6358                                 return (EINVAL);        /* Not on INET socket */
6359 
6360                         sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6361                         v6group = sin6->sin6_addr;
6362                 }
6363                 ifaddr = INADDR_ANY;
6364                 ifindex = greqp->gr_interface;
6365         } else if (inet6) {
6366                 v6_mreqp = (struct ipv6_mreq *)i1;
6367                 v6group = v6_mreqp->ipv6mr_multiaddr;
6368                 ifaddr = INADDR_ANY;
6369                 ifindex = v6_mreqp->ipv6mr_interface;
6370         } else {
6371                 v4_mreqp = (struct ip_mreq *)i1;
6372                 IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6373                 ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6374                 ifindex = 0;
6375         }
6376 
6377         /*
6378          * In the multirouting case, we need to replicate
6379          * the request on all interfaces that will take part
6380          * in replication.  We do so because multirouting is
6381          * reflective, thus we will probably receive multi-
6382          * casts on those interfaces.
6383          * The ip_multirt_apply_membership() succeeds if
6384          * the operation succeeds on at least one interface.
6385          */
6386         if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6387                 ipaddr_t group;
6388 
6389                 IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6390 
6391                 ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6392                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6393                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6394         } else {
6395                 ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6396                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6397                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6398         }
6399         if (ire != NULL) {
6400                 if (ire->ire_flags & RTF_MULTIRT) {
6401                         error = ip_multirt_apply_membership(optfn, ire, connp,
6402                             checkonly, &v6group, fmode, &ipv6_all_zeros);
6403                         done = B_TRUE;
6404                 }
6405                 ire_refrele(ire);
6406         }
6407 
6408         if (!done) {
6409                 error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6410                     fmode, &ipv6_all_zeros);
6411         }
6412         return (error);
6413 }
6414 
6415 /*
6416  * Set socket options for joining and leaving multicast groups
6417  * for specific sources.
6418  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6419  * The caller has already check that the option name is consistent with
6420  * the address family of the socket.
6421  */
6422 int
6423 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6424     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6425 {
6426         int             *i1 = (int *)invalp;
6427         int             error = 0;
6428         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
6429         struct ip_mreq_source *imreqp;
6430         struct group_source_req *gsreqp;
6431         in6_addr_t v6group, v6src;
6432         uint32_t ifindex;
6433         ipaddr_t ifaddr;
6434         boolean_t mcast_opt = B_TRUE;
6435         mcast_record_t fmode;
6436         ire_t *ire;
6437         boolean_t done = B_FALSE;
6438         int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6439             ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6440 
6441         switch (name) {
6442         case IP_BLOCK_SOURCE:
6443                 mcast_opt = B_FALSE;
6444                 /* FALLTHRU */
6445         case MCAST_BLOCK_SOURCE:
6446                 fmode = MODE_IS_EXCLUDE;
6447                 optfn = ip_opt_add_group;
6448                 break;
6449 
6450         case IP_UNBLOCK_SOURCE:
6451                 mcast_opt = B_FALSE;
6452                 /* FALLTHRU */
6453         case MCAST_UNBLOCK_SOURCE:
6454                 fmode = MODE_IS_EXCLUDE;
6455                 optfn = ip_opt_delete_group;
6456                 break;
6457 
6458         case IP_ADD_SOURCE_MEMBERSHIP:
6459                 mcast_opt = B_FALSE;
6460                 /* FALLTHRU */
6461         case MCAST_JOIN_SOURCE_GROUP:
6462                 fmode = MODE_IS_INCLUDE;
6463                 optfn = ip_opt_add_group;
6464                 break;
6465 
6466         case IP_DROP_SOURCE_MEMBERSHIP:
6467                 mcast_opt = B_FALSE;
6468                 /* FALLTHRU */
6469         case MCAST_LEAVE_SOURCE_GROUP:
6470                 fmode = MODE_IS_INCLUDE;
6471                 optfn = ip_opt_delete_group;
6472                 break;
6473         default:
6474                 ASSERT(0);
6475         }
6476 
6477         if (mcast_opt) {
6478                 gsreqp = (struct group_source_req *)i1;
6479                 ifindex = gsreqp->gsr_interface;
6480                 if (gsreqp->gsr_group.ss_family == AF_INET) {
6481                         struct sockaddr_in *s;
6482                         s = (struct sockaddr_in *)&gsreqp->gsr_group;
6483                         IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6484                         s = (struct sockaddr_in *)&gsreqp->gsr_source;
6485                         IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6486                 } else {
6487                         struct sockaddr_in6 *s6;
6488 
6489                         if (!inet6)
6490                                 return (EINVAL);        /* Not on INET socket */
6491 
6492                         s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6493                         v6group = s6->sin6_addr;
6494                         s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6495                         v6src = s6->sin6_addr;
6496                 }
6497                 ifaddr = INADDR_ANY;
6498         } else {
6499                 imreqp = (struct ip_mreq_source *)i1;
6500                 IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6501                 IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6502                 ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6503                 ifindex = 0;
6504         }
6505 
6506         /*
6507          * Handle src being mapped INADDR_ANY by changing it to unspecified.
6508          */
6509         if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6510                 v6src = ipv6_all_zeros;
6511 
6512         /*
6513          * In the multirouting case, we need to replicate
6514          * the request as noted in the mcast cases above.
6515          */
6516         if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6517                 ipaddr_t group;
6518 
6519                 IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6520 
6521                 ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6522                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6523                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6524         } else {
6525                 ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6526                     IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6527                     MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6528         }
6529         if (ire != NULL) {
6530                 if (ire->ire_flags & RTF_MULTIRT) {
6531                         error = ip_multirt_apply_membership(optfn, ire, connp,
6532                             checkonly, &v6group, fmode, &v6src);
6533                         done = B_TRUE;
6534                 }
6535                 ire_refrele(ire);
6536         }
6537         if (!done) {
6538                 error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6539                     fmode, &v6src);
6540         }
6541         return (error);
6542 }
6543 
6544 /*
6545  * Given a destination address and a pointer to where to put the information
6546  * this routine fills in the mtuinfo.
6547  * The socket must be connected.
6548  * For sctp conn_faddr is the primary address.
6549  */
6550 int
6551 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6552 {
6553         uint32_t        pmtu = IP_MAXPACKET;
6554         uint_t          scopeid;
6555 
6556         if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6557                 return (-1);
6558 
6559         /* In case we never sent or called ip_set_destination_v4/v6 */
6560         if (ixa->ixa_ire != NULL)
6561                 pmtu = ip_get_pmtu(ixa);
6562 
6563         if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6564                 scopeid = ixa->ixa_scopeid;
6565         else
6566                 scopeid = 0;
6567 
6568         bzero(mtuinfo, sizeof (*mtuinfo));
6569         mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6570         mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6571         mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6572         mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6573         mtuinfo->ip6m_mtu = pmtu;
6574 
6575         return (sizeof (struct ip6_mtuinfo));
6576 }
6577 
6578 /*
6579  * When the src multihoming is changed from weak to [strong, preferred]
6580  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6581  * and identify routes that were created by user-applications in the
6582  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6583  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6584  * is selected by finding an interface route for the gateway.
6585  */
6586 /* ARGSUSED */
6587 void
6588 ip_ire_rebind_walker(ire_t *ire, void *notused)
6589 {
6590         if (!ire->ire_unbound || ire->ire_ill != NULL)
6591                 return;
6592         ire_rebind(ire);
6593         ire_delete(ire);
6594 }
6595 
6596 /*
6597  * When the src multihoming is changed from  [strong, preferred] to weak,
6598  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6599  * set any entries that were created by user-applications in the unbound state
6600  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6601  */
6602 /* ARGSUSED */
6603 void
6604 ip_ire_unbind_walker(ire_t *ire, void *notused)
6605 {
6606         ire_t *new_ire;
6607 
6608         if (!ire->ire_unbound || ire->ire_ill == NULL)
6609                 return;
6610         if (ire->ire_ipversion == IPV6_VERSION) {
6611                 new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6612                     &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6613                     ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6614         } else {
6615                 new_ire = ire_create((uchar_t *)&ire->ire_addr,
6616                     (uchar_t *)&ire->ire_mask,
6617                     (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6618                     ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6619         }
6620         if (new_ire == NULL)
6621                 return;
6622         new_ire->ire_unbound = B_TRUE;
6623         /*
6624          * The bound ire must first be deleted so that we don't return
6625          * the existing one on the attempt to add the unbound new_ire.
6626          */
6627         ire_delete(ire);
6628         new_ire = ire_add(new_ire);
6629         if (new_ire != NULL)
6630                 ire_refrele(new_ire);
6631 }
6632 
6633 /*
6634  * When the settings of ip*_strict_src_multihoming tunables are changed,
6635  * all cached routes need to be recomputed. This recomputation needs to be
6636  * done when going from weaker to stronger modes so that the cached ire
6637  * for the connection does not violate the current ip*_strict_src_multihoming
6638  * setting. It also needs to be done when going from stronger to weaker modes,
6639  * so that we fall back to matching on the longest-matching-route (as opposed
6640  * to a shorter match that may have been selected in the strong mode
6641  * to satisfy src_multihoming settings).
6642  *
6643  * The cached ixa_ire entires for all conn_t entries are marked as
6644  * "verify" so that they will be recomputed for the next packet.
6645  */
6646 void
6647 conn_ire_revalidate(conn_t *connp, void *arg)
6648 {
6649         boolean_t isv6 = (boolean_t)arg;
6650 
6651         if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6652             (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6653                 return;
6654         connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6655 }
6656 
6657 /*
6658  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6659  * When an ipf is passed here for the first time, if
6660  * we already have in-order fragments on the queue, we convert from the fast-
6661  * path reassembly scheme to the hard-case scheme.  From then on, additional
6662  * fragments are reassembled here.  We keep track of the start and end offsets
6663  * of each piece, and the number of holes in the chain.  When the hole count
6664  * goes to zero, we are done!
6665  *
6666  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6667  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6668  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6669  * after the call to ip_reassemble().
6670  */
6671 int
6672 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6673     size_t msg_len)
6674 {
6675         uint_t  end;
6676         mblk_t  *next_mp;
6677         mblk_t  *mp1;
6678         uint_t  offset;
6679         boolean_t incr_dups = B_TRUE;
6680         boolean_t offset_zero_seen = B_FALSE;
6681         boolean_t pkt_boundary_checked = B_FALSE;
6682 
6683         /* If start == 0 then ipf_nf_hdr_len has to be set. */
6684         ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6685 
6686         /* Add in byte count */
6687         ipf->ipf_count += msg_len;
6688         if (ipf->ipf_end) {
6689                 /*
6690                  * We were part way through in-order reassembly, but now there
6691                  * is a hole.  We walk through messages already queued, and
6692                  * mark them for hard case reassembly.  We know that up till
6693                  * now they were in order starting from offset zero.
6694                  */
6695                 offset = 0;
6696                 for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6697                         IP_REASS_SET_START(mp1, offset);
6698                         if (offset == 0) {
6699                                 ASSERT(ipf->ipf_nf_hdr_len != 0);
6700                                 offset = -ipf->ipf_nf_hdr_len;
6701                         }
6702                         offset += mp1->b_wptr - mp1->b_rptr;
6703                         IP_REASS_SET_END(mp1, offset);
6704                 }
6705                 /* One hole at the end. */
6706                 ipf->ipf_hole_cnt = 1;
6707                 /* Brand it as a hard case, forever. */
6708                 ipf->ipf_end = 0;
6709         }
6710         /* Walk through all the new pieces. */
6711         do {
6712                 end = start + (mp->b_wptr - mp->b_rptr);
6713                 /*
6714                  * If start is 0, decrease 'end' only for the first mblk of
6715                  * the fragment. Otherwise 'end' can get wrong value in the
6716                  * second pass of the loop if first mblk is exactly the
6717                  * size of ipf_nf_hdr_len.
6718                  */
6719                 if (start == 0 && !offset_zero_seen) {
6720                         /* First segment */
6721                         ASSERT(ipf->ipf_nf_hdr_len != 0);
6722                         end -= ipf->ipf_nf_hdr_len;
6723                         offset_zero_seen = B_TRUE;
6724                 }
6725                 next_mp = mp->b_cont;
6726                 /*
6727                  * We are checking to see if there is any interesing data
6728                  * to process.  If there isn't and the mblk isn't the
6729                  * one which carries the unfragmentable header then we
6730                  * drop it.  It's possible to have just the unfragmentable
6731                  * header come through without any data.  That needs to be
6732                  * saved.
6733                  *
6734                  * If the assert at the top of this function holds then the
6735                  * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6736                  * is infrequently traveled enough that the test is left in
6737                  * to protect against future code changes which break that
6738                  * invariant.
6739                  */
6740                 if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6741                         /* Empty.  Blast it. */
6742                         IP_REASS_SET_START(mp, 0);
6743                         IP_REASS_SET_END(mp, 0);
6744                         /*
6745                          * If the ipf points to the mblk we are about to free,
6746                          * update ipf to point to the next mblk (or NULL
6747                          * if none).
6748                          */
6749                         if (ipf->ipf_mp->b_cont == mp)
6750                                 ipf->ipf_mp->b_cont = next_mp;
6751                         freeb(mp);
6752                         continue;
6753                 }
6754                 mp->b_cont = NULL;
6755                 IP_REASS_SET_START(mp, start);
6756                 IP_REASS_SET_END(mp, end);
6757                 if (!ipf->ipf_tail_mp) {
6758                         ipf->ipf_tail_mp = mp;
6759                         ipf->ipf_mp->b_cont = mp;
6760                         if (start == 0 || !more) {
6761                                 ipf->ipf_hole_cnt = 1;
6762                                 /*
6763                                  * if the first fragment comes in more than one
6764                                  * mblk, this loop will be executed for each
6765                                  * mblk. Need to adjust hole count so exiting
6766                                  * this routine will leave hole count at 1.
6767                                  */
6768                                 if (next_mp)
6769                                         ipf->ipf_hole_cnt++;
6770                         } else
6771                                 ipf->ipf_hole_cnt = 2;
6772                         continue;
6773                 } else if (ipf->ipf_last_frag_seen && !more &&
6774                     !pkt_boundary_checked) {
6775                         /*
6776                          * We check datagram boundary only if this fragment
6777                          * claims to be the last fragment and we have seen a
6778                          * last fragment in the past too. We do this only
6779                          * once for a given fragment.
6780                          *
6781                          * start cannot be 0 here as fragments with start=0
6782                          * and MF=0 gets handled as a complete packet. These
6783                          * fragments should not reach here.
6784                          */
6785 
6786                         if (start + msgdsize(mp) !=
6787                             IP_REASS_END(ipf->ipf_tail_mp)) {
6788                                 /*
6789                                  * We have two fragments both of which claim
6790                                  * to be the last fragment but gives conflicting
6791                                  * information about the whole datagram size.
6792                                  * Something fishy is going on. Drop the
6793                                  * fragment and free up the reassembly list.
6794                                  */
6795                                 return (IP_REASS_FAILED);
6796                         }
6797 
6798                         /*
6799                          * We shouldn't come to this code block again for this
6800                          * particular fragment.
6801                          */
6802                         pkt_boundary_checked = B_TRUE;
6803                 }
6804 
6805                 /* New stuff at or beyond tail? */
6806                 offset = IP_REASS_END(ipf->ipf_tail_mp);
6807                 if (start >= offset) {
6808                         if (ipf->ipf_last_frag_seen) {
6809                                 /* current fragment is beyond last fragment */
6810                                 return (IP_REASS_FAILED);
6811                         }
6812                         /* Link it on end. */
6813                         ipf->ipf_tail_mp->b_cont = mp;
6814                         ipf->ipf_tail_mp = mp;
6815                         if (more) {
6816                                 if (start != offset)
6817                                         ipf->ipf_hole_cnt++;
6818                         } else if (start == offset && next_mp == NULL)
6819                                         ipf->ipf_hole_cnt--;
6820                         continue;
6821                 }
6822                 mp1 = ipf->ipf_mp->b_cont;
6823                 offset = IP_REASS_START(mp1);
6824                 /* New stuff at the front? */
6825                 if (start < offset) {
6826                         if (start == 0) {
6827                                 if (end >= offset) {
6828                                         /* Nailed the hole at the begining. */
6829                                         ipf->ipf_hole_cnt--;
6830                                 }
6831                         } else if (end < offset) {
6832                                 /*
6833                                  * A hole, stuff, and a hole where there used
6834                                  * to be just a hole.
6835                                  */
6836                                 ipf->ipf_hole_cnt++;
6837                         }
6838                         mp->b_cont = mp1;
6839                         /* Check for overlap. */
6840                         while (end > offset) {
6841                                 if (end < IP_REASS_END(mp1)) {
6842                                         mp->b_wptr -= end - offset;
6843                                         IP_REASS_SET_END(mp, offset);
6844                                         BUMP_MIB(ill->ill_ip_mib,
6845                                             ipIfStatsReasmPartDups);
6846                                         break;
6847                                 }
6848                                 /* Did we cover another hole? */
6849                                 if ((mp1->b_cont &&
6850                                     IP_REASS_END(mp1) !=
6851                                     IP_REASS_START(mp1->b_cont) &&
6852                                     end >= IP_REASS_START(mp1->b_cont)) ||
6853                                     (!ipf->ipf_last_frag_seen && !more)) {
6854                                         ipf->ipf_hole_cnt--;
6855                                 }
6856                                 /* Clip out mp1. */
6857                                 if ((mp->b_cont = mp1->b_cont) == NULL) {
6858                                         /*
6859                                          * After clipping out mp1, this guy
6860                                          * is now hanging off the end.
6861                                          */
6862                                         ipf->ipf_tail_mp = mp;
6863                                 }
6864                                 IP_REASS_SET_START(mp1, 0);
6865                                 IP_REASS_SET_END(mp1, 0);
6866                                 /* Subtract byte count */
6867                                 ipf->ipf_count -= mp1->b_datap->db_lim -
6868                                     mp1->b_datap->db_base;
6869                                 freeb(mp1);
6870                                 BUMP_MIB(ill->ill_ip_mib,
6871                                     ipIfStatsReasmPartDups);
6872                                 mp1 = mp->b_cont;
6873                                 if (!mp1)
6874                                         break;
6875                                 offset = IP_REASS_START(mp1);
6876                         }
6877                         ipf->ipf_mp->b_cont = mp;
6878                         continue;
6879                 }
6880                 /*
6881                  * The new piece starts somewhere between the start of the head
6882                  * and before the end of the tail.
6883                  */
6884                 for (; mp1; mp1 = mp1->b_cont) {
6885                         offset = IP_REASS_END(mp1);
6886                         if (start < offset) {
6887                                 if (end <= offset) {
6888                                         /* Nothing new. */
6889                                         IP_REASS_SET_START(mp, 0);
6890                                         IP_REASS_SET_END(mp, 0);
6891                                         /* Subtract byte count */
6892                                         ipf->ipf_count -= mp->b_datap->db_lim -
6893                                             mp->b_datap->db_base;
6894                                         if (incr_dups) {
6895                                                 ipf->ipf_num_dups++;
6896                                                 incr_dups = B_FALSE;
6897                                         }
6898                                         freeb(mp);
6899                                         BUMP_MIB(ill->ill_ip_mib,
6900                                             ipIfStatsReasmDuplicates);
6901                                         break;
6902                                 }
6903                                 /*
6904                                  * Trim redundant stuff off beginning of new
6905                                  * piece.
6906                                  */
6907                                 IP_REASS_SET_START(mp, offset);
6908                                 mp->b_rptr += offset - start;
6909                                 BUMP_MIB(ill->ill_ip_mib,
6910                                     ipIfStatsReasmPartDups);
6911                                 start = offset;
6912                                 if (!mp1->b_cont) {
6913                                         /*
6914                                          * After trimming, this guy is now
6915                                          * hanging off the end.
6916                                          */
6917                                         mp1->b_cont = mp;
6918                                         ipf->ipf_tail_mp = mp;
6919                                         if (!more) {
6920                                                 ipf->ipf_hole_cnt--;
6921                                         }
6922                                         break;
6923                                 }
6924                         }
6925                         if (start >= IP_REASS_START(mp1->b_cont))
6926                                 continue;
6927                         /* Fill a hole */
6928                         if (start > offset)
6929                                 ipf->ipf_hole_cnt++;
6930                         mp->b_cont = mp1->b_cont;
6931                         mp1->b_cont = mp;
6932                         mp1 = mp->b_cont;
6933                         offset = IP_REASS_START(mp1);
6934                         if (end >= offset) {
6935                                 ipf->ipf_hole_cnt--;
6936                                 /* Check for overlap. */
6937                                 while (end > offset) {
6938                                         if (end < IP_REASS_END(mp1)) {
6939                                                 mp->b_wptr -= end - offset;
6940                                                 IP_REASS_SET_END(mp, offset);
6941                                                 /*
6942                                                  * TODO we might bump
6943                                                  * this up twice if there is
6944                                                  * overlap at both ends.
6945                                                  */
6946                                                 BUMP_MIB(ill->ill_ip_mib,
6947                                                     ipIfStatsReasmPartDups);
6948                                                 break;
6949                                         }
6950                                         /* Did we cover another hole? */
6951                                         if ((mp1->b_cont &&
6952                                             IP_REASS_END(mp1)
6953                                             != IP_REASS_START(mp1->b_cont) &&
6954                                             end >=
6955                                             IP_REASS_START(mp1->b_cont)) ||
6956                                             (!ipf->ipf_last_frag_seen &&
6957                                             !more)) {
6958                                                 ipf->ipf_hole_cnt--;
6959                                         }
6960                                         /* Clip out mp1. */
6961                                         if ((mp->b_cont = mp1->b_cont) ==
6962                                             NULL) {
6963                                                 /*
6964                                                  * After clipping out mp1,
6965                                                  * this guy is now hanging
6966                                                  * off the end.
6967                                                  */
6968                                                 ipf->ipf_tail_mp = mp;
6969                                         }
6970                                         IP_REASS_SET_START(mp1, 0);
6971                                         IP_REASS_SET_END(mp1, 0);
6972                                         /* Subtract byte count */
6973                                         ipf->ipf_count -=
6974                                             mp1->b_datap->db_lim -
6975                                             mp1->b_datap->db_base;
6976                                         freeb(mp1);
6977                                         BUMP_MIB(ill->ill_ip_mib,
6978                                             ipIfStatsReasmPartDups);
6979                                         mp1 = mp->b_cont;
6980                                         if (!mp1)
6981                                                 break;
6982                                         offset = IP_REASS_START(mp1);
6983                                 }
6984                         }
6985                         break;
6986                 }
6987         } while (start = end, mp = next_mp);
6988 
6989         /* Fragment just processed could be the last one. Remember this fact */
6990         if (!more)
6991                 ipf->ipf_last_frag_seen = B_TRUE;
6992 
6993         /* Still got holes? */
6994         if (ipf->ipf_hole_cnt)
6995                 return (IP_REASS_PARTIAL);
6996         /* Clean up overloaded fields to avoid upstream disasters. */
6997         for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6998                 IP_REASS_SET_START(mp1, 0);
6999                 IP_REASS_SET_END(mp1, 0);
7000         }
7001         return (IP_REASS_COMPLETE);
7002 }
7003 
7004 /*
7005  * Fragmentation reassembly.  Each ILL has a hash table for
7006  * queuing packets undergoing reassembly for all IPIFs
7007  * associated with the ILL.  The hash is based on the packet
7008  * IP ident field.  The ILL frag hash table was allocated
7009  * as a timer block at the time the ILL was created.  Whenever
7010  * there is anything on the reassembly queue, the timer will
7011  * be running.  Returns the reassembled packet if reassembly completes.
7012  */
7013 mblk_t *
7014 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7015 {
7016         uint32_t        frag_offset_flags;
7017         mblk_t          *t_mp;
7018         ipaddr_t        dst;
7019         uint8_t         proto = ipha->ipha_protocol;
7020         uint32_t        sum_val;
7021         uint16_t        sum_flags;
7022         ipf_t           *ipf;
7023         ipf_t           **ipfp;
7024         ipfb_t          *ipfb;
7025         uint16_t        ident;
7026         uint32_t        offset;
7027         ipaddr_t        src;
7028         uint_t          hdr_length;
7029         uint32_t        end;
7030         mblk_t          *mp1;
7031         mblk_t          *tail_mp;
7032         size_t          count;
7033         size_t          msg_len;
7034         uint8_t         ecn_info = 0;
7035         uint32_t        packet_size;
7036         boolean_t       pruned = B_FALSE;
7037         ill_t           *ill = ira->ira_ill;
7038         ip_stack_t      *ipst = ill->ill_ipst;
7039 
7040         /*
7041          * Drop the fragmented as early as possible, if
7042          * we don't have resource(s) to re-assemble.
7043          */
7044         if (ipst->ips_ip_reass_queue_bytes == 0) {
7045                 freemsg(mp);
7046                 return (NULL);
7047         }
7048 
7049         /* Check for fragmentation offset; return if there's none */
7050         if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7051             (IPH_MF | IPH_OFFSET)) == 0)
7052                 return (mp);
7053 
7054         /*
7055          * We utilize hardware computed checksum info only for UDP since
7056          * IP fragmentation is a normal occurrence for the protocol.  In
7057          * addition, checksum offload support for IP fragments carrying
7058          * UDP payload is commonly implemented across network adapters.
7059          */
7060         ASSERT(ira->ira_rill != NULL);
7061         if (proto == IPPROTO_UDP && dohwcksum &&
7062             ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7063             (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7064                 mblk_t *mp1 = mp->b_cont;
7065                 int32_t len;
7066 
7067                 /* Record checksum information from the packet */
7068                 sum_val = (uint32_t)DB_CKSUM16(mp);
7069                 sum_flags = DB_CKSUMFLAGS(mp);
7070 
7071                 /* IP payload offset from beginning of mblk */
7072                 offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7073 
7074                 if ((sum_flags & HCK_PARTIALCKSUM) &&
7075                     (mp1 == NULL || mp1->b_cont == NULL) &&
7076                     offset >= DB_CKSUMSTART(mp) &&
7077                     ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7078                         uint32_t adj;
7079                         /*
7080                          * Partial checksum has been calculated by hardware
7081                          * and attached to the packet; in addition, any
7082                          * prepended extraneous data is even byte aligned.
7083                          * If any such data exists, we adjust the checksum;
7084                          * this would also handle any postpended data.
7085                          */
7086                         IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7087                             mp, mp1, len, adj);
7088 
7089                         /* One's complement subtract extraneous checksum */
7090                         if (adj >= sum_val)
7091                                 sum_val = ~(adj - sum_val) & 0xFFFF;
7092                         else
7093                                 sum_val -= adj;
7094                 }
7095         } else {
7096                 sum_val = 0;
7097                 sum_flags = 0;
7098         }
7099 
7100         /* Clear hardware checksumming flag */
7101         DB_CKSUMFLAGS(mp) = 0;
7102 
7103         ident = ipha->ipha_ident;
7104         offset = (frag_offset_flags << 3) & 0xFFFF;
7105         src = ipha->ipha_src;
7106         dst = ipha->ipha_dst;
7107         hdr_length = IPH_HDR_LENGTH(ipha);
7108         end = ntohs(ipha->ipha_length) - hdr_length;
7109 
7110         /* If end == 0 then we have a packet with no data, so just free it */
7111         if (end == 0) {
7112                 freemsg(mp);
7113                 return (NULL);
7114         }
7115 
7116         /* Record the ECN field info. */
7117         ecn_info = (ipha->ipha_type_of_service & 0x3);
7118         if (offset != 0) {
7119                 /*
7120                  * If this isn't the first piece, strip the header, and
7121                  * add the offset to the end value.
7122                  */
7123                 mp->b_rptr += hdr_length;
7124                 end += offset;
7125         }
7126 
7127         /* Handle vnic loopback of fragments */
7128         if (mp->b_datap->db_ref > 2)
7129                 msg_len = 0;
7130         else
7131                 msg_len = MBLKSIZE(mp);
7132 
7133         tail_mp = mp;
7134         while (tail_mp->b_cont != NULL) {
7135                 tail_mp = tail_mp->b_cont;
7136                 if (tail_mp->b_datap->db_ref <= 2)
7137                         msg_len += MBLKSIZE(tail_mp);
7138         }
7139 
7140         /* If the reassembly list for this ILL will get too big, prune it */
7141         if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7142             ipst->ips_ip_reass_queue_bytes) {
7143                 DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7144                     uint_t, ill->ill_frag_count,
7145                     uint_t, ipst->ips_ip_reass_queue_bytes);
7146                 ill_frag_prune(ill,
7147                     (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7148                     (ipst->ips_ip_reass_queue_bytes - msg_len));
7149                 pruned = B_TRUE;
7150         }
7151 
7152         ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7153         mutex_enter(&ipfb->ipfb_lock);
7154 
7155         ipfp = &ipfb->ipfb_ipf;
7156         /* Try to find an existing fragment queue for this packet. */
7157         for (;;) {
7158                 ipf = ipfp[0];
7159                 if (ipf != NULL) {
7160                         /*
7161                          * It has to match on ident and src/dst address.
7162                          */
7163                         if (ipf->ipf_ident == ident &&
7164                             ipf->ipf_src == src &&
7165                             ipf->ipf_dst == dst &&
7166                             ipf->ipf_protocol == proto) {
7167                                 /*
7168                                  * If we have received too many
7169                                  * duplicate fragments for this packet
7170                                  * free it.
7171                                  */
7172                                 if (ipf->ipf_num_dups > ip_max_frag_dups) {
7173                                         ill_frag_free_pkts(ill, ipfb, ipf, 1);
7174                                         freemsg(mp);
7175                                         mutex_exit(&ipfb->ipfb_lock);
7176                                         return (NULL);
7177                                 }
7178                                 /* Found it. */
7179                                 break;
7180                         }
7181                         ipfp = &ipf->ipf_hash_next;
7182                         continue;
7183                 }
7184 
7185                 /*
7186                  * If we pruned the list, do we want to store this new
7187                  * fragment?. We apply an optimization here based on the
7188                  * fact that most fragments will be received in order.
7189                  * So if the offset of this incoming fragment is zero,
7190                  * it is the first fragment of a new packet. We will
7191                  * keep it.  Otherwise drop the fragment, as we have
7192                  * probably pruned the packet already (since the
7193                  * packet cannot be found).
7194                  */
7195                 if (pruned && offset != 0) {
7196                         mutex_exit(&ipfb->ipfb_lock);
7197                         freemsg(mp);
7198                         return (NULL);
7199                 }
7200 
7201                 if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7202                         /*
7203                          * Too many fragmented packets in this hash
7204                          * bucket. Free the oldest.
7205                          */
7206                         ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7207                 }
7208 
7209                 /* New guy.  Allocate a frag message. */
7210                 mp1 = allocb(sizeof (*ipf), BPRI_MED);
7211                 if (mp1 == NULL) {
7212                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7213                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7214                         freemsg(mp);
7215 reass_done:
7216                         mutex_exit(&ipfb->ipfb_lock);
7217                         return (NULL);
7218                 }
7219 
7220                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7221                 mp1->b_cont = mp;
7222 
7223                 /* Initialize the fragment header. */
7224                 ipf = (ipf_t *)mp1->b_rptr;
7225                 ipf->ipf_mp = mp1;
7226                 ipf->ipf_ptphn = ipfp;
7227                 ipfp[0] = ipf;
7228                 ipf->ipf_hash_next = NULL;
7229                 ipf->ipf_ident = ident;
7230                 ipf->ipf_protocol = proto;
7231                 ipf->ipf_src = src;
7232                 ipf->ipf_dst = dst;
7233                 ipf->ipf_nf_hdr_len = 0;
7234                 /* Record reassembly start time. */
7235                 ipf->ipf_timestamp = gethrestime_sec();
7236                 /* Record ipf generation and account for frag header */
7237                 ipf->ipf_gen = ill->ill_ipf_gen++;
7238                 ipf->ipf_count = MBLKSIZE(mp1);
7239                 ipf->ipf_last_frag_seen = B_FALSE;
7240                 ipf->ipf_ecn = ecn_info;
7241                 ipf->ipf_num_dups = 0;
7242                 ipfb->ipfb_frag_pkts++;
7243                 ipf->ipf_checksum = 0;
7244                 ipf->ipf_checksum_flags = 0;
7245 
7246                 /* Store checksum value in fragment header */
7247                 if (sum_flags != 0) {
7248                         sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7249                         sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7250                         ipf->ipf_checksum = sum_val;
7251                         ipf->ipf_checksum_flags = sum_flags;
7252                 }
7253 
7254                 /*
7255                  * We handle reassembly two ways.  In the easy case,
7256                  * where all the fragments show up in order, we do
7257                  * minimal bookkeeping, and just clip new pieces on
7258                  * the end.  If we ever see a hole, then we go off
7259                  * to ip_reassemble which has to mark the pieces and
7260                  * keep track of the number of holes, etc.  Obviously,
7261                  * the point of having both mechanisms is so we can
7262                  * handle the easy case as efficiently as possible.
7263                  */
7264                 if (offset == 0) {
7265                         /* Easy case, in-order reassembly so far. */
7266                         ipf->ipf_count += msg_len;
7267                         ipf->ipf_tail_mp = tail_mp;
7268                         /*
7269                          * Keep track of next expected offset in
7270                          * ipf_end.
7271                          */
7272                         ipf->ipf_end = end;
7273                         ipf->ipf_nf_hdr_len = hdr_length;
7274                 } else {
7275                         /* Hard case, hole at the beginning. */
7276                         ipf->ipf_tail_mp = NULL;
7277                         /*
7278                          * ipf_end == 0 means that we have given up
7279                          * on easy reassembly.
7280                          */
7281                         ipf->ipf_end = 0;
7282 
7283                         /* Forget checksum offload from now on */
7284                         ipf->ipf_checksum_flags = 0;
7285 
7286                         /*
7287                          * ipf_hole_cnt is set by ip_reassemble.
7288                          * ipf_count is updated by ip_reassemble.
7289                          * No need to check for return value here
7290                          * as we don't expect reassembly to complete
7291                          * or fail for the first fragment itself.
7292                          */
7293                         (void) ip_reassemble(mp, ipf,
7294                             (frag_offset_flags & IPH_OFFSET) << 3,
7295                             (frag_offset_flags & IPH_MF), ill, msg_len);
7296                 }
7297                 /* Update per ipfb and ill byte counts */
7298                 ipfb->ipfb_count += ipf->ipf_count;
7299                 ASSERT(ipfb->ipfb_count > 0);     /* Wraparound */
7300                 atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7301                 /* If the frag timer wasn't already going, start it. */
7302                 mutex_enter(&ill->ill_lock);
7303                 ill_frag_timer_start(ill);
7304                 mutex_exit(&ill->ill_lock);
7305                 goto reass_done;
7306         }
7307 
7308         /*
7309          * If the packet's flag has changed (it could be coming up
7310          * from an interface different than the previous, therefore
7311          * possibly different checksum capability), then forget about
7312          * any stored checksum states.  Otherwise add the value to
7313          * the existing one stored in the fragment header.
7314          */
7315         if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7316                 sum_val += ipf->ipf_checksum;
7317                 sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7318                 sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7319                 ipf->ipf_checksum = sum_val;
7320         } else if (ipf->ipf_checksum_flags != 0) {
7321                 /* Forget checksum offload from now on */
7322                 ipf->ipf_checksum_flags = 0;
7323         }
7324 
7325         /*
7326          * We have a new piece of a datagram which is already being
7327          * reassembled.  Update the ECN info if all IP fragments
7328          * are ECN capable.  If there is one which is not, clear
7329          * all the info.  If there is at least one which has CE
7330          * code point, IP needs to report that up to transport.
7331          */
7332         if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7333                 if (ecn_info == IPH_ECN_CE)
7334                         ipf->ipf_ecn = IPH_ECN_CE;
7335         } else {
7336                 ipf->ipf_ecn = IPH_ECN_NECT;
7337         }
7338         if (offset && ipf->ipf_end == offset) {
7339                 /* The new fragment fits at the end */
7340                 ipf->ipf_tail_mp->b_cont = mp;
7341                 /* Update the byte count */
7342                 ipf->ipf_count += msg_len;
7343                 /* Update per ipfb and ill byte counts */
7344                 ipfb->ipfb_count += msg_len;
7345                 ASSERT(ipfb->ipfb_count > 0);     /* Wraparound */
7346                 atomic_add_32(&ill->ill_frag_count, msg_len);
7347                 if (frag_offset_flags & IPH_MF) {
7348                         /* More to come. */
7349                         ipf->ipf_end = end;
7350                         ipf->ipf_tail_mp = tail_mp;
7351                         goto reass_done;
7352                 }
7353         } else {
7354                 /* Go do the hard cases. */
7355                 int ret;
7356 
7357                 if (offset == 0)
7358                         ipf->ipf_nf_hdr_len = hdr_length;
7359 
7360                 /* Save current byte count */
7361                 count = ipf->ipf_count;
7362                 ret = ip_reassemble(mp, ipf,
7363                     (frag_offset_flags & IPH_OFFSET) << 3,
7364                     (frag_offset_flags & IPH_MF), ill, msg_len);
7365                 /* Count of bytes added and subtracted (freeb()ed) */
7366                 count = ipf->ipf_count - count;
7367                 if (count) {
7368                         /* Update per ipfb and ill byte counts */
7369                         ipfb->ipfb_count += count;
7370                         ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7371                         atomic_add_32(&ill->ill_frag_count, count);
7372                 }
7373                 if (ret == IP_REASS_PARTIAL) {
7374                         goto reass_done;
7375                 } else if (ret == IP_REASS_FAILED) {
7376                         /* Reassembly failed. Free up all resources */
7377                         ill_frag_free_pkts(ill, ipfb, ipf, 1);
7378                         for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7379                                 IP_REASS_SET_START(t_mp, 0);
7380                                 IP_REASS_SET_END(t_mp, 0);
7381                         }
7382                         freemsg(mp);
7383                         goto reass_done;
7384                 }
7385                 /* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7386         }
7387         /*
7388          * We have completed reassembly.  Unhook the frag header from
7389          * the reassembly list.
7390          *
7391          * Before we free the frag header, record the ECN info
7392          * to report back to the transport.
7393          */
7394         ecn_info = ipf->ipf_ecn;
7395         BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7396         ipfp = ipf->ipf_ptphn;
7397 
7398         /* We need to supply these to caller */
7399         if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7400                 sum_val = ipf->ipf_checksum;
7401         else
7402                 sum_val = 0;
7403 
7404         mp1 = ipf->ipf_mp;
7405         count = ipf->ipf_count;
7406         ipf = ipf->ipf_hash_next;
7407         if (ipf != NULL)
7408                 ipf->ipf_ptphn = ipfp;
7409         ipfp[0] = ipf;
7410         atomic_add_32(&ill->ill_frag_count, -count);
7411         ASSERT(ipfb->ipfb_count >= count);
7412         ipfb->ipfb_count -= count;
7413         ipfb->ipfb_frag_pkts--;
7414         mutex_exit(&ipfb->ipfb_lock);
7415         /* Ditch the frag header. */
7416         mp = mp1->b_cont;
7417 
7418         freeb(mp1);
7419 
7420         /* Restore original IP length in header. */
7421         packet_size = (uint32_t)msgdsize(mp);
7422         if (packet_size > IP_MAXPACKET) {
7423                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7424                 ip_drop_input("Reassembled packet too large", mp, ill);
7425                 freemsg(mp);
7426                 return (NULL);
7427         }
7428 
7429         if (DB_REF(mp) > 1) {
7430                 mblk_t *mp2 = copymsg(mp);
7431 
7432                 if (mp2 == NULL) {
7433                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7434                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7435                         freemsg(mp);
7436                         return (NULL);
7437                 }
7438                 freemsg(mp);
7439                 mp = mp2;
7440         }
7441         ipha = (ipha_t *)mp->b_rptr;
7442 
7443         ipha->ipha_length = htons((uint16_t)packet_size);
7444         /* We're now complete, zip the frag state */
7445         ipha->ipha_fragment_offset_and_flags = 0;
7446         /* Record the ECN info. */
7447         ipha->ipha_type_of_service &= 0xFC;
7448         ipha->ipha_type_of_service |= ecn_info;
7449 
7450         /* Update the receive attributes */
7451         ira->ira_pktlen = packet_size;
7452         ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7453 
7454         /* Reassembly is successful; set checksum information in packet */
7455         DB_CKSUM16(mp) = (uint16_t)sum_val;
7456         DB_CKSUMFLAGS(mp) = sum_flags;
7457         DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7458 
7459         return (mp);
7460 }
7461 
7462 /*
7463  * Pullup function that should be used for IP input in order to
7464  * ensure we do not loose the L2 source address; we need the l2 source
7465  * address for IP_RECVSLLA and for ndp_input.
7466  *
7467  * We return either NULL or b_rptr.
7468  */
7469 void *
7470 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7471 {
7472         ill_t           *ill = ira->ira_ill;
7473 
7474         if (ip_rput_pullups++ == 0) {
7475                 (void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7476                     "ip_pullup: %s forced us to "
7477                     " pullup pkt, hdr len %ld, hdr addr %p",
7478                     ill->ill_name, len, (void *)mp->b_rptr);
7479         }
7480         if (!(ira->ira_flags & IRAF_L2SRC_SET))
7481                 ip_setl2src(mp, ira, ira->ira_rill);
7482         ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7483         if (!pullupmsg(mp, len))
7484                 return (NULL);
7485         else
7486                 return (mp->b_rptr);
7487 }
7488 
7489 /*
7490  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7491  * When called from the ULP ira_rill will be NULL hence the caller has to
7492  * pass in the ill.
7493  */
7494 /* ARGSUSED */
7495 void
7496 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7497 {
7498         const uchar_t *addr;
7499         int alen;
7500 
7501         if (ira->ira_flags & IRAF_L2SRC_SET)
7502                 return;
7503 
7504         ASSERT(ill != NULL);
7505         alen = ill->ill_phys_addr_length;
7506         ASSERT(alen <= sizeof (ira->ira_l2src));
7507         if (ira->ira_mhip != NULL &&
7508             (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7509                 bcopy(addr, ira->ira_l2src, alen);
7510         } else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7511             (addr = ill->ill_phys_addr) != NULL) {
7512                 bcopy(addr, ira->ira_l2src, alen);
7513         } else {
7514                 bzero(ira->ira_l2src, alen);
7515         }
7516         ira->ira_flags |= IRAF_L2SRC_SET;
7517 }
7518 
7519 /*
7520  * check ip header length and align it.
7521  */
7522 mblk_t *
7523 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7524 {
7525         ill_t   *ill = ira->ira_ill;
7526         ssize_t len;
7527 
7528         len = MBLKL(mp);
7529 
7530         if (!OK_32PTR(mp->b_rptr))
7531                 IP_STAT(ill->ill_ipst, ip_notaligned);
7532         else
7533                 IP_STAT(ill->ill_ipst, ip_recv_pullup);
7534 
7535         /* Guard against bogus device drivers */
7536         if (len < 0) {
7537                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7538                 ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7539                 freemsg(mp);
7540                 return (NULL);
7541         }
7542 
7543         if (len == 0) {
7544                 /* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7545                 mblk_t *mp1 = mp->b_cont;
7546 
7547                 if (!(ira->ira_flags & IRAF_L2SRC_SET))
7548                         ip_setl2src(mp, ira, ira->ira_rill);
7549                 ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7550 
7551                 freeb(mp);
7552                 mp = mp1;
7553                 if (mp == NULL)
7554                         return (NULL);
7555 
7556                 if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7557                         return (mp);
7558         }
7559         if (ip_pullup(mp, min_size, ira) == NULL) {
7560                 if (msgdsize(mp) < min_size) {
7561                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7562                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7563                 } else {
7564                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7565                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7566                 }
7567                 freemsg(mp);
7568                 return (NULL);
7569         }
7570         return (mp);
7571 }
7572 
7573 /*
7574  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7575  */
7576 mblk_t *
7577 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len, uint_t pkt_len,
7578     uint_t min_size, ip_recv_attr_t *ira)
7579 {
7580         ill_t   *ill = ira->ira_ill;
7581 
7582         /*
7583          * Make sure we have data length consistent
7584          * with the IP header.
7585          */
7586         if (mp->b_cont == NULL) {
7587                 /* pkt_len is based on ipha_len, not the mblk length */
7588                 if (pkt_len < min_size) {
7589                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7590                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7591                         freemsg(mp);
7592                         return (NULL);
7593                 }
7594                 if (len < 0) {
7595                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7596                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7597                         freemsg(mp);
7598                         return (NULL);
7599                 }
7600                 /* Drop any pad */
7601                 mp->b_wptr = rptr + pkt_len;
7602         } else if ((len += msgdsize(mp->b_cont)) != 0) {
7603                 ASSERT(pkt_len >= min_size);
7604                 if (pkt_len < min_size) {
7605                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7606                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7607                         freemsg(mp);
7608                         return (NULL);
7609                 }
7610                 if (len < 0) {
7611                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7612                         ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7613                         freemsg(mp);
7614                         return (NULL);
7615                 }
7616                 /* Drop any pad */
7617                 (void) adjmsg(mp, -len);
7618                 /*
7619                  * adjmsg may have freed an mblk from the chain, hence
7620                  * invalidate any hw checksum here. This will force IP to
7621                  * calculate the checksum in sw, but only for this packet.
7622                  */
7623                 DB_CKSUMFLAGS(mp) = 0;
7624                 IP_STAT(ill->ill_ipst, ip_multimblk);
7625         }
7626         return (mp);
7627 }
7628 
7629 /*
7630  * Check that the IPv4 opt_len is consistent with the packet and pullup
7631  * the options.
7632  */
7633 mblk_t *
7634 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7635     ip_recv_attr_t *ira)
7636 {
7637         ill_t   *ill = ira->ira_ill;
7638         ssize_t len;
7639 
7640         /* Assume no IPv6 packets arrive over the IPv4 queue */
7641         if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7642                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7643                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7644                 ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7645                 freemsg(mp);
7646                 return (NULL);
7647         }
7648 
7649         if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7650                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7651                 ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7652                 freemsg(mp);
7653                 return (NULL);
7654         }
7655         /*
7656          * Recompute complete header length and make sure we
7657          * have access to all of it.
7658          */
7659         len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7660         if (len > (mp->b_wptr - mp->b_rptr)) {
7661                 if (len > pkt_len) {
7662                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7663                         ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7664                         freemsg(mp);
7665                         return (NULL);
7666                 }
7667                 if (ip_pullup(mp, len, ira) == NULL) {
7668                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7669                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
7670                         freemsg(mp);
7671                         return (NULL);
7672                 }
7673         }
7674         return (mp);
7675 }
7676 
7677 /*
7678  * Returns a new ire, or the same ire, or NULL.
7679  * If a different IRE is returned, then it is held; the caller
7680  * needs to release it.
7681  * In no case is there any hold/release on the ire argument.
7682  */
7683 ire_t *
7684 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7685 {
7686         ire_t           *new_ire;
7687         ill_t           *ire_ill;
7688         uint_t          ifindex;
7689         ip_stack_t      *ipst = ill->ill_ipst;
7690         boolean_t       strict_check = B_FALSE;
7691 
7692         /*
7693          * IPMP common case: if IRE and ILL are in the same group, there's no
7694          * issue (e.g. packet received on an underlying interface matched an
7695          * IRE_LOCAL on its associated group interface).
7696          */
7697         ASSERT(ire->ire_ill != NULL);
7698         if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7699                 return (ire);
7700 
7701         /*
7702          * Do another ire lookup here, using the ingress ill, to see if the
7703          * interface is in a usesrc group.
7704          * As long as the ills belong to the same group, we don't consider
7705          * them to be arriving on the wrong interface. Thus, if the switch
7706          * is doing inbound load spreading, we won't drop packets when the
7707          * ip*_strict_dst_multihoming switch is on.
7708          * We also need to check for IPIF_UNNUMBERED point2point interfaces
7709          * where the local address may not be unique. In this case we were
7710          * at the mercy of the initial ire lookup and the IRE_LOCAL it
7711          * actually returned. The new lookup, which is more specific, should
7712          * only find the IRE_LOCAL associated with the ingress ill if one
7713          * exists.
7714          */
7715         if (ire->ire_ipversion == IPV4_VERSION) {
7716                 if (ipst->ips_ip_strict_dst_multihoming)
7717                         strict_check = B_TRUE;
7718                 new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7719                     IRE_LOCAL, ill, ALL_ZONES, NULL,
7720                     (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7721         } else {
7722                 ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7723                 if (ipst->ips_ipv6_strict_dst_multihoming)
7724                         strict_check = B_TRUE;
7725                 new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7726                     IRE_LOCAL, ill, ALL_ZONES, NULL,
7727                     (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7728         }
7729         /*
7730          * If the same ire that was returned in ip_input() is found then this
7731          * is an indication that usesrc groups are in use. The packet
7732          * arrived on a different ill in the group than the one associated with
7733          * the destination address.  If a different ire was found then the same
7734          * IP address must be hosted on multiple ills. This is possible with
7735          * unnumbered point2point interfaces. We switch to use this new ire in
7736          * order to have accurate interface statistics.
7737          */
7738         if (new_ire != NULL) {
7739                 /* Note: held in one case but not the other? Caller handles */
7740                 if (new_ire != ire)
7741                         return (new_ire);
7742                 /* Unchanged */
7743                 ire_refrele(new_ire);
7744                 return (ire);
7745         }
7746 
7747         /*
7748          * Chase pointers once and store locally.
7749          */
7750         ASSERT(ire->ire_ill != NULL);
7751         ire_ill = ire->ire_ill;
7752         ifindex = ill->ill_usesrc_ifindex;
7753 
7754         /*
7755          * Check if it's a legal address on the 'usesrc' interface.
7756          * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7757          * can just check phyint_ifindex.
7758          */
7759         if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7760                 return (ire);
7761         }
7762 
7763         /*
7764          * If the ip*_strict_dst_multihoming switch is on then we can
7765          * only accept this packet if the interface is marked as routing.
7766          */
7767         if (!(strict_check))
7768                 return (ire);
7769 
7770         if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7771                 return (ire);
7772         }
7773         return (NULL);
7774 }
7775 
7776 /*
7777  * This function is used to construct a mac_header_info_s from a
7778  * DL_UNITDATA_IND message.
7779  * The address fields in the mhi structure points into the message,
7780  * thus the caller can't use those fields after freeing the message.
7781  *
7782  * We determine whether the packet received is a non-unicast packet
7783  * and in doing so, determine whether or not it is broadcast vs multicast.
7784  * For it to be a broadcast packet, we must have the appropriate mblk_t
7785  * hanging off the ill_t.  If this is either not present or doesn't match
7786  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7787  * to be multicast.  Thus NICs that have no broadcast address (or no
7788  * capability for one, such as point to point links) cannot return as
7789  * the packet being broadcast.
7790  */
7791 void
7792 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7793 {
7794         dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7795         mblk_t *bmp;
7796         uint_t extra_offset;
7797 
7798         bzero(mhip, sizeof (struct mac_header_info_s));
7799 
7800         mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7801 
7802         if (ill->ill_sap_length < 0)
7803                 extra_offset = 0;
7804         else
7805                 extra_offset = ill->ill_sap_length;
7806 
7807         mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7808             extra_offset;
7809         mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7810             extra_offset;
7811 
7812         if (!ind->dl_group_address)
7813                 return;
7814 
7815         /* Multicast or broadcast */
7816         mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7817 
7818         if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7819             ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7820             (bmp = ill->ill_bcast_mp) != NULL) {
7821                 dl_unitdata_req_t *dlur;
7822                 uint8_t *bphys_addr;
7823 
7824                 dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7825                 bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7826                     extra_offset;
7827 
7828                 if (bcmp(mhip->mhi_daddr, bphys_addr,
7829                     ind->dl_dest_addr_length) == 0)
7830                         mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7831         }
7832 }
7833 
7834 /*
7835  * This function is used to construct a mac_header_info_s from a
7836  * M_DATA fastpath message from a DLPI driver.
7837  * The address fields in the mhi structure points into the message,
7838  * thus the caller can't use those fields after freeing the message.
7839  *
7840  * We determine whether the packet received is a non-unicast packet
7841  * and in doing so, determine whether or not it is broadcast vs multicast.
7842  * For it to be a broadcast packet, we must have the appropriate mblk_t
7843  * hanging off the ill_t.  If this is either not present or doesn't match
7844  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7845  * to be multicast.  Thus NICs that have no broadcast address (or no
7846  * capability for one, such as point to point links) cannot return as
7847  * the packet being broadcast.
7848  */
7849 void
7850 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7851 {
7852         mblk_t *bmp;
7853         struct ether_header *pether;
7854 
7855         bzero(mhip, sizeof (struct mac_header_info_s));
7856 
7857         mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7858 
7859         pether = (struct ether_header *)((char *)mp->b_rptr
7860             - sizeof (struct ether_header));
7861 
7862         /*
7863          * Make sure the interface is an ethernet type, since we don't
7864          * know the header format for anything but Ethernet. Also make
7865          * sure we are pointing correctly above db_base.
7866          */
7867         if (ill->ill_type != IFT_ETHER)
7868                 return;
7869 
7870 retry:
7871         if ((uchar_t *)pether < mp->b_datap->db_base)
7872                 return;
7873 
7874         /* Is there a VLAN tag? */
7875         if (ill->ill_isv6) {
7876                 if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7877                         pether = (struct ether_header *)((char *)pether - 4);
7878                         goto retry;
7879                 }
7880         } else {
7881                 if (pether->ether_type != htons(ETHERTYPE_IP)) {
7882                         pether = (struct ether_header *)((char *)pether - 4);
7883                         goto retry;
7884                 }
7885         }
7886         mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7887         mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7888 
7889         if (!(mhip->mhi_daddr[0] & 0x01))
7890                 return;
7891 
7892         /* Multicast or broadcast */
7893         mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7894 
7895         if ((bmp = ill->ill_bcast_mp) != NULL) {
7896                 dl_unitdata_req_t *dlur;
7897                 uint8_t *bphys_addr;
7898                 uint_t  addrlen;
7899 
7900                 dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7901                 addrlen = dlur->dl_dest_addr_length;
7902                 if (ill->ill_sap_length < 0) {
7903                         bphys_addr = (uchar_t *)dlur +
7904                             dlur->dl_dest_addr_offset;
7905                         addrlen += ill->ill_sap_length;
7906                 } else {
7907                         bphys_addr = (uchar_t *)dlur +
7908                             dlur->dl_dest_addr_offset +
7909                             ill->ill_sap_length;
7910                         addrlen -= ill->ill_sap_length;
7911                 }
7912                 if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7913                         mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7914         }
7915 }
7916 
7917 /*
7918  * Handle anything but M_DATA messages
7919  * We see the DL_UNITDATA_IND which are part
7920  * of the data path, and also the other messages from the driver.
7921  */
7922 void
7923 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7924 {
7925         mblk_t          *first_mp;
7926         struct iocblk   *iocp;
7927         struct mac_header_info_s mhi;
7928 
7929         switch (DB_TYPE(mp)) {
7930         case M_PROTO:
7931         case M_PCPROTO: {
7932                 if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7933                     DL_UNITDATA_IND) {
7934                         /* Go handle anything other than data elsewhere. */
7935                         ip_rput_dlpi(ill, mp);
7936                         return;
7937                 }
7938 
7939                 first_mp = mp;
7940                 mp = first_mp->b_cont;
7941                 first_mp->b_cont = NULL;
7942 
7943                 if (mp == NULL) {
7944                         freeb(first_mp);
7945                         return;
7946                 }
7947                 ip_dlur_to_mhi(ill, first_mp, &mhi);
7948                 if (ill->ill_isv6)
7949                         ip_input_v6(ill, NULL, mp, &mhi);
7950                 else
7951                         ip_input(ill, NULL, mp, &mhi);
7952 
7953                 /* Ditch the DLPI header. */
7954                 freeb(first_mp);
7955                 return;
7956         }
7957         case M_IOCACK:
7958                 iocp = (struct iocblk *)mp->b_rptr;
7959                 switch (iocp->ioc_cmd) {
7960                 case DL_IOC_HDR_INFO:
7961                         ill_fastpath_ack(ill, mp);
7962                         return;
7963                 default:
7964                         putnext(ill->ill_rq, mp);
7965                         return;
7966                 }
7967                 /* FALLTHRU */
7968         case M_ERROR:
7969         case M_HANGUP:
7970                 mutex_enter(&ill->ill_lock);
7971                 if (ill->ill_state_flags & ILL_CONDEMNED) {
7972                         mutex_exit(&ill->ill_lock);
7973                         freemsg(mp);
7974                         return;
7975                 }
7976                 ill_refhold_locked(ill);
7977                 mutex_exit(&ill->ill_lock);
7978                 qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7979                     B_FALSE);
7980                 return;
7981         case M_CTL:
7982                 putnext(ill->ill_rq, mp);
7983                 return;
7984         case M_IOCNAK:
7985                 ip1dbg(("got iocnak "));
7986                 iocp = (struct iocblk *)mp->b_rptr;
7987                 switch (iocp->ioc_cmd) {
7988                 case DL_IOC_HDR_INFO:
7989                         ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7990                         return;
7991                 default:
7992                         break;
7993                 }
7994                 /* FALLTHRU */
7995         default:
7996                 putnext(ill->ill_rq, mp);
7997                 return;
7998         }
7999 }
8000 
8001 /* Read side put procedure.  Packets coming from the wire arrive here. */
8002 void
8003 ip_rput(queue_t *q, mblk_t *mp)
8004 {
8005         ill_t   *ill;
8006         union DL_primitives *dl;
8007 
8008         ill = (ill_t *)q->q_ptr;
8009 
8010         if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8011                 /*
8012                  * If things are opening or closing, only accept high-priority
8013                  * DLPI messages.  (On open ill->ill_ipif has not yet been
8014                  * created; on close, things hanging off the ill may have been
8015                  * freed already.)
8016                  */
8017                 dl = (union DL_primitives *)mp->b_rptr;
8018                 if (DB_TYPE(mp) != M_PCPROTO ||
8019                     dl->dl_primitive == DL_UNITDATA_IND) {
8020                         inet_freemsg(mp);
8021                         return;
8022                 }
8023         }
8024         if (DB_TYPE(mp) == M_DATA) {
8025                 struct mac_header_info_s mhi;
8026 
8027                 ip_mdata_to_mhi(ill, mp, &mhi);
8028                 ip_input(ill, NULL, mp, &mhi);
8029         } else {
8030                 ip_rput_notdata(ill, mp);
8031         }
8032 }
8033 
8034 /*
8035  * Move the information to a copy.
8036  */
8037 mblk_t *
8038 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8039 {
8040         mblk_t          *mp1;
8041         ill_t           *ill = ira->ira_ill;
8042         ip_stack_t      *ipst = ill->ill_ipst;
8043 
8044         IP_STAT(ipst, ip_db_ref);
8045 
8046         /* Make sure we have ira_l2src before we loose the original mblk */
8047         if (!(ira->ira_flags & IRAF_L2SRC_SET))
8048                 ip_setl2src(mp, ira, ira->ira_rill);
8049 
8050         mp1 = copymsg(mp);
8051         if (mp1 == NULL) {
8052                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8053                 ip_drop_input("ipIfStatsInDiscards", mp, ill);
8054                 freemsg(mp);
8055                 return (NULL);
8056         }
8057         /* preserve the hardware checksum flags and data, if present */
8058         if (DB_CKSUMFLAGS(mp) != 0) {
8059                 DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8060                 DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8061                 DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8062                 DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8063                 DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8064         }
8065         freemsg(mp);
8066         return (mp1);
8067 }
8068 
8069 static void
8070 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8071     t_uscalar_t err)
8072 {
8073         if (dl_err == DL_SYSERR) {
8074                 (void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8075                     "%s: %s failed: DL_SYSERR (errno %u)\n",
8076                     ill->ill_name, dl_primstr(prim), err);
8077                 return;
8078         }
8079 
8080         (void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8081             "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8082             dl_errstr(dl_err));
8083 }
8084 
8085 /*
8086  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8087  * than DL_UNITDATA_IND messages. If we need to process this message
8088  * exclusively, we call qwriter_ip, in which case we also need to call
8089  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8090  */
8091 void
8092 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8093 {
8094         dl_ok_ack_t     *dloa = (dl_ok_ack_t *)mp->b_rptr;
8095         dl_error_ack_t  *dlea = (dl_error_ack_t *)dloa;
8096         queue_t         *q = ill->ill_rq;
8097         t_uscalar_t     prim = dloa->dl_primitive;
8098         t_uscalar_t     reqprim = DL_PRIM_INVAL;
8099 
8100         DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8101             char *, dl_primstr(prim), ill_t *, ill);
8102         ip1dbg(("ip_rput_dlpi"));
8103 
8104         /*
8105          * If we received an ACK but didn't send a request for it, then it
8106          * can't be part of any pending operation; discard up-front.
8107          */
8108         switch (prim) {
8109         case DL_ERROR_ACK:
8110                 reqprim = dlea->dl_error_primitive;
8111                 ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8112                     "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8113                     reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8114                     dlea->dl_unix_errno));
8115                 break;
8116         case DL_OK_ACK:
8117                 reqprim = dloa->dl_correct_primitive;
8118                 break;
8119         case DL_INFO_ACK:
8120                 reqprim = DL_INFO_REQ;
8121                 break;
8122         case DL_BIND_ACK:
8123                 reqprim = DL_BIND_REQ;
8124                 break;
8125         case DL_PHYS_ADDR_ACK:
8126                 reqprim = DL_PHYS_ADDR_REQ;
8127                 break;
8128         case DL_NOTIFY_ACK:
8129                 reqprim = DL_NOTIFY_REQ;
8130                 break;
8131         case DL_CAPABILITY_ACK:
8132                 reqprim = DL_CAPABILITY_REQ;
8133                 break;
8134         }
8135 
8136         if (prim != DL_NOTIFY_IND) {
8137                 if (reqprim == DL_PRIM_INVAL ||
8138                     !ill_dlpi_pending(ill, reqprim)) {
8139                         /* Not a DLPI message we support or expected */
8140                         freemsg(mp);
8141                         return;
8142                 }
8143                 ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8144                     dl_primstr(reqprim)));
8145         }
8146 
8147         switch (reqprim) {
8148         case DL_UNBIND_REQ:
8149                 /*
8150                  * NOTE: we mark the unbind as complete even if we got a
8151                  * DL_ERROR_ACK, since there's not much else we can do.
8152                  */
8153                 mutex_enter(&ill->ill_lock);
8154                 ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8155                 cv_signal(&ill->ill_cv);
8156                 mutex_exit(&ill->ill_lock);
8157                 break;
8158 
8159         case DL_ENABMULTI_REQ:
8160                 if (prim == DL_OK_ACK) {
8161                         if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8162                                 ill->ill_dlpi_multicast_state = IDS_OK;
8163                 }
8164                 break;
8165         }
8166 
8167         /*
8168          * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8169          * need to become writer to continue to process it.  Because an
8170          * exclusive operation doesn't complete until replies to all queued
8171          * DLPI messages have been received, we know we're in the middle of an
8172          * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8173          *
8174          * As required by qwriter_ip(), we refhold the ill; it will refrele.
8175          * Since this is on the ill stream we unconditionally bump up the
8176          * refcount without doing ILL_CAN_LOOKUP().
8177          */
8178         ill_refhold(ill);
8179         if (prim == DL_NOTIFY_IND)
8180                 qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8181         else
8182                 qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8183 }
8184 
8185 /*
8186  * Handling of DLPI messages that require exclusive access to the ipsq.
8187  *
8188  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8189  * happen here. (along with mi_copy_done)
8190  */
8191 /* ARGSUSED */
8192 static void
8193 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8194 {
8195         dl_ok_ack_t     *dloa = (dl_ok_ack_t *)mp->b_rptr;
8196         dl_error_ack_t  *dlea = (dl_error_ack_t *)dloa;
8197         int             err = 0;
8198         ill_t           *ill = (ill_t *)q->q_ptr;
8199         ipif_t          *ipif = NULL;
8200         mblk_t          *mp1 = NULL;
8201         conn_t          *connp = NULL;
8202         t_uscalar_t     paddrreq;
8203         mblk_t          *mp_hw;
8204         boolean_t       success;
8205         boolean_t       ioctl_aborted = B_FALSE;
8206         boolean_t       log = B_TRUE;
8207 
8208         DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8209             char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8210 
8211         ip1dbg(("ip_rput_dlpi_writer .."));
8212         ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8213         ASSERT(IAM_WRITER_ILL(ill));
8214 
8215         ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8216         /*
8217          * The current ioctl could have been aborted by the user and a new
8218          * ioctl to bring up another ill could have started. We could still
8219          * get a response from the driver later.
8220          */
8221         if (ipif != NULL && ipif->ipif_ill != ill)
8222                 ioctl_aborted = B_TRUE;
8223 
8224         switch (dloa->dl_primitive) {
8225         case DL_ERROR_ACK:
8226                 ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8227                     dl_primstr(dlea->dl_error_primitive)));
8228 
8229                 DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8230                     char *, dl_primstr(dlea->dl_error_primitive),
8231                     ill_t *, ill);
8232 
8233                 switch (dlea->dl_error_primitive) {
8234                 case DL_DISABMULTI_REQ:
8235                         ill_dlpi_done(ill, dlea->dl_error_primitive);
8236                         break;
8237                 case DL_PROMISCON_REQ:
8238                 case DL_PROMISCOFF_REQ:
8239                 case DL_UNBIND_REQ:
8240                 case DL_ATTACH_REQ:
8241                 case DL_INFO_REQ:
8242                         ill_dlpi_done(ill, dlea->dl_error_primitive);
8243                         break;
8244                 case DL_NOTIFY_REQ:
8245                         ill_dlpi_done(ill, DL_NOTIFY_REQ);
8246                         log = B_FALSE;
8247                         break;
8248                 case DL_PHYS_ADDR_REQ:
8249                         /*
8250                          * For IPv6 only, there are two additional
8251                          * phys_addr_req's sent to the driver to get the
8252                          * IPv6 token and lla. This allows IP to acquire
8253                          * the hardware address format for a given interface
8254                          * without having built in knowledge of the hardware
8255                          * address. ill_phys_addr_pend keeps track of the last
8256                          * DL_PAR sent so we know which response we are
8257                          * dealing with. ill_dlpi_done will update
8258                          * ill_phys_addr_pend when it sends the next req.
8259                          * We don't complete the IOCTL until all three DL_PARs
8260                          * have been attempted, so set *_len to 0 and break.
8261                          */
8262                         paddrreq = ill->ill_phys_addr_pend;
8263                         ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8264                         if (paddrreq == DL_IPV6_TOKEN) {
8265                                 ill->ill_token_length = 0;
8266                                 log = B_FALSE;
8267                                 break;
8268                         } else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8269                                 ill->ill_nd_lla_len = 0;
8270                                 log = B_FALSE;
8271                                 break;
8272                         }
8273                         /*
8274                          * Something went wrong with the DL_PHYS_ADDR_REQ.
8275                          * We presumably have an IOCTL hanging out waiting
8276                          * for completion. Find it and complete the IOCTL
8277                          * with the error noted.
8278                          * However, ill_dl_phys was called on an ill queue
8279                          * (from SIOCSLIFNAME), thus conn_pending_ill is not
8280                          * set. But the ioctl is known to be pending on ill_wq.
8281                          */
8282                         if (!ill->ill_ifname_pending)
8283                                 break;
8284                         ill->ill_ifname_pending = 0;
8285                         if (!ioctl_aborted)
8286                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8287                         if (mp1 != NULL) {
8288                                 /*
8289                                  * This operation (SIOCSLIFNAME) must have
8290                                  * happened on the ill. Assert there is no conn
8291                                  */
8292                                 ASSERT(connp == NULL);
8293                                 q = ill->ill_wq;
8294                         }
8295                         break;
8296                 case DL_BIND_REQ:
8297                         ill_dlpi_done(ill, DL_BIND_REQ);
8298                         if (ill->ill_ifname_pending)
8299                                 break;
8300                         mutex_enter(&ill->ill_lock);
8301                         ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8302                         mutex_exit(&ill->ill_lock);
8303                         /*
8304                          * Something went wrong with the bind.  We presumably
8305                          * have an IOCTL hanging out waiting for completion.
8306                          * Find it, take down the interface that was coming
8307                          * up, and complete the IOCTL with the error noted.
8308                          */
8309                         if (!ioctl_aborted)
8310                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8311                         if (mp1 != NULL) {
8312                                 /*
8313                                  * This might be a result of a DL_NOTE_REPLUMB
8314                                  * notification. In that case, connp is NULL.
8315                                  */
8316                                 if (connp != NULL)
8317                                         q = CONNP_TO_WQ(connp);
8318 
8319                                 (void) ipif_down(ipif, NULL, NULL);
8320                                 /* error is set below the switch */
8321                         }
8322                         break;
8323                 case DL_ENABMULTI_REQ:
8324                         ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8325 
8326                         if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8327                                 ill->ill_dlpi_multicast_state = IDS_FAILED;
8328                         if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8329 
8330                                 printf("ip: joining multicasts failed (%d)"
8331                                     " on %s - will use link layer "
8332                                     "broadcasts for multicast\n",
8333                                     dlea->dl_errno, ill->ill_name);
8334 
8335                                 /*
8336                                  * Set up for multi_bcast; We are the
8337                                  * writer, so ok to access ill->ill_ipif
8338                                  * without any lock.
8339                                  */
8340                                 mutex_enter(&ill->ill_phyint->phyint_lock);
8341                                 ill->ill_phyint->phyint_flags |=
8342                                     PHYI_MULTI_BCAST;
8343                                 mutex_exit(&ill->ill_phyint->phyint_lock);
8344 
8345                         }
8346                         freemsg(mp);    /* Don't want to pass this up */
8347                         return;
8348                 case DL_CAPABILITY_REQ:
8349                         ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8350                             "DL_CAPABILITY REQ\n"));
8351                         if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8352                                 ill->ill_dlpi_capab_state = IDCS_FAILED;
8353                         ill_capability_done(ill);
8354                         freemsg(mp);
8355                         return;
8356                 }
8357                 /*
8358                  * Note the error for IOCTL completion (mp1 is set when
8359                  * ready to complete ioctl). If ill_ifname_pending_err is
8360                  * set, an error occured during plumbing (ill_ifname_pending),
8361                  * so we want to report that error.
8362                  *
8363                  * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8364                  * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8365                  * expected to get errack'd if the driver doesn't support
8366                  * these flags (e.g. ethernet). log will be set to B_FALSE
8367                  * if these error conditions are encountered.
8368                  */
8369                 if (mp1 != NULL) {
8370                         if (ill->ill_ifname_pending_err != 0)  {
8371                                 err = ill->ill_ifname_pending_err;
8372                                 ill->ill_ifname_pending_err = 0;
8373                         } else {
8374                                 err = dlea->dl_unix_errno ?
8375                                     dlea->dl_unix_errno : ENXIO;
8376                         }
8377                 /*
8378                  * If we're plumbing an interface and an error hasn't already
8379                  * been saved, set ill_ifname_pending_err to the error passed
8380                  * up. Ignore the error if log is B_FALSE (see comment above).
8381                  */
8382                 } else if (log && ill->ill_ifname_pending &&
8383                     ill->ill_ifname_pending_err == 0) {
8384                         ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8385                             dlea->dl_unix_errno : ENXIO;
8386                 }
8387 
8388                 if (log)
8389                         ip_dlpi_error(ill, dlea->dl_error_primitive,
8390                             dlea->dl_errno, dlea->dl_unix_errno);
8391                 break;
8392         case DL_CAPABILITY_ACK:
8393                 ill_capability_ack(ill, mp);
8394                 /*
8395                  * The message has been handed off to ill_capability_ack
8396                  * and must not be freed below
8397                  */
8398                 mp = NULL;
8399                 break;
8400 
8401         case DL_INFO_ACK:
8402                 /* Call a routine to handle this one. */
8403                 ill_dlpi_done(ill, DL_INFO_REQ);
8404                 ip_ll_subnet_defaults(ill, mp);
8405                 ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8406                 return;
8407         case DL_BIND_ACK:
8408                 /*
8409                  * We should have an IOCTL waiting on this unless
8410                  * sent by ill_dl_phys, in which case just return
8411                  */
8412                 ill_dlpi_done(ill, DL_BIND_REQ);
8413 
8414                 if (ill->ill_ifname_pending) {
8415                         DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8416                             ill_t *, ill, mblk_t *, mp);
8417                         break;
8418                 }
8419                 mutex_enter(&ill->ill_lock);
8420                 ill->ill_dl_up = 1;
8421                 ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8422                 mutex_exit(&ill->ill_lock);
8423 
8424                 if (!ioctl_aborted)
8425                         mp1 = ipsq_pending_mp_get(ipsq, &connp);
8426                 if (mp1 == NULL) {
8427                         DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8428                         break;
8429                 }
8430                 /*
8431                  * mp1 was added by ill_dl_up(). if that is a result of
8432                  * a DL_NOTE_REPLUMB notification, connp could be NULL.
8433                  */
8434                 if (connp != NULL)
8435                         q = CONNP_TO_WQ(connp);
8436                 /*
8437                  * We are exclusive. So nothing can change even after
8438                  * we get the pending mp.
8439                  */
8440                 ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8441                 DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8442                 ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8443 
8444                 /*
8445                  * Now bring up the resolver; when that is complete, we'll
8446                  * create IREs.  Note that we intentionally mirror what
8447                  * ipif_up() would have done, because we got here by way of
8448                  * ill_dl_up(), which stopped ipif_up()'s processing.
8449                  */
8450                 if (ill->ill_isv6) {
8451                         /*
8452                          * v6 interfaces.
8453                          * Unlike ARP which has to do another bind
8454                          * and attach, once we get here we are
8455                          * done with NDP
8456                          */
8457                         (void) ipif_resolver_up(ipif, Res_act_initial);
8458                         if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8459                                 err = ipif_up_done_v6(ipif);
8460                 } else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8461                         /*
8462                          * ARP and other v4 external resolvers.
8463                          * Leave the pending mblk intact so that
8464                          * the ioctl completes in ip_rput().
8465                          */
8466                         if (connp != NULL)
8467                                 mutex_enter(&connp->conn_lock);
8468                         mutex_enter(&ill->ill_lock);
8469                         success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8470                         mutex_exit(&ill->ill_lock);
8471                         if (connp != NULL)
8472                                 mutex_exit(&connp->conn_lock);
8473                         if (success) {
8474                                 err = ipif_resolver_up(ipif, Res_act_initial);
8475                                 if (err == EINPROGRESS) {
8476                                         freemsg(mp);
8477                                         return;
8478                                 }
8479                                 mp1 = ipsq_pending_mp_get(ipsq, &connp);
8480                         } else {
8481                                 /* The conn has started closing */
8482                                 err = EINTR;
8483                         }
8484                 } else {
8485                         /*
8486                          * This one is complete. Reply to pending ioctl.
8487                          */
8488                         (void) ipif_resolver_up(ipif, Res_act_initial);
8489                         err = ipif_up_done(ipif);
8490                 }
8491 
8492                 if ((err == 0) && (ill->ill_up_ipifs)) {
8493                         err = ill_up_ipifs(ill, q, mp1);
8494                         if (err == EINPROGRESS) {
8495                                 freemsg(mp);
8496                                 return;
8497                         }
8498                 }
8499 
8500                 /*
8501                  * If we have a moved ipif to bring up, and everything has
8502                  * succeeded to this point, bring it up on the IPMP ill.
8503                  * Otherwise, leave it down -- the admin can try to bring it
8504                  * up by hand if need be.
8505                  */
8506                 if (ill->ill_move_ipif != NULL) {
8507                         if (err != 0) {
8508                                 ill->ill_move_ipif = NULL;
8509                         } else {
8510                                 ipif = ill->ill_move_ipif;
8511                                 ill->ill_move_ipif = NULL;
8512                                 err = ipif_up(ipif, q, mp1);
8513                                 if (err == EINPROGRESS) {
8514                                         freemsg(mp);
8515                                         return;
8516                                 }
8517                         }
8518                 }
8519                 break;
8520 
8521         case DL_NOTIFY_IND: {
8522                 dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8523                 uint_t orig_mtu, orig_mc_mtu;
8524 
8525                 switch (notify->dl_notification) {
8526                 case DL_NOTE_PHYS_ADDR:
8527                         err = ill_set_phys_addr(ill, mp);
8528                         break;
8529 
8530                 case DL_NOTE_REPLUMB:
8531                         /*
8532                          * Directly return after calling ill_replumb().
8533                          * Note that we should not free mp as it is reused
8534                          * in the ill_replumb() function.
8535                          */
8536                         err = ill_replumb(ill, mp);
8537                         return;
8538 
8539                 case DL_NOTE_FASTPATH_FLUSH:
8540                         nce_flush(ill, B_FALSE);
8541                         break;
8542 
8543                 case DL_NOTE_SDU_SIZE:
8544                 case DL_NOTE_SDU_SIZE2:
8545                         /*
8546                          * The dce and fragmentation code can cope with
8547                          * this changing while packets are being sent.
8548                          * When packets are sent ip_output will discover
8549                          * a change.
8550                          *
8551                          * Change the MTU size of the interface.
8552                          */
8553                         mutex_enter(&ill->ill_lock);
8554                         orig_mtu = ill->ill_mtu;
8555                         orig_mc_mtu = ill->ill_mc_mtu;
8556                         switch (notify->dl_notification) {
8557                         case DL_NOTE_SDU_SIZE:
8558                                 ill->ill_current_frag =
8559                                     (uint_t)notify->dl_data;
8560                                 ill->ill_mc_mtu = (uint_t)notify->dl_data;
8561                                 break;
8562                         case DL_NOTE_SDU_SIZE2:
8563                                 ill->ill_current_frag =
8564                                     (uint_t)notify->dl_data1;
8565                                 ill->ill_mc_mtu = (uint_t)notify->dl_data2;
8566                                 break;
8567                         }
8568                         if (ill->ill_current_frag > ill->ill_max_frag)
8569                                 ill->ill_max_frag = ill->ill_current_frag;
8570 
8571                         if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8572                                 ill->ill_mtu = ill->ill_current_frag;
8573 
8574                                 /*
8575                                  * If ill_user_mtu was set (via
8576                                  * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8577                                  */
8578                                 if (ill->ill_user_mtu != 0 &&
8579                                     ill->ill_user_mtu < ill->ill_mtu)
8580                                         ill->ill_mtu = ill->ill_user_mtu;
8581 
8582                                 if (ill->ill_user_mtu != 0 &&
8583                                     ill->ill_user_mtu < ill->ill_mc_mtu)
8584                                         ill->ill_mc_mtu = ill->ill_user_mtu;
8585 
8586                                 if (ill->ill_isv6) {
8587                                         if (ill->ill_mtu < IPV6_MIN_MTU)
8588                                                 ill->ill_mtu = IPV6_MIN_MTU;
8589                                         if (ill->ill_mc_mtu < IPV6_MIN_MTU)
8590                                                 ill->ill_mc_mtu = IPV6_MIN_MTU;
8591                                 } else {
8592                                         if (ill->ill_mtu < IP_MIN_MTU)
8593                                                 ill->ill_mtu = IP_MIN_MTU;
8594                                         if (ill->ill_mc_mtu < IP_MIN_MTU)
8595                                                 ill->ill_mc_mtu = IP_MIN_MTU;
8596                                 }
8597                         } else if (ill->ill_mc_mtu > ill->ill_mtu) {
8598                                 ill->ill_mc_mtu = ill->ill_mtu;
8599                         }
8600 
8601                         mutex_exit(&ill->ill_lock);
8602                         /*
8603                          * Make sure all dce_generation checks find out
8604                          * that ill_mtu/ill_mc_mtu has changed.
8605                          */
8606                         if (orig_mtu != ill->ill_mtu ||
8607                             orig_mc_mtu != ill->ill_mc_mtu) {
8608                                 dce_increment_all_generations(ill->ill_isv6,
8609                                     ill->ill_ipst);
8610                         }
8611 
8612                         /*
8613                          * Refresh IPMP meta-interface MTU if necessary.
8614                          */
8615                         if (IS_UNDER_IPMP(ill))
8616                                 ipmp_illgrp_refresh_mtu(ill->ill_grp);
8617                         break;
8618 
8619                 case DL_NOTE_LINK_UP:
8620                 case DL_NOTE_LINK_DOWN: {
8621                         /*
8622                          * We are writer. ill / phyint / ipsq assocs stable.
8623                          * The RUNNING flag reflects the state of the link.
8624                          */
8625                         phyint_t *phyint = ill->ill_phyint;
8626                         uint64_t new_phyint_flags;
8627                         boolean_t changed = B_FALSE;
8628                         boolean_t went_up;
8629 
8630                         went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8631                         mutex_enter(&phyint->phyint_lock);
8632 
8633                         new_phyint_flags = went_up ?
8634                             phyint->phyint_flags | PHYI_RUNNING :
8635                             phyint->phyint_flags & ~PHYI_RUNNING;
8636 
8637                         if (IS_IPMP(ill)) {
8638                                 new_phyint_flags = went_up ?
8639                                     new_phyint_flags & ~PHYI_FAILED :
8640                                     new_phyint_flags | PHYI_FAILED;
8641                         }
8642 
8643                         if (new_phyint_flags != phyint->phyint_flags) {
8644                                 phyint->phyint_flags = new_phyint_flags;
8645                                 changed = B_TRUE;
8646                         }
8647                         mutex_exit(&phyint->phyint_lock);
8648                         /*
8649                          * ill_restart_dad handles the DAD restart and routing
8650                          * socket notification logic.
8651                          */
8652                         if (changed) {
8653                                 ill_restart_dad(phyint->phyint_illv4, went_up);
8654                                 ill_restart_dad(phyint->phyint_illv6, went_up);
8655                         }
8656                         break;
8657                 }
8658                 case DL_NOTE_PROMISC_ON_PHYS: {
8659                         phyint_t *phyint = ill->ill_phyint;
8660 
8661                         mutex_enter(&phyint->phyint_lock);
8662                         phyint->phyint_flags |= PHYI_PROMISC;
8663                         mutex_exit(&phyint->phyint_lock);
8664                         break;
8665                 }
8666                 case DL_NOTE_PROMISC_OFF_PHYS: {
8667                         phyint_t *phyint = ill->ill_phyint;
8668 
8669                         mutex_enter(&phyint->phyint_lock);
8670                         phyint->phyint_flags &= ~PHYI_PROMISC;
8671                         mutex_exit(&phyint->phyint_lock);
8672                         break;
8673                 }
8674                 case DL_NOTE_CAPAB_RENEG:
8675                         /*
8676                          * Something changed on the driver side.
8677                          * It wants us to renegotiate the capabilities
8678                          * on this ill. One possible cause is the aggregation
8679                          * interface under us where a port got added or
8680                          * went away.
8681                          *
8682                          * If the capability negotiation is already done
8683                          * or is in progress, reset the capabilities and
8684                          * mark the ill's ill_capab_reneg to be B_TRUE,
8685                          * so that when the ack comes back, we can start
8686                          * the renegotiation process.
8687                          *
8688                          * Note that if ill_capab_reneg is already B_TRUE
8689                          * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8690                          * the capability resetting request has been sent
8691                          * and the renegotiation has not been started yet;
8692                          * nothing needs to be done in this case.
8693                          */
8694                         ipsq_current_start(ipsq, ill->ill_ipif, 0);
8695                         ill_capability_reset(ill, B_TRUE);
8696                         ipsq_current_finish(ipsq);
8697                         break;
8698 
8699                 case DL_NOTE_ALLOWED_IPS:
8700                         ill_set_allowed_ips(ill, mp);
8701                         break;
8702                 default:
8703                         ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8704                             "type 0x%x for DL_NOTIFY_IND\n",
8705                             notify->dl_notification));
8706                         break;
8707                 }
8708 
8709                 /*
8710                  * As this is an asynchronous operation, we
8711                  * should not call ill_dlpi_done
8712                  */
8713                 break;
8714         }
8715         case DL_NOTIFY_ACK: {
8716                 dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8717 
8718                 if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8719                         ill->ill_note_link = 1;
8720                 ill_dlpi_done(ill, DL_NOTIFY_REQ);
8721                 break;
8722         }
8723         case DL_PHYS_ADDR_ACK: {
8724                 /*
8725                  * As part of plumbing the interface via SIOCSLIFNAME,
8726                  * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8727                  * whose answers we receive here.  As each answer is received,
8728                  * we call ill_dlpi_done() to dispatch the next request as
8729                  * we're processing the current one.  Once all answers have
8730                  * been received, we use ipsq_pending_mp_get() to dequeue the
8731                  * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8732                  * is invoked from an ill queue, conn_oper_pending_ill is not
8733                  * available, but we know the ioctl is pending on ill_wq.)
8734                  */
8735                 uint_t  paddrlen, paddroff;
8736                 uint8_t *addr;
8737 
8738                 paddrreq = ill->ill_phys_addr_pend;
8739                 paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8740                 paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8741                 addr = mp->b_rptr + paddroff;
8742 
8743                 ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8744                 if (paddrreq == DL_IPV6_TOKEN) {
8745                         /*
8746                          * bcopy to low-order bits of ill_token
8747                          *
8748                          * XXX Temporary hack - currently, all known tokens
8749                          * are 64 bits, so I'll cheat for the moment.
8750                          */
8751                         bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8752                         ill->ill_token_length = paddrlen;
8753                         break;
8754                 } else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8755                         ASSERT(ill->ill_nd_lla_mp == NULL);
8756                         ill_set_ndmp(ill, mp, paddroff, paddrlen);
8757                         mp = NULL;
8758                         break;
8759                 } else if (paddrreq == DL_CURR_DEST_ADDR) {
8760                         ASSERT(ill->ill_dest_addr_mp == NULL);
8761                         ill->ill_dest_addr_mp = mp;
8762                         ill->ill_dest_addr = addr;
8763                         mp = NULL;
8764                         if (ill->ill_isv6) {
8765                                 ill_setdesttoken(ill);
8766                                 ipif_setdestlinklocal(ill->ill_ipif);
8767                         }
8768                         break;
8769                 }
8770 
8771                 ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8772                 ASSERT(ill->ill_phys_addr_mp == NULL);
8773                 if (!ill->ill_ifname_pending)
8774                         break;
8775                 ill->ill_ifname_pending = 0;
8776                 if (!ioctl_aborted)
8777                         mp1 = ipsq_pending_mp_get(ipsq, &connp);
8778                 if (mp1 != NULL) {
8779                         ASSERT(connp == NULL);
8780                         q = ill->ill_wq;
8781                 }
8782                 /*
8783                  * If any error acks received during the plumbing sequence,
8784                  * ill_ifname_pending_err will be set. Break out and send up
8785                  * the error to the pending ioctl.
8786                  */
8787                 if (ill->ill_ifname_pending_err != 0) {
8788                         err = ill->ill_ifname_pending_err;
8789                         ill->ill_ifname_pending_err = 0;
8790                         break;
8791                 }
8792 
8793                 ill->ill_phys_addr_mp = mp;
8794                 ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8795                 mp = NULL;
8796 
8797                 /*
8798                  * If paddrlen or ill_phys_addr_length is zero, the DLPI
8799                  * provider doesn't support physical addresses.  We check both
8800                  * paddrlen and ill_phys_addr_length because sppp (PPP) does
8801                  * not have physical addresses, but historically adversises a
8802                  * physical address length of 0 in its DL_INFO_ACK, but 6 in
8803                  * its DL_PHYS_ADDR_ACK.
8804                  */
8805                 if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8806                         ill->ill_phys_addr = NULL;
8807                 } else if (paddrlen != ill->ill_phys_addr_length) {
8808                         ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8809                             paddrlen, ill->ill_phys_addr_length));
8810                         err = EINVAL;
8811                         break;
8812                 }
8813 
8814                 if (ill->ill_nd_lla_mp == NULL) {
8815                         if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8816                                 err = ENOMEM;
8817                                 break;
8818                         }
8819                         ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8820                 }
8821 
8822                 if (ill->ill_isv6) {
8823                         ill_setdefaulttoken(ill);
8824                         ipif_setlinklocal(ill->ill_ipif);
8825                 }
8826                 break;
8827         }
8828         case DL_OK_ACK:
8829                 ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8830                     dl_primstr((int)dloa->dl_correct_primitive),
8831                     dloa->dl_correct_primitive));
8832                 DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8833                     char *, dl_primstr(dloa->dl_correct_primitive),
8834                     ill_t *, ill);
8835 
8836                 switch (dloa->dl_correct_primitive) {
8837                 case DL_ENABMULTI_REQ:
8838                 case DL_DISABMULTI_REQ:
8839                         ill_dlpi_done(ill, dloa->dl_correct_primitive);
8840                         break;
8841                 case DL_PROMISCON_REQ:
8842                 case DL_PROMISCOFF_REQ:
8843                 case DL_UNBIND_REQ:
8844                 case DL_ATTACH_REQ:
8845                         ill_dlpi_done(ill, dloa->dl_correct_primitive);
8846                         break;
8847                 }
8848                 break;
8849         default:
8850                 break;
8851         }
8852 
8853         freemsg(mp);
8854         if (mp1 == NULL)
8855                 return;
8856 
8857         /*
8858          * The operation must complete without EINPROGRESS since
8859          * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8860          * the operation will be stuck forever inside the IPSQ.
8861          */
8862         ASSERT(err != EINPROGRESS);
8863 
8864         DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8865             int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8866             ipif_t *, NULL);
8867 
8868         switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8869         case 0:
8870                 ipsq_current_finish(ipsq);
8871                 break;
8872 
8873         case SIOCSLIFNAME:
8874         case IF_UNITSEL: {
8875                 ill_t *ill_other = ILL_OTHER(ill);
8876 
8877                 /*
8878                  * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8879                  * ill has a peer which is in an IPMP group, then place ill
8880                  * into the same group.  One catch: although ifconfig plumbs
8881                  * the appropriate IPMP meta-interface prior to plumbing this
8882                  * ill, it is possible for multiple ifconfig applications to
8883                  * race (or for another application to adjust plumbing), in
8884                  * which case the IPMP meta-interface we need will be missing.
8885                  * If so, kick the phyint out of the group.
8886                  */
8887                 if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8888                         ipmp_grp_t      *grp = ill->ill_phyint->phyint_grp;
8889                         ipmp_illgrp_t   *illg;
8890 
8891                         illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8892                         if (illg == NULL)
8893                                 ipmp_phyint_leave_grp(ill->ill_phyint);
8894                         else
8895                                 ipmp_ill_join_illgrp(ill, illg);
8896                 }
8897 
8898                 if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8899                         ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8900                 else
8901                         ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8902                 break;
8903         }
8904         case SIOCLIFADDIF:
8905                 ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8906                 break;
8907 
8908         default:
8909                 ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8910                 break;
8911         }
8912 }
8913 
8914 /*
8915  * ip_rput_other is called by ip_rput to handle messages modifying the global
8916  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8917  */
8918 /* ARGSUSED */
8919 void
8920 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8921 {
8922         ill_t           *ill = q->q_ptr;
8923         struct iocblk   *iocp;
8924 
8925         ip1dbg(("ip_rput_other "));
8926         if (ipsq != NULL) {
8927                 ASSERT(IAM_WRITER_IPSQ(ipsq));
8928                 ASSERT(ipsq->ipsq_xop ==
8929                     ill->ill_phyint->phyint_ipsq->ipsq_xop);
8930         }
8931 
8932         switch (mp->b_datap->db_type) {
8933         case M_ERROR:
8934         case M_HANGUP:
8935                 /*
8936                  * The device has a problem.  We force the ILL down.  It can
8937                  * be brought up again manually using SIOCSIFFLAGS (via
8938                  * ifconfig or equivalent).
8939                  */
8940                 ASSERT(ipsq != NULL);
8941                 if (mp->b_rptr < mp->b_wptr)
8942                         ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8943                 if (ill->ill_error == 0)
8944                         ill->ill_error = ENXIO;
8945                 if (!ill_down_start(q, mp))
8946                         return;
8947                 ipif_all_down_tail(ipsq, q, mp, NULL);
8948                 break;
8949         case M_IOCNAK: {
8950                 iocp = (struct iocblk *)mp->b_rptr;
8951 
8952                 ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8953                 /*
8954                  * If this was the first attempt, turn off the fastpath
8955                  * probing.
8956                  */
8957                 mutex_enter(&ill->ill_lock);
8958                 if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8959                         ill->ill_dlpi_fastpath_state = IDS_FAILED;
8960                         mutex_exit(&ill->ill_lock);
8961                         /*
8962                          * don't flush the nce_t entries: we use them
8963                          * as an index to the ncec itself.
8964                          */
8965                         ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8966                             ill->ill_name));
8967                 } else {
8968                         mutex_exit(&ill->ill_lock);
8969                 }
8970                 freemsg(mp);
8971                 break;
8972         }
8973         default:
8974                 ASSERT(0);
8975                 break;
8976         }
8977 }
8978 
8979 /*
8980  * Update any source route, record route or timestamp options
8981  * When it fails it has consumed the message and BUMPed the MIB.
8982  */
8983 boolean_t
8984 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8985     ip_recv_attr_t *ira)
8986 {
8987         ipoptp_t        opts;
8988         uchar_t         *opt;
8989         uint8_t         optval;
8990         uint8_t         optlen;
8991         ipaddr_t        dst;
8992         ipaddr_t        ifaddr;
8993         uint32_t        ts;
8994         timestruc_t     now;
8995         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
8996 
8997         ip2dbg(("ip_forward_options\n"));
8998         dst = ipha->ipha_dst;
8999         for (optval = ipoptp_first(&opts, ipha);
9000             optval != IPOPT_EOL;
9001             optval = ipoptp_next(&opts)) {
9002                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9003                 opt = opts.ipoptp_cur;
9004                 optlen = opts.ipoptp_len;
9005                 ip2dbg(("ip_forward_options: opt %d, len %d\n",
9006                     optval, opts.ipoptp_len));
9007                 switch (optval) {
9008                         uint32_t off;
9009                 case IPOPT_SSRR:
9010                 case IPOPT_LSRR:
9011                         /* Check if adminstratively disabled */
9012                         if (!ipst->ips_ip_forward_src_routed) {
9013                                 BUMP_MIB(dst_ill->ill_ip_mib,
9014                                     ipIfStatsForwProhibits);
9015                                 ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9016                                     mp, dst_ill);
9017                                 icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9018                                     ira);
9019                                 return (B_FALSE);
9020                         }
9021                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9022                                 /*
9023                                  * Must be partial since ip_input_options
9024                                  * checked for strict.
9025                                  */
9026                                 break;
9027                         }
9028                         off = opt[IPOPT_OFFSET];
9029                         off--;
9030                 redo_srr:
9031                         if (optlen < IP_ADDR_LEN ||
9032                             off > optlen - IP_ADDR_LEN) {
9033                                 /* End of source route */
9034                                 ip1dbg((
9035                                     "ip_forward_options: end of SR\n"));
9036                                 break;
9037                         }
9038                         /* Pick a reasonable address on the outbound if */
9039                         ASSERT(dst_ill != NULL);
9040                         if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9041                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9042                             NULL) != 0) {
9043                                 /* No source! Shouldn't happen */
9044                                 ifaddr = INADDR_ANY;
9045                         }
9046                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9047                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9048                         ip1dbg(("ip_forward_options: next hop 0x%x\n",
9049                             ntohl(dst)));
9050 
9051                         /*
9052                          * Check if our address is present more than
9053                          * once as consecutive hops in source route.
9054                          */
9055                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9056                                 off += IP_ADDR_LEN;
9057                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9058                                 goto redo_srr;
9059                         }
9060                         ipha->ipha_dst = dst;
9061                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9062                         break;
9063                 case IPOPT_RR:
9064                         off = opt[IPOPT_OFFSET];
9065                         off--;
9066                         if (optlen < IP_ADDR_LEN ||
9067                             off > optlen - IP_ADDR_LEN) {
9068                                 /* No more room - ignore */
9069                                 ip1dbg((
9070                                     "ip_forward_options: end of RR\n"));
9071                                 break;
9072                         }
9073                         /* Pick a reasonable address on the outbound if */
9074                         ASSERT(dst_ill != NULL);
9075                         if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9076                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9077                             NULL) != 0) {
9078                                 /* No source! Shouldn't happen */
9079                                 ifaddr = INADDR_ANY;
9080                         }
9081                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9082                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9083                         break;
9084                 case IPOPT_TS:
9085                         /* Insert timestamp if there is room */
9086                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9087                         case IPOPT_TS_TSONLY:
9088                                 off = IPOPT_TS_TIMELEN;
9089                                 break;
9090                         case IPOPT_TS_PRESPEC:
9091                         case IPOPT_TS_PRESPEC_RFC791:
9092                                 /* Verify that the address matched */
9093                                 off = opt[IPOPT_OFFSET] - 1;
9094                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9095                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9096                                         /* Not for us */
9097                                         break;
9098                                 }
9099                                 /* FALLTHRU */
9100                         case IPOPT_TS_TSANDADDR:
9101                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9102                                 break;
9103                         default:
9104                                 /*
9105                                  * ip_*put_options should have already
9106                                  * dropped this packet.
9107                                  */
9108                                 cmn_err(CE_PANIC, "ip_forward_options: "
9109                                     "unknown IT - bug in ip_input_options?\n");
9110                                 return (B_TRUE);        /* Keep "lint" happy */
9111                         }
9112                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9113                                 /* Increase overflow counter */
9114                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9115                                 opt[IPOPT_POS_OV_FLG] =
9116                                     (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9117                                     (off << 4));
9118                                 break;
9119                         }
9120                         off = opt[IPOPT_OFFSET] - 1;
9121                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9122                         case IPOPT_TS_PRESPEC:
9123                         case IPOPT_TS_PRESPEC_RFC791:
9124                         case IPOPT_TS_TSANDADDR:
9125                                 /* Pick a reasonable addr on the outbound if */
9126                                 ASSERT(dst_ill != NULL);
9127                                 if (ip_select_source_v4(dst_ill, INADDR_ANY,
9128                                     dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9129                                     NULL, NULL) != 0) {
9130                                         /* No source! Shouldn't happen */
9131                                         ifaddr = INADDR_ANY;
9132                                 }
9133                                 bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9134                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9135                                 /* FALLTHRU */
9136                         case IPOPT_TS_TSONLY:
9137                                 off = opt[IPOPT_OFFSET] - 1;
9138                                 /* Compute # of milliseconds since midnight */
9139                                 gethrestime(&now);
9140                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9141                                     NSEC2MSEC(now.tv_nsec);
9142                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9143                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9144                                 break;
9145                         }
9146                         break;
9147                 }
9148         }
9149         return (B_TRUE);
9150 }
9151 
9152 /*
9153  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9154  * returns 'true' if there are still fragments left on the queue, in
9155  * which case we restart the timer.
9156  */
9157 void
9158 ill_frag_timer(void *arg)
9159 {
9160         ill_t   *ill = (ill_t *)arg;
9161         boolean_t frag_pending;
9162         ip_stack_t *ipst = ill->ill_ipst;
9163         time_t  timeout;
9164 
9165         mutex_enter(&ill->ill_lock);
9166         ASSERT(!ill->ill_fragtimer_executing);
9167         if (ill->ill_state_flags & ILL_CONDEMNED) {
9168                 ill->ill_frag_timer_id = 0;
9169                 mutex_exit(&ill->ill_lock);
9170                 return;
9171         }
9172         ill->ill_fragtimer_executing = 1;
9173         mutex_exit(&ill->ill_lock);
9174 
9175         timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9176             ipst->ips_ip_reassembly_timeout);
9177 
9178         frag_pending = ill_frag_timeout(ill, timeout);
9179 
9180         /*
9181          * Restart the timer, if we have fragments pending or if someone
9182          * wanted us to be scheduled again.
9183          */
9184         mutex_enter(&ill->ill_lock);
9185         ill->ill_fragtimer_executing = 0;
9186         ill->ill_frag_timer_id = 0;
9187         if (frag_pending || ill->ill_fragtimer_needrestart)
9188                 ill_frag_timer_start(ill);
9189         mutex_exit(&ill->ill_lock);
9190 }
9191 
9192 void
9193 ill_frag_timer_start(ill_t *ill)
9194 {
9195         ip_stack_t *ipst = ill->ill_ipst;
9196         clock_t timeo_ms;
9197 
9198         ASSERT(MUTEX_HELD(&ill->ill_lock));
9199 
9200         /* If the ill is closing or opening don't proceed */
9201         if (ill->ill_state_flags & ILL_CONDEMNED)
9202                 return;
9203 
9204         if (ill->ill_fragtimer_executing) {
9205                 /*
9206                  * ill_frag_timer is currently executing. Just record the
9207                  * the fact that we want the timer to be restarted.
9208                  * ill_frag_timer will post a timeout before it returns,
9209                  * ensuring it will be called again.
9210                  */
9211                 ill->ill_fragtimer_needrestart = 1;
9212                 return;
9213         }
9214 
9215         if (ill->ill_frag_timer_id == 0) {
9216                 timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9217                     ipst->ips_ip_reassembly_timeout) * SECONDS;
9218 
9219                 /*
9220                  * The timer is neither running nor is the timeout handler
9221                  * executing. Post a timeout so that ill_frag_timer will be
9222                  * called
9223                  */
9224                 ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9225                     MSEC_TO_TICK(timeo_ms >> 1));
9226                 ill->ill_fragtimer_needrestart = 0;
9227         }
9228 }
9229 
9230 /*
9231  * Update any source route, record route or timestamp options.
9232  * Check that we are at end of strict source route.
9233  * The options have already been checked for sanity in ip_input_options().
9234  */
9235 boolean_t
9236 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9237 {
9238         ipoptp_t        opts;
9239         uchar_t         *opt;
9240         uint8_t         optval;
9241         uint8_t         optlen;
9242         ipaddr_t        dst;
9243         ipaddr_t        ifaddr;
9244         uint32_t        ts;
9245         timestruc_t     now;
9246         ill_t           *ill = ira->ira_ill;
9247         ip_stack_t      *ipst = ill->ill_ipst;
9248 
9249         ip2dbg(("ip_input_local_options\n"));
9250 
9251         for (optval = ipoptp_first(&opts, ipha);
9252             optval != IPOPT_EOL;
9253             optval = ipoptp_next(&opts)) {
9254                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9255                 opt = opts.ipoptp_cur;
9256                 optlen = opts.ipoptp_len;
9257                 ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9258                     optval, optlen));
9259                 switch (optval) {
9260                         uint32_t off;
9261                 case IPOPT_SSRR:
9262                 case IPOPT_LSRR:
9263                         off = opt[IPOPT_OFFSET];
9264                         off--;
9265                         if (optlen < IP_ADDR_LEN ||
9266                             off > optlen - IP_ADDR_LEN) {
9267                                 /* End of source route */
9268                                 ip1dbg(("ip_input_local_options: end of SR\n"));
9269                                 break;
9270                         }
9271                         /*
9272                          * This will only happen if two consecutive entries
9273                          * in the source route contains our address or if
9274                          * it is a packet with a loose source route which
9275                          * reaches us before consuming the whole source route
9276                          */
9277                         ip1dbg(("ip_input_local_options: not end of SR\n"));
9278                         if (optval == IPOPT_SSRR) {
9279                                 goto bad_src_route;
9280                         }
9281                         /*
9282                          * Hack: instead of dropping the packet truncate the
9283                          * source route to what has been used by filling the
9284                          * rest with IPOPT_NOP.
9285                          */
9286                         opt[IPOPT_OLEN] = (uint8_t)off;
9287                         while (off < optlen) {
9288                                 opt[off++] = IPOPT_NOP;
9289                         }
9290                         break;
9291                 case IPOPT_RR:
9292                         off = opt[IPOPT_OFFSET];
9293                         off--;
9294                         if (optlen < IP_ADDR_LEN ||
9295                             off > optlen - IP_ADDR_LEN) {
9296                                 /* No more room - ignore */
9297                                 ip1dbg((
9298                                     "ip_input_local_options: end of RR\n"));
9299                                 break;
9300                         }
9301                         /* Pick a reasonable address on the outbound if */
9302                         if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9303                             INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9304                             NULL) != 0) {
9305                                 /* No source! Shouldn't happen */
9306                                 ifaddr = INADDR_ANY;
9307                         }
9308                         bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9309                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9310                         break;
9311                 case IPOPT_TS:
9312                         /* Insert timestamp if there is romm */
9313                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9314                         case IPOPT_TS_TSONLY:
9315                                 off = IPOPT_TS_TIMELEN;
9316                                 break;
9317                         case IPOPT_TS_PRESPEC:
9318                         case IPOPT_TS_PRESPEC_RFC791:
9319                                 /* Verify that the address matched */
9320                                 off = opt[IPOPT_OFFSET] - 1;
9321                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9322                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9323                                         /* Not for us */
9324                                         break;
9325                                 }
9326                                 /* FALLTHRU */
9327                         case IPOPT_TS_TSANDADDR:
9328                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9329                                 break;
9330                         default:
9331                                 /*
9332                                  * ip_*put_options should have already
9333                                  * dropped this packet.
9334                                  */
9335                                 cmn_err(CE_PANIC, "ip_input_local_options: "
9336                                     "unknown IT - bug in ip_input_options?\n");
9337                                 return (B_TRUE);        /* Keep "lint" happy */
9338                         }
9339                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9340                                 /* Increase overflow counter */
9341                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9342                                 opt[IPOPT_POS_OV_FLG] =
9343                                     (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9344                                     (off << 4));
9345                                 break;
9346                         }
9347                         off = opt[IPOPT_OFFSET] - 1;
9348                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9349                         case IPOPT_TS_PRESPEC:
9350                         case IPOPT_TS_PRESPEC_RFC791:
9351                         case IPOPT_TS_TSANDADDR:
9352                                 /* Pick a reasonable addr on the outbound if */
9353                                 if (ip_select_source_v4(ill, INADDR_ANY,
9354                                     ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9355                                     &ifaddr, NULL, NULL) != 0) {
9356                                         /* No source! Shouldn't happen */
9357                                         ifaddr = INADDR_ANY;
9358                                 }
9359                                 bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9360                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9361                                 /* FALLTHRU */
9362                         case IPOPT_TS_TSONLY:
9363                                 off = opt[IPOPT_OFFSET] - 1;
9364                                 /* Compute # of milliseconds since midnight */
9365                                 gethrestime(&now);
9366                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9367                                     NSEC2MSEC(now.tv_nsec);
9368                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9369                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9370                                 break;
9371                         }
9372                         break;
9373                 }
9374         }
9375         return (B_TRUE);
9376 
9377 bad_src_route:
9378         /* make sure we clear any indication of a hardware checksum */
9379         DB_CKSUMFLAGS(mp) = 0;
9380         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9381         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9382         return (B_FALSE);
9383 
9384 }
9385 
9386 /*
9387  * Process IP options in an inbound packet.  Always returns the nexthop.
9388  * Normally this is the passed in nexthop, but if there is an option
9389  * that effects the nexthop (such as a source route) that will be returned.
9390  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9391  * and mp freed.
9392  */
9393 ipaddr_t
9394 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9395     ip_recv_attr_t *ira, int *errorp)
9396 {
9397         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
9398         ipoptp_t        opts;
9399         uchar_t         *opt;
9400         uint8_t         optval;
9401         uint8_t         optlen;
9402         intptr_t        code = 0;
9403         ire_t           *ire;
9404 
9405         ip2dbg(("ip_input_options\n"));
9406         *errorp = 0;
9407         for (optval = ipoptp_first(&opts, ipha);
9408             optval != IPOPT_EOL;
9409             optval = ipoptp_next(&opts)) {
9410                 opt = opts.ipoptp_cur;
9411                 optlen = opts.ipoptp_len;
9412                 ip2dbg(("ip_input_options: opt %d, len %d\n",
9413                     optval, optlen));
9414                 /*
9415                  * Note: we need to verify the checksum before we
9416                  * modify anything thus this routine only extracts the next
9417                  * hop dst from any source route.
9418                  */
9419                 switch (optval) {
9420                         uint32_t off;
9421                 case IPOPT_SSRR:
9422                 case IPOPT_LSRR:
9423                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9424                                 if (optval == IPOPT_SSRR) {
9425                                         ip1dbg(("ip_input_options: not next"
9426                                             " strict source route 0x%x\n",
9427                                             ntohl(dst)));
9428                                         code = (char *)&ipha->ipha_dst -
9429                                             (char *)ipha;
9430                                         goto param_prob; /* RouterReq's */
9431                                 }
9432                                 ip2dbg(("ip_input_options: "
9433                                     "not next source route 0x%x\n",
9434                                     ntohl(dst)));
9435                                 break;
9436                         }
9437 
9438                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9439                                 ip1dbg((
9440                                     "ip_input_options: bad option offset\n"));
9441                                 code = (char *)&opt[IPOPT_OLEN] -
9442                                     (char *)ipha;
9443                                 goto param_prob;
9444                         }
9445                         off = opt[IPOPT_OFFSET];
9446                         off--;
9447                 redo_srr:
9448                         if (optlen < IP_ADDR_LEN ||
9449                             off > optlen - IP_ADDR_LEN) {
9450                                 /* End of source route */
9451                                 ip1dbg(("ip_input_options: end of SR\n"));
9452                                 break;
9453                         }
9454                         bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9455                         ip1dbg(("ip_input_options: next hop 0x%x\n",
9456                             ntohl(dst)));
9457 
9458                         /*
9459                          * Check if our address is present more than
9460                          * once as consecutive hops in source route.
9461                          * XXX verify per-interface ip_forwarding
9462                          * for source route?
9463                          */
9464                         if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9465                                 off += IP_ADDR_LEN;
9466                                 goto redo_srr;
9467                         }
9468 
9469                         if (dst == htonl(INADDR_LOOPBACK)) {
9470                                 ip1dbg(("ip_input_options: loopback addr in "
9471                                     "source route!\n"));
9472                                 goto bad_src_route;
9473                         }
9474                         /*
9475                          * For strict: verify that dst is directly
9476                          * reachable.
9477                          */
9478                         if (optval == IPOPT_SSRR) {
9479                                 ire = ire_ftable_lookup_v4(dst, 0, 0,
9480                                     IRE_INTERFACE, NULL, ALL_ZONES,
9481                                     ira->ira_tsl,
9482                                     MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9483                                     NULL);
9484                                 if (ire == NULL) {
9485                                         ip1dbg(("ip_input_options: SSRR not "
9486                                             "directly reachable: 0x%x\n",
9487                                             ntohl(dst)));
9488                                         goto bad_src_route;
9489                                 }
9490                                 ire_refrele(ire);
9491                         }
9492                         /*
9493                          * Defer update of the offset and the record route
9494                          * until the packet is forwarded.
9495                          */
9496                         break;
9497                 case IPOPT_RR:
9498                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9499                                 ip1dbg((
9500                                     "ip_input_options: bad option offset\n"));
9501                                 code = (char *)&opt[IPOPT_OLEN] -
9502                                     (char *)ipha;
9503                                 goto param_prob;
9504                         }
9505                         break;
9506                 case IPOPT_TS:
9507                         /*
9508                          * Verify that length >= 5 and that there is either
9509                          * room for another timestamp or that the overflow
9510                          * counter is not maxed out.
9511                          */
9512                         code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9513                         if (optlen < IPOPT_MINLEN_IT) {
9514                                 goto param_prob;
9515                         }
9516                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9517                                 ip1dbg((
9518                                     "ip_input_options: bad option offset\n"));
9519                                 code = (char *)&opt[IPOPT_OFFSET] -
9520                                     (char *)ipha;
9521                                 goto param_prob;
9522                         }
9523                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9524                         case IPOPT_TS_TSONLY:
9525                                 off = IPOPT_TS_TIMELEN;
9526                                 break;
9527                         case IPOPT_TS_TSANDADDR:
9528                         case IPOPT_TS_PRESPEC:
9529                         case IPOPT_TS_PRESPEC_RFC791:
9530                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9531                                 break;
9532                         default:
9533                                 code = (char *)&opt[IPOPT_POS_OV_FLG] -
9534                                     (char *)ipha;
9535                                 goto param_prob;
9536                         }
9537                         if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9538                             (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9539                                 /*
9540                                  * No room and the overflow counter is 15
9541                                  * already.
9542                                  */
9543                                 goto param_prob;
9544                         }
9545                         break;
9546                 }
9547         }
9548 
9549         if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9550                 return (dst);
9551         }
9552 
9553         ip1dbg(("ip_input_options: error processing IP options."));
9554         code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9555 
9556 param_prob:
9557         /* make sure we clear any indication of a hardware checksum */
9558         DB_CKSUMFLAGS(mp) = 0;
9559         ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9560         icmp_param_problem(mp, (uint8_t)code, ira);
9561         *errorp = -1;
9562         return (dst);
9563 
9564 bad_src_route:
9565         /* make sure we clear any indication of a hardware checksum */
9566         DB_CKSUMFLAGS(mp) = 0;
9567         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9568         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9569         *errorp = -1;
9570         return (dst);
9571 }
9572 
9573 /*
9574  * IP & ICMP info in >=14 msg's ...
9575  *  - ip fixed part (mib2_ip_t)
9576  *  - icmp fixed part (mib2_icmp_t)
9577  *  - ipAddrEntryTable (ip 20)          all IPv4 ipifs
9578  *  - ipRouteEntryTable (ip 21)         all IPv4 IREs
9579  *  - ipNetToMediaEntryTable (ip 22)    all IPv4 Neighbor Cache entries
9580  *  - ipRouteAttributeTable (ip 102)    labeled routes
9581  *  - ip multicast membership (ip_member_t)
9582  *  - ip multicast source filtering (ip_grpsrc_t)
9583  *  - igmp fixed part (struct igmpstat)
9584  *  - multicast routing stats (struct mrtstat)
9585  *  - multicast routing vifs (array of struct vifctl)
9586  *  - multicast routing routes (array of struct mfcctl)
9587  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9588  *                                      One per ill plus one generic
9589  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9590  *                                      One per ill plus one generic
9591  *  - ipv6RouteEntry                    all IPv6 IREs
9592  *  - ipv6RouteAttributeTable (ip6 102) labeled routes
9593  *  - ipv6NetToMediaEntry               all IPv6 Neighbor Cache entries
9594  *  - ipv6AddrEntry                     all IPv6 ipifs
9595  *  - ipv6 multicast membership (ipv6_member_t)
9596  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9597  *
9598  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9599  * already filled in by the caller.
9600  * If legacy_req is true then MIB structures needs to be truncated to their
9601  * legacy sizes before being returned.
9602  * Return value of 0 indicates that no messages were sent and caller
9603  * should free mpctl.
9604  */
9605 int
9606 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9607 {
9608         ip_stack_t *ipst;
9609         sctp_stack_t *sctps;
9610 
9611         if (q->q_next != NULL) {
9612                 ipst = ILLQ_TO_IPST(q);
9613         } else {
9614                 ipst = CONNQ_TO_IPST(q);
9615         }
9616         ASSERT(ipst != NULL);
9617         sctps = ipst->ips_netstack->netstack_sctp;
9618 
9619         if (mpctl == NULL || mpctl->b_cont == NULL) {
9620                 return (0);
9621         }
9622 
9623         /*
9624          * For the purposes of the (broken) packet shell use
9625          * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9626          * to make TCP and UDP appear first in the list of mib items.
9627          * TBD: We could expand this and use it in netstat so that
9628          * the kernel doesn't have to produce large tables (connections,
9629          * routes, etc) when netstat only wants the statistics or a particular
9630          * table.
9631          */
9632         if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9633                 if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9634                         return (1);
9635                 }
9636         }
9637 
9638         if (level != MIB2_TCP) {
9639                 if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9640                         return (1);
9641                 }
9642         }
9643 
9644         if (level != MIB2_UDP) {
9645                 if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9646                         return (1);
9647                 }
9648         }
9649 
9650         if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9651             ipst, legacy_req)) == NULL) {
9652                 return (1);
9653         }
9654 
9655         if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9656             legacy_req)) == NULL) {
9657                 return (1);
9658         }
9659 
9660         if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9661                 return (1);
9662         }
9663 
9664         if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9665                 return (1);
9666         }
9667 
9668         if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9669                 return (1);
9670         }
9671 
9672         if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9673                 return (1);
9674         }
9675 
9676         if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9677             legacy_req)) == NULL) {
9678                 return (1);
9679         }
9680 
9681         if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9682             legacy_req)) == NULL) {
9683                 return (1);
9684         }
9685 
9686         if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9687                 return (1);
9688         }
9689 
9690         if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9691                 return (1);
9692         }
9693 
9694         if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9695                 return (1);
9696         }
9697 
9698         if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9699                 return (1);
9700         }
9701 
9702         if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9703                 return (1);
9704         }
9705 
9706         if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9707                 return (1);
9708         }
9709 
9710         mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9711         if (mpctl == NULL)
9712                 return (1);
9713 
9714         mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9715         if (mpctl == NULL)
9716                 return (1);
9717 
9718         if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9719                 return (1);
9720         }
9721         if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9722                 return (1);
9723         }
9724         freemsg(mpctl);
9725         return (1);
9726 }
9727 
9728 /* Get global (legacy) IPv4 statistics */
9729 static mblk_t *
9730 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9731     ip_stack_t *ipst, boolean_t legacy_req)
9732 {
9733         mib2_ip_t               old_ip_mib;
9734         struct opthdr           *optp;
9735         mblk_t                  *mp2ctl;
9736         mib2_ipAddrEntry_t      mae;
9737 
9738         /*
9739          * make a copy of the original message
9740          */
9741         mp2ctl = copymsg(mpctl);
9742 
9743         /* fixed length IP structure... */
9744         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9745         optp->level = MIB2_IP;
9746         optp->name = 0;
9747         SET_MIB(old_ip_mib.ipForwarding,
9748             (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9749         SET_MIB(old_ip_mib.ipDefaultTTL,
9750             (uint32_t)ipst->ips_ip_def_ttl);
9751         SET_MIB(old_ip_mib.ipReasmTimeout,
9752             ipst->ips_ip_reassembly_timeout);
9753         SET_MIB(old_ip_mib.ipAddrEntrySize,
9754             (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9755             sizeof (mib2_ipAddrEntry_t));
9756         SET_MIB(old_ip_mib.ipRouteEntrySize,
9757             sizeof (mib2_ipRouteEntry_t));
9758         SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9759             sizeof (mib2_ipNetToMediaEntry_t));
9760         SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9761         SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9762         SET_MIB(old_ip_mib.ipRouteAttributeSize,
9763             sizeof (mib2_ipAttributeEntry_t));
9764         SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9765         SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9766 
9767         /*
9768          * Grab the statistics from the new IP MIB
9769          */
9770         SET_MIB(old_ip_mib.ipInReceives,
9771             (uint32_t)ipmib->ipIfStatsHCInReceives);
9772         SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9773         SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9774         SET_MIB(old_ip_mib.ipForwDatagrams,
9775             (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9776         SET_MIB(old_ip_mib.ipInUnknownProtos,
9777             ipmib->ipIfStatsInUnknownProtos);
9778         SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9779         SET_MIB(old_ip_mib.ipInDelivers,
9780             (uint32_t)ipmib->ipIfStatsHCInDelivers);
9781         SET_MIB(old_ip_mib.ipOutRequests,
9782             (uint32_t)ipmib->ipIfStatsHCOutRequests);
9783         SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9784         SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9785         SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9786         SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9787         SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9788         SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9789         SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9790         SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9791 
9792         /* ipRoutingDiscards is not being used */
9793         SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9794         SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9795         SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9796         SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9797         SET_MIB(old_ip_mib.ipReasmDuplicates,
9798             ipmib->ipIfStatsReasmDuplicates);
9799         SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9800         SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9801         SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9802         SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9803         SET_MIB(old_ip_mib.rawipInOverflows,
9804             ipmib->rawipIfStatsInOverflows);
9805 
9806         SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9807         SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9808         SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9809         SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9810         SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9811             ipmib->ipIfStatsOutSwitchIPVersion);
9812 
9813         if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9814             (int)sizeof (old_ip_mib))) {
9815                 ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9816                     (uint_t)sizeof (old_ip_mib)));
9817         }
9818 
9819         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9820         ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9821             (int)optp->level, (int)optp->name, (int)optp->len));
9822         qreply(q, mpctl);
9823         return (mp2ctl);
9824 }
9825 
9826 /* Per interface IPv4 statistics */
9827 static mblk_t *
9828 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9829     boolean_t legacy_req)
9830 {
9831         struct opthdr           *optp;
9832         mblk_t                  *mp2ctl;
9833         ill_t                   *ill;
9834         ill_walk_context_t      ctx;
9835         mblk_t                  *mp_tail = NULL;
9836         mib2_ipIfStatsEntry_t   global_ip_mib;
9837         mib2_ipAddrEntry_t      mae;
9838 
9839         /*
9840          * Make a copy of the original message
9841          */
9842         mp2ctl = copymsg(mpctl);
9843 
9844         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9845         optp->level = MIB2_IP;
9846         optp->name = MIB2_IP_TRAFFIC_STATS;
9847         /* Include "unknown interface" ip_mib */
9848         ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9849         ipst->ips_ip_mib.ipIfStatsIfIndex =
9850             MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9851         SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9852             (ipst->ips_ip_forwarding ? 1 : 2));
9853         SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9854             (uint32_t)ipst->ips_ip_def_ttl);
9855         SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9856             sizeof (mib2_ipIfStatsEntry_t));
9857         SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9858             sizeof (mib2_ipAddrEntry_t));
9859         SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9860             sizeof (mib2_ipRouteEntry_t));
9861         SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9862             sizeof (mib2_ipNetToMediaEntry_t));
9863         SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9864             sizeof (ip_member_t));
9865         SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9866             sizeof (ip_grpsrc_t));
9867 
9868         bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9869 
9870         if (legacy_req) {
9871                 SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9872                     LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9873         }
9874 
9875         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9876             (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9877                 ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9878                     "failed to allocate %u bytes\n",
9879                     (uint_t)sizeof (global_ip_mib)));
9880         }
9881 
9882         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9883         ill = ILL_START_WALK_V4(&ctx, ipst);
9884         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9885                 ill->ill_ip_mib->ipIfStatsIfIndex =
9886                     ill->ill_phyint->phyint_ifindex;
9887                 SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9888                     (ipst->ips_ip_forwarding ? 1 : 2));
9889                 SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9890                     (uint32_t)ipst->ips_ip_def_ttl);
9891 
9892                 ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9893                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9894                     (char *)ill->ill_ip_mib,
9895                     (int)sizeof (*ill->ill_ip_mib))) {
9896                         ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9897                             "failed to allocate %u bytes\n",
9898                             (uint_t)sizeof (*ill->ill_ip_mib)));
9899                 }
9900         }
9901         rw_exit(&ipst->ips_ill_g_lock);
9902 
9903         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9904         ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9905             "level %d, name %d, len %d\n",
9906             (int)optp->level, (int)optp->name, (int)optp->len));
9907         qreply(q, mpctl);
9908 
9909         if (mp2ctl == NULL)
9910                 return (NULL);
9911 
9912         return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9913             legacy_req));
9914 }
9915 
9916 /* Global IPv4 ICMP statistics */
9917 static mblk_t *
9918 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9919 {
9920         struct opthdr           *optp;
9921         mblk_t                  *mp2ctl;
9922 
9923         /*
9924          * Make a copy of the original message
9925          */
9926         mp2ctl = copymsg(mpctl);
9927 
9928         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9929         optp->level = MIB2_ICMP;
9930         optp->name = 0;
9931         if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9932             (int)sizeof (ipst->ips_icmp_mib))) {
9933                 ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9934                     (uint_t)sizeof (ipst->ips_icmp_mib)));
9935         }
9936         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9937         ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9938             (int)optp->level, (int)optp->name, (int)optp->len));
9939         qreply(q, mpctl);
9940         return (mp2ctl);
9941 }
9942 
9943 /* Global IPv4 IGMP statistics */
9944 static mblk_t *
9945 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9946 {
9947         struct opthdr           *optp;
9948         mblk_t                  *mp2ctl;
9949 
9950         /*
9951          * make a copy of the original message
9952          */
9953         mp2ctl = copymsg(mpctl);
9954 
9955         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9956         optp->level = EXPER_IGMP;
9957         optp->name = 0;
9958         if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9959             (int)sizeof (ipst->ips_igmpstat))) {
9960                 ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9961                     (uint_t)sizeof (ipst->ips_igmpstat)));
9962         }
9963         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9964         ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9965             (int)optp->level, (int)optp->name, (int)optp->len));
9966         qreply(q, mpctl);
9967         return (mp2ctl);
9968 }
9969 
9970 /* Global IPv4 Multicast Routing statistics */
9971 static mblk_t *
9972 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9973 {
9974         struct opthdr           *optp;
9975         mblk_t                  *mp2ctl;
9976 
9977         /*
9978          * make a copy of the original message
9979          */
9980         mp2ctl = copymsg(mpctl);
9981 
9982         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9983         optp->level = EXPER_DVMRP;
9984         optp->name = 0;
9985         if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9986                 ip0dbg(("ip_mroute_stats: failed\n"));
9987         }
9988         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9989         ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9990             (int)optp->level, (int)optp->name, (int)optp->len));
9991         qreply(q, mpctl);
9992         return (mp2ctl);
9993 }
9994 
9995 /* IPv4 address information */
9996 static mblk_t *
9997 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9998     boolean_t legacy_req)
9999 {
10000         struct opthdr           *optp;
10001         mblk_t                  *mp2ctl;
10002         mblk_t                  *mp_tail = NULL;
10003         ill_t                   *ill;
10004         ipif_t                  *ipif;
10005         uint_t                  bitval;
10006         mib2_ipAddrEntry_t      mae;
10007         size_t                  mae_size;
10008         zoneid_t                zoneid;
10009         ill_walk_context_t      ctx;
10010 
10011         /*
10012          * make a copy of the original message
10013          */
10014         mp2ctl = copymsg(mpctl);
10015 
10016         mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
10017             sizeof (mib2_ipAddrEntry_t);
10018 
10019         /* ipAddrEntryTable */
10020 
10021         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10022         optp->level = MIB2_IP;
10023         optp->name = MIB2_IP_ADDR;
10024         zoneid = Q_TO_CONN(q)->conn_zoneid;
10025 
10026         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10027         ill = ILL_START_WALK_V4(&ctx, ipst);
10028         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10029                 for (ipif = ill->ill_ipif; ipif != NULL;
10030                     ipif = ipif->ipif_next) {
10031                         if (ipif->ipif_zoneid != zoneid &&
10032                             ipif->ipif_zoneid != ALL_ZONES)
10033                                 continue;
10034                         /* Sum of count from dead IRE_LO* and our current */
10035                         mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10036                         if (ipif->ipif_ire_local != NULL) {
10037                                 mae.ipAdEntInfo.ae_ibcnt +=
10038                                     ipif->ipif_ire_local->ire_ib_pkt_count;
10039                         }
10040                         mae.ipAdEntInfo.ae_obcnt = 0;
10041                         mae.ipAdEntInfo.ae_focnt = 0;
10042 
10043                         ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10044                             OCTET_LENGTH);
10045                         mae.ipAdEntIfIndex.o_length =
10046                             mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10047                         mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10048                         mae.ipAdEntNetMask = ipif->ipif_net_mask;
10049                         mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10050                         mae.ipAdEntInfo.ae_subnet_len =
10051                             ip_mask_to_plen(ipif->ipif_net_mask);
10052                         mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10053                         for (bitval = 1;
10054                             bitval &&
10055                             !(bitval & ipif->ipif_brd_addr);
10056                             bitval <<= 1)
10057                                 noop;
10058                         mae.ipAdEntBcastAddr = bitval;
10059                         mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10060                         mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10061                         mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
10062                         mae.ipAdEntInfo.ae_broadcast_addr =
10063                             ipif->ipif_brd_addr;
10064                         mae.ipAdEntInfo.ae_pp_dst_addr =
10065                             ipif->ipif_pp_dst_addr;
10066                         mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10067                             ill->ill_flags | ill->ill_phyint->phyint_flags;
10068                         mae.ipAdEntRetransmitTime =
10069                             ill->ill_reachable_retrans_time;
10070 
10071                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10072                             (char *)&mae, (int)mae_size)) {
10073                                 ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10074                                     "allocate %u bytes\n", (uint_t)mae_size));
10075                         }
10076                 }
10077         }
10078         rw_exit(&ipst->ips_ill_g_lock);
10079 
10080         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10081         ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10082             (int)optp->level, (int)optp->name, (int)optp->len));
10083         qreply(q, mpctl);
10084         return (mp2ctl);
10085 }
10086 
10087 /* IPv6 address information */
10088 static mblk_t *
10089 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10090     boolean_t legacy_req)
10091 {
10092         struct opthdr           *optp;
10093         mblk_t                  *mp2ctl;
10094         mblk_t                  *mp_tail = NULL;
10095         ill_t                   *ill;
10096         ipif_t                  *ipif;
10097         mib2_ipv6AddrEntry_t    mae6;
10098         size_t                  mae6_size;
10099         zoneid_t                zoneid;
10100         ill_walk_context_t      ctx;
10101 
10102         /*
10103          * make a copy of the original message
10104          */
10105         mp2ctl = copymsg(mpctl);
10106 
10107         mae6_size = (legacy_req) ?
10108             LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10109             sizeof (mib2_ipv6AddrEntry_t);
10110 
10111         /* ipv6AddrEntryTable */
10112 
10113         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10114         optp->level = MIB2_IP6;
10115         optp->name = MIB2_IP6_ADDR;
10116         zoneid = Q_TO_CONN(q)->conn_zoneid;
10117 
10118         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10119         ill = ILL_START_WALK_V6(&ctx, ipst);
10120         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10121                 for (ipif = ill->ill_ipif; ipif != NULL;
10122                     ipif = ipif->ipif_next) {
10123                         if (ipif->ipif_zoneid != zoneid &&
10124                             ipif->ipif_zoneid != ALL_ZONES)
10125                                 continue;
10126                         /* Sum of count from dead IRE_LO* and our current */
10127                         mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10128                         if (ipif->ipif_ire_local != NULL) {
10129                                 mae6.ipv6AddrInfo.ae_ibcnt +=
10130                                     ipif->ipif_ire_local->ire_ib_pkt_count;
10131                         }
10132                         mae6.ipv6AddrInfo.ae_obcnt = 0;
10133                         mae6.ipv6AddrInfo.ae_focnt = 0;
10134 
10135                         ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10136                             OCTET_LENGTH);
10137                         mae6.ipv6AddrIfIndex.o_length =
10138                             mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10139                         mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10140                         mae6.ipv6AddrPfxLength =
10141                             ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10142                         mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10143                         mae6.ipv6AddrInfo.ae_subnet_len =
10144                             mae6.ipv6AddrPfxLength;
10145                         mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10146 
10147                         /* Type: stateless(1), stateful(2), unknown(3) */
10148                         if (ipif->ipif_flags & IPIF_ADDRCONF)
10149                                 mae6.ipv6AddrType = 1;
10150                         else
10151                                 mae6.ipv6AddrType = 2;
10152                         /* Anycast: true(1), false(2) */
10153                         if (ipif->ipif_flags & IPIF_ANYCAST)
10154                                 mae6.ipv6AddrAnycastFlag = 1;
10155                         else
10156                                 mae6.ipv6AddrAnycastFlag = 2;
10157 
10158                         /*
10159                          * Address status: preferred(1), deprecated(2),
10160                          * invalid(3), inaccessible(4), unknown(5)
10161                          */
10162                         if (ipif->ipif_flags & IPIF_NOLOCAL)
10163                                 mae6.ipv6AddrStatus = 3;
10164                         else if (ipif->ipif_flags & IPIF_DEPRECATED)
10165                                 mae6.ipv6AddrStatus = 2;
10166                         else
10167                                 mae6.ipv6AddrStatus = 1;
10168                         mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10169                         mae6.ipv6AddrInfo.ae_metric  =
10170                             ipif->ipif_ill->ill_metric;
10171                         mae6.ipv6AddrInfo.ae_pp_dst_addr =
10172                             ipif->ipif_v6pp_dst_addr;
10173                         mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10174                             ill->ill_flags | ill->ill_phyint->phyint_flags;
10175                         mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10176                         mae6.ipv6AddrIdentifier = ill->ill_token;
10177                         mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10178                         mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10179                         mae6.ipv6AddrRetransmitTime =
10180                             ill->ill_reachable_retrans_time;
10181                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10182                             (char *)&mae6, (int)mae6_size)) {
10183                                 ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10184                                     "allocate %u bytes\n",
10185                                     (uint_t)mae6_size));
10186                         }
10187                 }
10188         }
10189         rw_exit(&ipst->ips_ill_g_lock);
10190 
10191         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10192         ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10193             (int)optp->level, (int)optp->name, (int)optp->len));
10194         qreply(q, mpctl);
10195         return (mp2ctl);
10196 }
10197 
10198 /* IPv4 multicast group membership. */
10199 static mblk_t *
10200 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10201 {
10202         struct opthdr           *optp;
10203         mblk_t                  *mp2ctl;
10204         ill_t                   *ill;
10205         ipif_t                  *ipif;
10206         ilm_t                   *ilm;
10207         ip_member_t             ipm;
10208         mblk_t                  *mp_tail = NULL;
10209         ill_walk_context_t      ctx;
10210         zoneid_t                zoneid;
10211 
10212         /*
10213          * make a copy of the original message
10214          */
10215         mp2ctl = copymsg(mpctl);
10216         zoneid = Q_TO_CONN(q)->conn_zoneid;
10217 
10218         /* ipGroupMember table */
10219         optp = (struct opthdr *)&mpctl->b_rptr[
10220             sizeof (struct T_optmgmt_ack)];
10221         optp->level = MIB2_IP;
10222         optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10223 
10224         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10225         ill = ILL_START_WALK_V4(&ctx, ipst);
10226         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10227                 /* Make sure the ill isn't going away. */
10228                 if (!ill_check_and_refhold(ill))
10229                         continue;
10230                 rw_exit(&ipst->ips_ill_g_lock);
10231                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10232                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10233                         if (ilm->ilm_zoneid != zoneid &&
10234                             ilm->ilm_zoneid != ALL_ZONES)
10235                                 continue;
10236 
10237                         /* Is there an ipif for ilm_ifaddr? */
10238                         for (ipif = ill->ill_ipif; ipif != NULL;
10239                             ipif = ipif->ipif_next) {
10240                                 if (!IPIF_IS_CONDEMNED(ipif) &&
10241                                     ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10242                                     ilm->ilm_ifaddr != INADDR_ANY)
10243                                         break;
10244                         }
10245                         if (ipif != NULL) {
10246                                 ipif_get_name(ipif,
10247                                     ipm.ipGroupMemberIfIndex.o_bytes,
10248                                     OCTET_LENGTH);
10249                         } else {
10250                                 ill_get_name(ill,
10251                                     ipm.ipGroupMemberIfIndex.o_bytes,
10252                                     OCTET_LENGTH);
10253                         }
10254                         ipm.ipGroupMemberIfIndex.o_length =
10255                             mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10256 
10257                         ipm.ipGroupMemberAddress = ilm->ilm_addr;
10258                         ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10259                         ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10260                         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10261                             (char *)&ipm, (int)sizeof (ipm))) {
10262                                 ip1dbg(("ip_snmp_get_mib2_ip_group: "
10263                                     "failed to allocate %u bytes\n",
10264                                     (uint_t)sizeof (ipm)));
10265                         }
10266                 }
10267                 rw_exit(&ill->ill_mcast_lock);
10268                 ill_refrele(ill);
10269                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10270         }
10271         rw_exit(&ipst->ips_ill_g_lock);
10272         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10273         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10274             (int)optp->level, (int)optp->name, (int)optp->len));
10275         qreply(q, mpctl);
10276         return (mp2ctl);
10277 }
10278 
10279 /* IPv6 multicast group membership. */
10280 static mblk_t *
10281 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10282 {
10283         struct opthdr           *optp;
10284         mblk_t                  *mp2ctl;
10285         ill_t                   *ill;
10286         ilm_t                   *ilm;
10287         ipv6_member_t           ipm6;
10288         mblk_t                  *mp_tail = NULL;
10289         ill_walk_context_t      ctx;
10290         zoneid_t                zoneid;
10291 
10292         /*
10293          * make a copy of the original message
10294          */
10295         mp2ctl = copymsg(mpctl);
10296         zoneid = Q_TO_CONN(q)->conn_zoneid;
10297 
10298         /* ip6GroupMember table */
10299         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10300         optp->level = MIB2_IP6;
10301         optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10302 
10303         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10304         ill = ILL_START_WALK_V6(&ctx, ipst);
10305         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10306                 /* Make sure the ill isn't going away. */
10307                 if (!ill_check_and_refhold(ill))
10308                         continue;
10309                 rw_exit(&ipst->ips_ill_g_lock);
10310                 /*
10311                  * Normally we don't have any members on under IPMP interfaces.
10312                  * We report them as a debugging aid.
10313                  */
10314                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10315                 ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10316                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10317                         if (ilm->ilm_zoneid != zoneid &&
10318                             ilm->ilm_zoneid != ALL_ZONES)
10319                                 continue;       /* not this zone */
10320                         ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10321                         ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10322                         ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10323                         if (!snmp_append_data2(mpctl->b_cont,
10324                             &mp_tail,
10325                             (char *)&ipm6, (int)sizeof (ipm6))) {
10326                                 ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10327                                     "failed to allocate %u bytes\n",
10328                                     (uint_t)sizeof (ipm6)));
10329                         }
10330                 }
10331                 rw_exit(&ill->ill_mcast_lock);
10332                 ill_refrele(ill);
10333                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10334         }
10335         rw_exit(&ipst->ips_ill_g_lock);
10336 
10337         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10338         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10339             (int)optp->level, (int)optp->name, (int)optp->len));
10340         qreply(q, mpctl);
10341         return (mp2ctl);
10342 }
10343 
10344 /* IP multicast filtered sources */
10345 static mblk_t *
10346 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10347 {
10348         struct opthdr           *optp;
10349         mblk_t                  *mp2ctl;
10350         ill_t                   *ill;
10351         ipif_t                  *ipif;
10352         ilm_t                   *ilm;
10353         ip_grpsrc_t             ips;
10354         mblk_t                  *mp_tail = NULL;
10355         ill_walk_context_t      ctx;
10356         zoneid_t                zoneid;
10357         int                     i;
10358         slist_t                 *sl;
10359 
10360         /*
10361          * make a copy of the original message
10362          */
10363         mp2ctl = copymsg(mpctl);
10364         zoneid = Q_TO_CONN(q)->conn_zoneid;
10365 
10366         /* ipGroupSource table */
10367         optp = (struct opthdr *)&mpctl->b_rptr[
10368             sizeof (struct T_optmgmt_ack)];
10369         optp->level = MIB2_IP;
10370         optp->name = EXPER_IP_GROUP_SOURCES;
10371 
10372         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10373         ill = ILL_START_WALK_V4(&ctx, ipst);
10374         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10375                 /* Make sure the ill isn't going away. */
10376                 if (!ill_check_and_refhold(ill))
10377                         continue;
10378                 rw_exit(&ipst->ips_ill_g_lock);
10379                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10380                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10381                         sl = ilm->ilm_filter;
10382                         if (ilm->ilm_zoneid != zoneid &&
10383                             ilm->ilm_zoneid != ALL_ZONES)
10384                                 continue;
10385                         if (SLIST_IS_EMPTY(sl))
10386                                 continue;
10387 
10388                         /* Is there an ipif for ilm_ifaddr? */
10389                         for (ipif = ill->ill_ipif; ipif != NULL;
10390                             ipif = ipif->ipif_next) {
10391                                 if (!IPIF_IS_CONDEMNED(ipif) &&
10392                                     ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10393                                     ilm->ilm_ifaddr != INADDR_ANY)
10394                                         break;
10395                         }
10396                         if (ipif != NULL) {
10397                                 ipif_get_name(ipif,
10398                                     ips.ipGroupSourceIfIndex.o_bytes,
10399                                     OCTET_LENGTH);
10400                         } else {
10401                                 ill_get_name(ill,
10402                                     ips.ipGroupSourceIfIndex.o_bytes,
10403                                     OCTET_LENGTH);
10404                         }
10405                         ips.ipGroupSourceIfIndex.o_length =
10406                             mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10407 
10408                         ips.ipGroupSourceGroup = ilm->ilm_addr;
10409                         for (i = 0; i < sl->sl_numsrc; i++) {
10410                                 if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10411                                         continue;
10412                                 IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10413                                     ips.ipGroupSourceAddress);
10414                                 if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10415                                     (char *)&ips, (int)sizeof (ips)) == 0) {
10416                                         ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10417                                             " failed to allocate %u bytes\n",
10418                                             (uint_t)sizeof (ips)));
10419                                 }
10420                         }
10421                 }
10422                 rw_exit(&ill->ill_mcast_lock);
10423                 ill_refrele(ill);
10424                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10425         }
10426         rw_exit(&ipst->ips_ill_g_lock);
10427         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10428         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10429             (int)optp->level, (int)optp->name, (int)optp->len));
10430         qreply(q, mpctl);
10431         return (mp2ctl);
10432 }
10433 
10434 /* IPv6 multicast filtered sources. */
10435 static mblk_t *
10436 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10437 {
10438         struct opthdr           *optp;
10439         mblk_t                  *mp2ctl;
10440         ill_t                   *ill;
10441         ilm_t                   *ilm;
10442         ipv6_grpsrc_t           ips6;
10443         mblk_t                  *mp_tail = NULL;
10444         ill_walk_context_t      ctx;
10445         zoneid_t                zoneid;
10446         int                     i;
10447         slist_t                 *sl;
10448 
10449         /*
10450          * make a copy of the original message
10451          */
10452         mp2ctl = copymsg(mpctl);
10453         zoneid = Q_TO_CONN(q)->conn_zoneid;
10454 
10455         /* ip6GroupMember table */
10456         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10457         optp->level = MIB2_IP6;
10458         optp->name = EXPER_IP6_GROUP_SOURCES;
10459 
10460         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10461         ill = ILL_START_WALK_V6(&ctx, ipst);
10462         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10463                 /* Make sure the ill isn't going away. */
10464                 if (!ill_check_and_refhold(ill))
10465                         continue;
10466                 rw_exit(&ipst->ips_ill_g_lock);
10467                 /*
10468                  * Normally we don't have any members on under IPMP interfaces.
10469                  * We report them as a debugging aid.
10470                  */
10471                 rw_enter(&ill->ill_mcast_lock, RW_READER);
10472                 ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10473                 for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10474                         sl = ilm->ilm_filter;
10475                         if (ilm->ilm_zoneid != zoneid &&
10476                             ilm->ilm_zoneid != ALL_ZONES)
10477                                 continue;
10478                         if (SLIST_IS_EMPTY(sl))
10479                                 continue;
10480                         ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10481                         for (i = 0; i < sl->sl_numsrc; i++) {
10482                                 ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10483                                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10484                                     (char *)&ips6, (int)sizeof (ips6))) {
10485                                         ip1dbg(("ip_snmp_get_mib2_ip6_"
10486                                             "group_src: failed to allocate "
10487                                             "%u bytes\n",
10488                                             (uint_t)sizeof (ips6)));
10489                                 }
10490                         }
10491                 }
10492                 rw_exit(&ill->ill_mcast_lock);
10493                 ill_refrele(ill);
10494                 rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10495         }
10496         rw_exit(&ipst->ips_ill_g_lock);
10497 
10498         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10499         ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10500             (int)optp->level, (int)optp->name, (int)optp->len));
10501         qreply(q, mpctl);
10502         return (mp2ctl);
10503 }
10504 
10505 /* Multicast routing virtual interface table. */
10506 static mblk_t *
10507 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10508 {
10509         struct opthdr           *optp;
10510         mblk_t                  *mp2ctl;
10511 
10512         /*
10513          * make a copy of the original message
10514          */
10515         mp2ctl = copymsg(mpctl);
10516 
10517         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10518         optp->level = EXPER_DVMRP;
10519         optp->name = EXPER_DVMRP_VIF;
10520         if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10521                 ip0dbg(("ip_mroute_vif: failed\n"));
10522         }
10523         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10524         ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10525             (int)optp->level, (int)optp->name, (int)optp->len));
10526         qreply(q, mpctl);
10527         return (mp2ctl);
10528 }
10529 
10530 /* Multicast routing table. */
10531 static mblk_t *
10532 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10533 {
10534         struct opthdr           *optp;
10535         mblk_t                  *mp2ctl;
10536 
10537         /*
10538          * make a copy of the original message
10539          */
10540         mp2ctl = copymsg(mpctl);
10541 
10542         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10543         optp->level = EXPER_DVMRP;
10544         optp->name = EXPER_DVMRP_MRT;
10545         if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10546                 ip0dbg(("ip_mroute_mrt: failed\n"));
10547         }
10548         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10549         ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10550             (int)optp->level, (int)optp->name, (int)optp->len));
10551         qreply(q, mpctl);
10552         return (mp2ctl);
10553 }
10554 
10555 /*
10556  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10557  * in one IRE walk.
10558  */
10559 static mblk_t *
10560 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10561     ip_stack_t *ipst)
10562 {
10563         struct opthdr   *optp;
10564         mblk_t          *mp2ctl;        /* Returned */
10565         mblk_t          *mp3ctl;        /* nettomedia */
10566         mblk_t          *mp4ctl;        /* routeattrs */
10567         iproutedata_t   ird;
10568         zoneid_t        zoneid;
10569 
10570         /*
10571          * make copies of the original message
10572          *      - mp2ctl is returned unchanged to the caller for his use
10573          *      - mpctl is sent upstream as ipRouteEntryTable
10574          *      - mp3ctl is sent upstream as ipNetToMediaEntryTable
10575          *      - mp4ctl is sent upstream as ipRouteAttributeTable
10576          */
10577         mp2ctl = copymsg(mpctl);
10578         mp3ctl = copymsg(mpctl);
10579         mp4ctl = copymsg(mpctl);
10580         if (mp3ctl == NULL || mp4ctl == NULL) {
10581                 freemsg(mp4ctl);
10582                 freemsg(mp3ctl);
10583                 freemsg(mp2ctl);
10584                 freemsg(mpctl);
10585                 return (NULL);
10586         }
10587 
10588         bzero(&ird, sizeof (ird));
10589 
10590         ird.ird_route.lp_head = mpctl->b_cont;
10591         ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10592         ird.ird_attrs.lp_head = mp4ctl->b_cont;
10593         /*
10594          * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10595          * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10596          * intended a temporary solution until a proper MIB API is provided
10597          * that provides complete filtering/caller-opt-in.
10598          */
10599         if (level == EXPER_IP_AND_ALL_IRES)
10600                 ird.ird_flags |= IRD_REPORT_ALL;
10601 
10602         zoneid = Q_TO_CONN(q)->conn_zoneid;
10603         ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10604 
10605         /* ipRouteEntryTable in mpctl */
10606         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10607         optp->level = MIB2_IP;
10608         optp->name = MIB2_IP_ROUTE;
10609         optp->len = msgdsize(ird.ird_route.lp_head);
10610         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10611             (int)optp->level, (int)optp->name, (int)optp->len));
10612         qreply(q, mpctl);
10613 
10614         /* ipNetToMediaEntryTable in mp3ctl */
10615         ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10616 
10617         optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10618         optp->level = MIB2_IP;
10619         optp->name = MIB2_IP_MEDIA;
10620         optp->len = msgdsize(ird.ird_netmedia.lp_head);
10621         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10622             (int)optp->level, (int)optp->name, (int)optp->len));
10623         qreply(q, mp3ctl);
10624 
10625         /* ipRouteAttributeTable in mp4ctl */
10626         optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10627         optp->level = MIB2_IP;
10628         optp->name = EXPER_IP_RTATTR;
10629         optp->len = msgdsize(ird.ird_attrs.lp_head);
10630         ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10631             (int)optp->level, (int)optp->name, (int)optp->len));
10632         if (optp->len == 0)
10633                 freemsg(mp4ctl);
10634         else
10635                 qreply(q, mp4ctl);
10636 
10637         return (mp2ctl);
10638 }
10639 
10640 /*
10641  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10642  * ipv6NetToMediaEntryTable in an NDP walk.
10643  */
10644 static mblk_t *
10645 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10646     ip_stack_t *ipst)
10647 {
10648         struct opthdr   *optp;
10649         mblk_t          *mp2ctl;        /* Returned */
10650         mblk_t          *mp3ctl;        /* nettomedia */
10651         mblk_t          *mp4ctl;        /* routeattrs */
10652         iproutedata_t   ird;
10653         zoneid_t        zoneid;
10654 
10655         /*
10656          * make copies of the original message
10657          *      - mp2ctl is returned unchanged to the caller for his use
10658          *      - mpctl is sent upstream as ipv6RouteEntryTable
10659          *      - mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10660          *      - mp4ctl is sent upstream as ipv6RouteAttributeTable
10661          */
10662         mp2ctl = copymsg(mpctl);
10663         mp3ctl = copymsg(mpctl);
10664         mp4ctl = copymsg(mpctl);
10665         if (mp3ctl == NULL || mp4ctl == NULL) {
10666                 freemsg(mp4ctl);
10667                 freemsg(mp3ctl);
10668                 freemsg(mp2ctl);
10669                 freemsg(mpctl);
10670                 return (NULL);
10671         }
10672 
10673         bzero(&ird, sizeof (ird));
10674 
10675         ird.ird_route.lp_head = mpctl->b_cont;
10676         ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10677         ird.ird_attrs.lp_head = mp4ctl->b_cont;
10678         /*
10679          * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10680          * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10681          * intended a temporary solution until a proper MIB API is provided
10682          * that provides complete filtering/caller-opt-in.
10683          */
10684         if (level == EXPER_IP_AND_ALL_IRES)
10685                 ird.ird_flags |= IRD_REPORT_ALL;
10686 
10687         zoneid = Q_TO_CONN(q)->conn_zoneid;
10688         ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10689 
10690         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10691         optp->level = MIB2_IP6;
10692         optp->name = MIB2_IP6_ROUTE;
10693         optp->len = msgdsize(ird.ird_route.lp_head);
10694         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10695             (int)optp->level, (int)optp->name, (int)optp->len));
10696         qreply(q, mpctl);
10697 
10698         /* ipv6NetToMediaEntryTable in mp3ctl */
10699         ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10700 
10701         optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10702         optp->level = MIB2_IP6;
10703         optp->name = MIB2_IP6_MEDIA;
10704         optp->len = msgdsize(ird.ird_netmedia.lp_head);
10705         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10706             (int)optp->level, (int)optp->name, (int)optp->len));
10707         qreply(q, mp3ctl);
10708 
10709         /* ipv6RouteAttributeTable in mp4ctl */
10710         optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10711         optp->level = MIB2_IP6;
10712         optp->name = EXPER_IP_RTATTR;
10713         optp->len = msgdsize(ird.ird_attrs.lp_head);
10714         ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10715             (int)optp->level, (int)optp->name, (int)optp->len));
10716         if (optp->len == 0)
10717                 freemsg(mp4ctl);
10718         else
10719                 qreply(q, mp4ctl);
10720 
10721         return (mp2ctl);
10722 }
10723 
10724 /*
10725  * IPv6 mib: One per ill
10726  */
10727 static mblk_t *
10728 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10729     boolean_t legacy_req)
10730 {
10731         struct opthdr           *optp;
10732         mblk_t                  *mp2ctl;
10733         ill_t                   *ill;
10734         ill_walk_context_t      ctx;
10735         mblk_t                  *mp_tail = NULL;
10736         mib2_ipv6AddrEntry_t    mae6;
10737         mib2_ipIfStatsEntry_t   *ise;
10738         size_t                  ise_size, iae_size;
10739 
10740         /*
10741          * Make a copy of the original message
10742          */
10743         mp2ctl = copymsg(mpctl);
10744 
10745         /* fixed length IPv6 structure ... */
10746 
10747         if (legacy_req) {
10748                 ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10749                     mib2_ipIfStatsEntry_t);
10750                 iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10751         } else {
10752                 ise_size = sizeof (mib2_ipIfStatsEntry_t);
10753                 iae_size = sizeof (mib2_ipv6AddrEntry_t);
10754         }
10755 
10756         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10757         optp->level = MIB2_IP6;
10758         optp->name = 0;
10759         /* Include "unknown interface" ip6_mib */
10760         ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10761         ipst->ips_ip6_mib.ipIfStatsIfIndex =
10762             MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10763         SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10764             ipst->ips_ipv6_forwarding ? 1 : 2);
10765         SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10766             ipst->ips_ipv6_def_hops);
10767         SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10768             sizeof (mib2_ipIfStatsEntry_t));
10769         SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10770             sizeof (mib2_ipv6AddrEntry_t));
10771         SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10772             sizeof (mib2_ipv6RouteEntry_t));
10773         SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10774             sizeof (mib2_ipv6NetToMediaEntry_t));
10775         SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10776             sizeof (ipv6_member_t));
10777         SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10778             sizeof (ipv6_grpsrc_t));
10779 
10780         /*
10781          * Synchronize 64- and 32-bit counters
10782          */
10783         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10784             ipIfStatsHCInReceives);
10785         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10786             ipIfStatsHCInDelivers);
10787         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10788             ipIfStatsHCOutRequests);
10789         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10790             ipIfStatsHCOutForwDatagrams);
10791         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10792             ipIfStatsHCOutMcastPkts);
10793         SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10794             ipIfStatsHCInMcastPkts);
10795 
10796         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10797             (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10798                 ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10799                     (uint_t)ise_size));
10800         } else if (legacy_req) {
10801                 /* Adjust the EntrySize fields for legacy requests. */
10802                 ise =
10803                     (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10804                 SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10805                 SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10806         }
10807 
10808         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10809         ill = ILL_START_WALK_V6(&ctx, ipst);
10810         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10811                 ill->ill_ip_mib->ipIfStatsIfIndex =
10812                     ill->ill_phyint->phyint_ifindex;
10813                 SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10814                     ipst->ips_ipv6_forwarding ? 1 : 2);
10815                 SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10816                     ill->ill_max_hops);
10817 
10818                 /*
10819                  * Synchronize 64- and 32-bit counters
10820                  */
10821                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10822                     ipIfStatsHCInReceives);
10823                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10824                     ipIfStatsHCInDelivers);
10825                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10826                     ipIfStatsHCOutRequests);
10827                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10828                     ipIfStatsHCOutForwDatagrams);
10829                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10830                     ipIfStatsHCOutMcastPkts);
10831                 SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10832                     ipIfStatsHCInMcastPkts);
10833 
10834                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10835                     (char *)ill->ill_ip_mib, (int)ise_size)) {
10836                         ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10837                         "%u bytes\n", (uint_t)ise_size));
10838                 } else if (legacy_req) {
10839                         /* Adjust the EntrySize fields for legacy requests. */
10840                         ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10841                             (int)ise_size);
10842                         SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10843                         SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10844                 }
10845         }
10846         rw_exit(&ipst->ips_ill_g_lock);
10847 
10848         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10849         ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10850             (int)optp->level, (int)optp->name, (int)optp->len));
10851         qreply(q, mpctl);
10852         return (mp2ctl);
10853 }
10854 
10855 /*
10856  * ICMPv6 mib: One per ill
10857  */
10858 static mblk_t *
10859 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10860 {
10861         struct opthdr           *optp;
10862         mblk_t                  *mp2ctl;
10863         ill_t                   *ill;
10864         ill_walk_context_t      ctx;
10865         mblk_t                  *mp_tail = NULL;
10866         /*
10867          * Make a copy of the original message
10868          */
10869         mp2ctl = copymsg(mpctl);
10870 
10871         /* fixed length ICMPv6 structure ... */
10872 
10873         optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10874         optp->level = MIB2_ICMP6;
10875         optp->name = 0;
10876         /* Include "unknown interface" icmp6_mib */
10877         ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10878             MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10879         ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10880             sizeof (mib2_ipv6IfIcmpEntry_t);
10881         if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10882             (char *)&ipst->ips_icmp6_mib,
10883             (int)sizeof (ipst->ips_icmp6_mib))) {
10884                 ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10885                     (uint_t)sizeof (ipst->ips_icmp6_mib)));
10886         }
10887 
10888         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10889         ill = ILL_START_WALK_V6(&ctx, ipst);
10890         for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10891                 ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10892                     ill->ill_phyint->phyint_ifindex;
10893                 if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10894                     (char *)ill->ill_icmp6_mib,
10895                     (int)sizeof (*ill->ill_icmp6_mib))) {
10896                         ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10897                             "%u bytes\n",
10898                             (uint_t)sizeof (*ill->ill_icmp6_mib)));
10899                 }
10900         }
10901         rw_exit(&ipst->ips_ill_g_lock);
10902 
10903         optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10904         ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10905             (int)optp->level, (int)optp->name, (int)optp->len));
10906         qreply(q, mpctl);
10907         return (mp2ctl);
10908 }
10909 
10910 /*
10911  * ire_walk routine to create both ipRouteEntryTable and
10912  * ipRouteAttributeTable in one IRE walk
10913  */
10914 static void
10915 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10916 {
10917         ill_t                           *ill;
10918         mib2_ipRouteEntry_t             *re;
10919         mib2_ipAttributeEntry_t         iaes;
10920         tsol_ire_gw_secattr_t           *attrp;
10921         tsol_gc_t                       *gc = NULL;
10922         tsol_gcgrp_t                    *gcgrp = NULL;
10923         ip_stack_t                      *ipst = ire->ire_ipst;
10924 
10925         ASSERT(ire->ire_ipversion == IPV4_VERSION);
10926 
10927         if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10928                 if (ire->ire_testhidden)
10929                         return;
10930                 if (ire->ire_type & IRE_IF_CLONE)
10931                         return;
10932         }
10933 
10934         if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10935                 return;
10936 
10937         if ((attrp = ire->ire_gw_secattr) != NULL) {
10938                 mutex_enter(&attrp->igsa_lock);
10939                 if ((gc = attrp->igsa_gc) != NULL) {
10940                         gcgrp = gc->gc_grp;
10941                         ASSERT(gcgrp != NULL);
10942                         rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10943                 }
10944                 mutex_exit(&attrp->igsa_lock);
10945         }
10946         /*
10947          * Return all IRE types for route table... let caller pick and choose
10948          */
10949         re->ipRouteDest = ire->ire_addr;
10950         ill = ire->ire_ill;
10951         re->ipRouteIfIndex.o_length = 0;
10952         if (ill != NULL) {
10953                 ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10954                 re->ipRouteIfIndex.o_length =
10955                     mi_strlen(re->ipRouteIfIndex.o_bytes);
10956         }
10957         re->ipRouteMetric1 = -1;
10958         re->ipRouteMetric2 = -1;
10959         re->ipRouteMetric3 = -1;
10960         re->ipRouteMetric4 = -1;
10961 
10962         re->ipRouteNextHop = ire->ire_gateway_addr;
10963         /* indirect(4), direct(3), or invalid(2) */
10964         if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10965                 re->ipRouteType = 2;
10966         else if (ire->ire_type & IRE_ONLINK)
10967                 re->ipRouteType = 3;
10968         else
10969                 re->ipRouteType = 4;
10970 
10971         re->ipRouteProto = -1;
10972         re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10973         re->ipRouteMask = ire->ire_mask;
10974         re->ipRouteMetric5 = -1;
10975         re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10976         if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10977                 re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10978 
10979         re->ipRouteInfo.re_frag_flag = 0;
10980         re->ipRouteInfo.re_rtt               = 0;
10981         re->ipRouteInfo.re_src_addr  = 0;
10982         re->ipRouteInfo.re_ref               = ire->ire_refcnt;
10983         re->ipRouteInfo.re_obpkt     = ire->ire_ob_pkt_count;
10984         re->ipRouteInfo.re_ibpkt     = ire->ire_ib_pkt_count;
10985         re->ipRouteInfo.re_flags     = ire->ire_flags;
10986 
10987         /* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10988         if (ire->ire_type & IRE_INTERFACE) {
10989                 ire_t *child;
10990 
10991                 rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10992                 child = ire->ire_dep_children;
10993                 while (child != NULL) {
10994                         re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10995                         re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10996                         child = child->ire_dep_sib_next;
10997                 }
10998                 rw_exit(&ipst->ips_ire_dep_lock);
10999         }
11000 
11001         if (ire->ire_flags & RTF_DYNAMIC) {
11002                 re->ipRouteInfo.re_ire_type  = IRE_HOST_REDIRECT;
11003         } else {
11004                 re->ipRouteInfo.re_ire_type  = ire->ire_type;
11005         }
11006 
11007         if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11008             (char *)re, (int)sizeof (*re))) {
11009                 ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11010                     (uint_t)sizeof (*re)));
11011         }
11012 
11013         if (gc != NULL) {
11014                 iaes.iae_routeidx = ird->ird_idx;
11015                 iaes.iae_doi = gc->gc_db->gcdb_doi;
11016                 iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11017 
11018                 if (!snmp_append_data2(ird->ird_attrs.lp_head,
11019                     &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11020                         ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11021                             "bytes\n", (uint_t)sizeof (iaes)));
11022                 }
11023         }
11024 
11025         /* bump route index for next pass */
11026         ird->ird_idx++;
11027 
11028         kmem_free(re, sizeof (*re));
11029         if (gcgrp != NULL)
11030                 rw_exit(&gcgrp->gcgrp_rwlock);
11031 }
11032 
11033 /*
11034  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11035  */
11036 static void
11037 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11038 {
11039         ill_t                           *ill;
11040         mib2_ipv6RouteEntry_t           *re;
11041         mib2_ipAttributeEntry_t         iaes;
11042         tsol_ire_gw_secattr_t           *attrp;
11043         tsol_gc_t                       *gc = NULL;
11044         tsol_gcgrp_t                    *gcgrp = NULL;
11045         ip_stack_t                      *ipst = ire->ire_ipst;
11046 
11047         ASSERT(ire->ire_ipversion == IPV6_VERSION);
11048 
11049         if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11050                 if (ire->ire_testhidden)
11051                         return;
11052                 if (ire->ire_type & IRE_IF_CLONE)
11053                         return;
11054         }
11055 
11056         if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11057                 return;
11058 
11059         if ((attrp = ire->ire_gw_secattr) != NULL) {
11060                 mutex_enter(&attrp->igsa_lock);
11061                 if ((gc = attrp->igsa_gc) != NULL) {
11062                         gcgrp = gc->gc_grp;
11063                         ASSERT(gcgrp != NULL);
11064                         rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11065                 }
11066                 mutex_exit(&attrp->igsa_lock);
11067         }
11068         /*
11069          * Return all IRE types for route table... let caller pick and choose
11070          */
11071         re->ipv6RouteDest = ire->ire_addr_v6;
11072         re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11073         re->ipv6RouteIndex = 0;      /* Unique when multiple with same dest/plen */
11074         re->ipv6RouteIfIndex.o_length = 0;
11075         ill = ire->ire_ill;
11076         if (ill != NULL) {
11077                 ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11078                 re->ipv6RouteIfIndex.o_length =
11079                     mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11080         }
11081 
11082         ASSERT(!(ire->ire_type & IRE_BROADCAST));
11083 
11084         mutex_enter(&ire->ire_lock);
11085         re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11086         mutex_exit(&ire->ire_lock);
11087 
11088         /* remote(4), local(3), or discard(2) */
11089         if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11090                 re->ipv6RouteType = 2;
11091         else if (ire->ire_type & IRE_ONLINK)
11092                 re->ipv6RouteType = 3;
11093         else
11094                 re->ipv6RouteType = 4;
11095 
11096         re->ipv6RouteProtocol        = -1;
11097         re->ipv6RoutePolicy  = 0;
11098         re->ipv6RouteAge     = gethrestime_sec() - ire->ire_create_time;
11099         re->ipv6RouteNextHopRDI      = 0;
11100         re->ipv6RouteWeight  = 0;
11101         re->ipv6RouteMetric  = 0;
11102         re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11103         if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11104                 re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11105 
11106         re->ipv6RouteInfo.re_frag_flag       = 0;
11107         re->ipv6RouteInfo.re_rtt     = 0;
11108         re->ipv6RouteInfo.re_src_addr        = ipv6_all_zeros;
11109         re->ipv6RouteInfo.re_obpkt   = ire->ire_ob_pkt_count;
11110         re->ipv6RouteInfo.re_ibpkt   = ire->ire_ib_pkt_count;
11111         re->ipv6RouteInfo.re_ref     = ire->ire_refcnt;
11112         re->ipv6RouteInfo.re_flags   = ire->ire_flags;
11113 
11114         /* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11115         if (ire->ire_type & IRE_INTERFACE) {
11116                 ire_t *child;
11117 
11118                 rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11119                 child = ire->ire_dep_children;
11120                 while (child != NULL) {
11121                         re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11122                         re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11123                         child = child->ire_dep_sib_next;
11124                 }
11125                 rw_exit(&ipst->ips_ire_dep_lock);
11126         }
11127         if (ire->ire_flags & RTF_DYNAMIC) {
11128                 re->ipv6RouteInfo.re_ire_type        = IRE_HOST_REDIRECT;
11129         } else {
11130                 re->ipv6RouteInfo.re_ire_type        = ire->ire_type;
11131         }
11132 
11133         if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11134             (char *)re, (int)sizeof (*re))) {
11135                 ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11136                     (uint_t)sizeof (*re)));
11137         }
11138 
11139         if (gc != NULL) {
11140                 iaes.iae_routeidx = ird->ird_idx;
11141                 iaes.iae_doi = gc->gc_db->gcdb_doi;
11142                 iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11143 
11144                 if (!snmp_append_data2(ird->ird_attrs.lp_head,
11145                     &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11146                         ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11147                             "bytes\n", (uint_t)sizeof (iaes)));
11148                 }
11149         }
11150 
11151         /* bump route index for next pass */
11152         ird->ird_idx++;
11153 
11154         kmem_free(re, sizeof (*re));
11155         if (gcgrp != NULL)
11156                 rw_exit(&gcgrp->gcgrp_rwlock);
11157 }
11158 
11159 /*
11160  * ncec_walk routine to create ipv6NetToMediaEntryTable
11161  */
11162 static int
11163 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11164 {
11165         ill_t                           *ill;
11166         mib2_ipv6NetToMediaEntry_t      ntme;
11167 
11168         ill = ncec->ncec_ill;
11169         /* skip arpce entries, and loopback ncec entries */
11170         if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11171                 return (0);
11172         /*
11173          * Neighbor cache entry attached to IRE with on-link
11174          * destination.
11175          * We report all IPMP groups on ncec_ill which is normally the upper.
11176          */
11177         ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11178         ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11179         ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11180         if (ncec->ncec_lladdr != NULL) {
11181                 bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11182                     ntme.ipv6NetToMediaPhysAddress.o_length);
11183         }
11184         /*
11185          * Note: Returns ND_* states. Should be:
11186          * reachable(1), stale(2), delay(3), probe(4),
11187          * invalid(5), unknown(6)
11188          */
11189         ntme.ipv6NetToMediaState = ncec->ncec_state;
11190         ntme.ipv6NetToMediaLastUpdated = 0;
11191 
11192         /* other(1), dynamic(2), static(3), local(4) */
11193         if (NCE_MYADDR(ncec)) {
11194                 ntme.ipv6NetToMediaType = 4;
11195         } else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11196                 ntme.ipv6NetToMediaType = 1; /* proxy */
11197         } else if (ncec->ncec_flags & NCE_F_STATIC) {
11198                 ntme.ipv6NetToMediaType = 3;
11199         } else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11200                 ntme.ipv6NetToMediaType = 1;
11201         } else {
11202                 ntme.ipv6NetToMediaType = 2;
11203         }
11204 
11205         if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11206             &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11207                 ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11208                     (uint_t)sizeof (ntme)));
11209         }
11210         return (0);
11211 }
11212 
11213 int
11214 nce2ace(ncec_t *ncec)
11215 {
11216         int flags = 0;
11217 
11218         if (NCE_ISREACHABLE(ncec))
11219                 flags |= ACE_F_RESOLVED;
11220         if (ncec->ncec_flags & NCE_F_AUTHORITY)
11221                 flags |= ACE_F_AUTHORITY;
11222         if (ncec->ncec_flags & NCE_F_PUBLISH)
11223                 flags |= ACE_F_PUBLISH;
11224         if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11225                 flags |= ACE_F_PERMANENT;
11226         if (NCE_MYADDR(ncec))
11227                 flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11228         if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11229                 flags |= ACE_F_UNVERIFIED;
11230         if (ncec->ncec_flags & NCE_F_AUTHORITY)
11231                 flags |= ACE_F_AUTHORITY;
11232         if (ncec->ncec_flags & NCE_F_DELAYED)
11233                 flags |= ACE_F_DELAYED;
11234         return (flags);
11235 }
11236 
11237 /*
11238  * ncec_walk routine to create ipNetToMediaEntryTable
11239  */
11240 static int
11241 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11242 {
11243         ill_t                           *ill;
11244         mib2_ipNetToMediaEntry_t        ntme;
11245         const char                      *name = "unknown";
11246         ipaddr_t                        ncec_addr;
11247 
11248         ill = ncec->ncec_ill;
11249         if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11250             ill->ill_net_type == IRE_LOOPBACK)
11251                 return (0);
11252 
11253         /* We report all IPMP groups on ncec_ill which is normally the upper. */
11254         name = ill->ill_name;
11255         /* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11256         if (NCE_MYADDR(ncec)) {
11257                 ntme.ipNetToMediaType = 4;
11258         } else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11259                 ntme.ipNetToMediaType = 1;
11260         } else {
11261                 ntme.ipNetToMediaType = 3;
11262         }
11263         ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11264         bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11265             ntme.ipNetToMediaIfIndex.o_length);
11266 
11267         IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11268         bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11269 
11270         ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11271         ncec_addr = INADDR_BROADCAST;
11272         bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11273             sizeof (ncec_addr));
11274         /*
11275          * map all the flags to the ACE counterpart.
11276          */
11277         ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11278 
11279         ntme.ipNetToMediaPhysAddress.o_length =
11280             MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11281 
11282         if (!NCE_ISREACHABLE(ncec))
11283                 ntme.ipNetToMediaPhysAddress.o_length = 0;
11284         else {
11285                 if (ncec->ncec_lladdr != NULL) {
11286                         bcopy(ncec->ncec_lladdr,
11287                             ntme.ipNetToMediaPhysAddress.o_bytes,
11288                             ntme.ipNetToMediaPhysAddress.o_length);
11289                 }
11290         }
11291 
11292         if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11293             &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11294                 ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11295                     (uint_t)sizeof (ntme)));
11296         }
11297         return (0);
11298 }
11299 
11300 /*
11301  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11302  */
11303 /* ARGSUSED */
11304 int
11305 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11306 {
11307         switch (level) {
11308         case MIB2_IP:
11309         case MIB2_ICMP:
11310                 switch (name) {
11311                 default:
11312                         break;
11313                 }
11314                 return (1);
11315         default:
11316                 return (1);
11317         }
11318 }
11319 
11320 /*
11321  * When there exists both a 64- and 32-bit counter of a particular type
11322  * (i.e., InReceives), only the 64-bit counters are added.
11323  */
11324 void
11325 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11326 {
11327         UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11328         UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11329         UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11330         UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11331         UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11332         UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11333         UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11334         UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11335         UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11336         UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11337         UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11338         UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11339         UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11340         UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11341         UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11342         UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11343         UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11344         UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11345         UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11346         UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11347         UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11348         UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11349             o2->ipIfStatsInWrongIPVersion);
11350         UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11351             o2->ipIfStatsInWrongIPVersion);
11352         UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11353             o2->ipIfStatsOutSwitchIPVersion);
11354         UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11355         UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11356         UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11357             o2->ipIfStatsHCInForwDatagrams);
11358         UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11359         UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11360         UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11361             o2->ipIfStatsHCOutForwDatagrams);
11362         UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11363         UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11364         UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11365         UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11366         UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11367         UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11368         UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11369             o2->ipIfStatsHCOutMcastOctets);
11370         UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11371         UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11372         UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11373         UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11374         UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11375         UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11376         UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11377 }
11378 
11379 void
11380 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11381 {
11382         UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11383         UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11384         UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11385         UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11386         UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11387         UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11388         UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11389         UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11390         UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11391         UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11392             o2->ipv6IfIcmpInRouterSolicits);
11393         UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11394             o2->ipv6IfIcmpInRouterAdvertisements);
11395         UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11396             o2->ipv6IfIcmpInNeighborSolicits);
11397         UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11398             o2->ipv6IfIcmpInNeighborAdvertisements);
11399         UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11400         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11401             o2->ipv6IfIcmpInGroupMembQueries);
11402         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11403             o2->ipv6IfIcmpInGroupMembResponses);
11404         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11405             o2->ipv6IfIcmpInGroupMembReductions);
11406         UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11407         UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11408         UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11409             o2->ipv6IfIcmpOutDestUnreachs);
11410         UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11411             o2->ipv6IfIcmpOutAdminProhibs);
11412         UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11413         UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11414             o2->ipv6IfIcmpOutParmProblems);
11415         UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11416         UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11417         UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11418         UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11419             o2->ipv6IfIcmpOutRouterSolicits);
11420         UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11421             o2->ipv6IfIcmpOutRouterAdvertisements);
11422         UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11423             o2->ipv6IfIcmpOutNeighborSolicits);
11424         UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11425             o2->ipv6IfIcmpOutNeighborAdvertisements);
11426         UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11427         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11428             o2->ipv6IfIcmpOutGroupMembQueries);
11429         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11430             o2->ipv6IfIcmpOutGroupMembResponses);
11431         UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11432             o2->ipv6IfIcmpOutGroupMembReductions);
11433         UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11434         UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11435         UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11436             o2->ipv6IfIcmpInBadNeighborAdvertisements);
11437         UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11438             o2->ipv6IfIcmpInBadNeighborSolicitations);
11439         UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11440         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11441             o2->ipv6IfIcmpInGroupMembTotal);
11442         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11443             o2->ipv6IfIcmpInGroupMembBadQueries);
11444         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11445             o2->ipv6IfIcmpInGroupMembBadReports);
11446         UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11447             o2->ipv6IfIcmpInGroupMembOurReports);
11448 }
11449 
11450 /*
11451  * Called before the options are updated to check if this packet will
11452  * be source routed from here.
11453  * This routine assumes that the options are well formed i.e. that they
11454  * have already been checked.
11455  */
11456 boolean_t
11457 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11458 {
11459         ipoptp_t        opts;
11460         uchar_t         *opt;
11461         uint8_t         optval;
11462         uint8_t         optlen;
11463         ipaddr_t        dst;
11464 
11465         if (IS_SIMPLE_IPH(ipha)) {
11466                 ip2dbg(("not source routed\n"));
11467                 return (B_FALSE);
11468         }
11469         dst = ipha->ipha_dst;
11470         for (optval = ipoptp_first(&opts, ipha);
11471             optval != IPOPT_EOL;
11472             optval = ipoptp_next(&opts)) {
11473                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11474                 opt = opts.ipoptp_cur;
11475                 optlen = opts.ipoptp_len;
11476                 ip2dbg(("ip_source_routed: opt %d, len %d\n",
11477                     optval, optlen));
11478                 switch (optval) {
11479                         uint32_t off;
11480                 case IPOPT_SSRR:
11481                 case IPOPT_LSRR:
11482                         /*
11483                          * If dst is one of our addresses and there are some
11484                          * entries left in the source route return (true).
11485                          */
11486                         if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11487                                 ip2dbg(("ip_source_routed: not next"
11488                                     " source route 0x%x\n",
11489                                     ntohl(dst)));
11490                                 return (B_FALSE);
11491                         }
11492                         off = opt[IPOPT_OFFSET];
11493                         off--;
11494                         if (optlen < IP_ADDR_LEN ||
11495                             off > optlen - IP_ADDR_LEN) {
11496                                 /* End of source route */
11497                                 ip1dbg(("ip_source_routed: end of SR\n"));
11498                                 return (B_FALSE);
11499                         }
11500                         return (B_TRUE);
11501                 }
11502         }
11503         ip2dbg(("not source routed\n"));
11504         return (B_FALSE);
11505 }
11506 
11507 /*
11508  * ip_unbind is called by the transports to remove a conn from
11509  * the fanout table.
11510  */
11511 void
11512 ip_unbind(conn_t *connp)
11513 {
11514 
11515         ASSERT(!MUTEX_HELD(&connp->conn_lock));
11516 
11517         if (is_system_labeled() && connp->conn_anon_port) {
11518                 (void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11519                     connp->conn_mlp_type, connp->conn_proto,
11520                     ntohs(connp->conn_lport), B_FALSE);
11521                 connp->conn_anon_port = 0;
11522         }
11523         connp->conn_mlp_type = mlptSingle;
11524 
11525         ipcl_hash_remove(connp);
11526 }
11527 
11528 /*
11529  * Used for deciding the MSS size for the upper layer. Thus
11530  * we need to check the outbound policy values in the conn.
11531  */
11532 int
11533 conn_ipsec_length(conn_t *connp)
11534 {
11535         ipsec_latch_t *ipl;
11536 
11537         ipl = connp->conn_latch;
11538         if (ipl == NULL)
11539                 return (0);
11540 
11541         if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11542                 return (0);
11543 
11544         return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11545 }
11546 
11547 /*
11548  * Returns an estimate of the IPsec headers size. This is used if
11549  * we don't want to call into IPsec to get the exact size.
11550  */
11551 int
11552 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11553 {
11554         ipsec_action_t *a;
11555 
11556         if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11557                 return (0);
11558 
11559         a = ixa->ixa_ipsec_action;
11560         if (a == NULL) {
11561                 ASSERT(ixa->ixa_ipsec_policy != NULL);
11562                 a = ixa->ixa_ipsec_policy->ipsp_act;
11563         }
11564         ASSERT(a != NULL);
11565 
11566         return (a->ipa_ovhd);
11567 }
11568 
11569 /*
11570  * If there are any source route options, return the true final
11571  * destination. Otherwise, return the destination.
11572  */
11573 ipaddr_t
11574 ip_get_dst(ipha_t *ipha)
11575 {
11576         ipoptp_t        opts;
11577         uchar_t         *opt;
11578         uint8_t         optval;
11579         uint8_t         optlen;
11580         ipaddr_t        dst;
11581         uint32_t off;
11582 
11583         dst = ipha->ipha_dst;
11584 
11585         if (IS_SIMPLE_IPH(ipha))
11586                 return (dst);
11587 
11588         for (optval = ipoptp_first(&opts, ipha);
11589             optval != IPOPT_EOL;
11590             optval = ipoptp_next(&opts)) {
11591                 opt = opts.ipoptp_cur;
11592                 optlen = opts.ipoptp_len;
11593                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11594                 switch (optval) {
11595                 case IPOPT_SSRR:
11596                 case IPOPT_LSRR:
11597                         off = opt[IPOPT_OFFSET];
11598                         /*
11599                          * If one of the conditions is true, it means
11600                          * end of options and dst already has the right
11601                          * value.
11602                          */
11603                         if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11604                                 off = optlen - IP_ADDR_LEN;
11605                                 bcopy(&opt[off], &dst, IP_ADDR_LEN);
11606                         }
11607                         return (dst);
11608                 default:
11609                         break;
11610                 }
11611         }
11612 
11613         return (dst);
11614 }
11615 
11616 /*
11617  * Outbound IP fragmentation routine.
11618  * Assumes the caller has checked whether or not fragmentation should
11619  * be allowed. Here we copy the DF bit from the header to all the generated
11620  * fragments.
11621  */
11622 int
11623 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11624     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11625     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11626 {
11627         int             i1;
11628         int             hdr_len;
11629         mblk_t          *hdr_mp;
11630         ipha_t          *ipha;
11631         int             ip_data_end;
11632         int             len;
11633         mblk_t          *mp = mp_orig;
11634         int             offset;
11635         ill_t           *ill = nce->nce_ill;
11636         ip_stack_t      *ipst = ill->ill_ipst;
11637         mblk_t          *carve_mp;
11638         uint32_t        frag_flag;
11639         uint_t          priority = mp->b_band;
11640         int             error = 0;
11641 
11642         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11643 
11644         if (pkt_len != msgdsize(mp)) {
11645                 ip0dbg(("Packet length mismatch: %d, %ld\n",
11646                     pkt_len, msgdsize(mp)));
11647                 freemsg(mp);
11648                 return (EINVAL);
11649         }
11650 
11651         if (max_frag == 0) {
11652                 ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11653                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11654                 ip_drop_output("FragFails: zero max_frag", mp, ill);
11655                 freemsg(mp);
11656                 return (EINVAL);
11657         }
11658 
11659         ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11660         ipha = (ipha_t *)mp->b_rptr;
11661         ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11662         frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11663 
11664         /*
11665          * Establish the starting offset.  May not be zero if we are fragging
11666          * a fragment that is being forwarded.
11667          */
11668         offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11669 
11670         /* TODO why is this test needed? */
11671         if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11672                 /* TODO: notify ulp somehow */
11673                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11674                 ip_drop_output("FragFails: bad starting offset", mp, ill);
11675                 freemsg(mp);
11676                 return (EINVAL);
11677         }
11678 
11679         hdr_len = IPH_HDR_LENGTH(ipha);
11680         ipha->ipha_hdr_checksum = 0;
11681 
11682         /*
11683          * Establish the number of bytes maximum per frag, after putting
11684          * in the header.
11685          */
11686         len = (max_frag - hdr_len) & ~7;
11687 
11688         /* Get a copy of the header for the trailing frags */
11689         hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11690             mp);
11691         if (hdr_mp == NULL) {
11692                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11693                 ip_drop_output("FragFails: no hdr_mp", mp, ill);
11694                 freemsg(mp);
11695                 return (ENOBUFS);
11696         }
11697 
11698         /* Store the starting offset, with the MoreFrags flag. */
11699         i1 = offset | IPH_MF | frag_flag;
11700         ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11701 
11702         /* Establish the ending byte offset, based on the starting offset. */
11703         offset <<= 3;
11704         ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11705 
11706         /* Store the length of the first fragment in the IP header. */
11707         i1 = len + hdr_len;
11708         ASSERT(i1 <= IP_MAXPACKET);
11709         ipha->ipha_length = htons((uint16_t)i1);
11710 
11711         /*
11712          * Compute the IP header checksum for the first frag.  We have to
11713          * watch out that we stop at the end of the header.
11714          */
11715         ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11716 
11717         /*
11718          * Now carve off the first frag.  Note that this will include the
11719          * original IP header.
11720          */
11721         if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11722                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11723                 ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11724                 freeb(hdr_mp);
11725                 freemsg(mp_orig);
11726                 return (ENOBUFS);
11727         }
11728 
11729         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11730 
11731         error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11732             ixa_cookie);
11733         if (error != 0 && error != EWOULDBLOCK) {
11734                 /* No point in sending the other fragments */
11735                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11736                 ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11737                 freeb(hdr_mp);
11738                 freemsg(mp_orig);
11739                 return (error);
11740         }
11741 
11742         /* No need to redo state machine in loop */
11743         ixaflags &= ~IXAF_REACH_CONF;
11744 
11745         /* Advance the offset to the second frag starting point. */
11746         offset += len;
11747         /*
11748          * Update hdr_len from the copied header - there might be less options
11749          * in the later fragments.
11750          */
11751         hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11752         /* Loop until done. */
11753         for (;;) {
11754                 uint16_t        offset_and_flags;
11755                 uint16_t        ip_len;
11756 
11757                 if (ip_data_end - offset > len) {
11758                         /*
11759                          * Carve off the appropriate amount from the original
11760                          * datagram.
11761                          */
11762                         if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11763                                 mp = NULL;
11764                                 break;
11765                         }
11766                         /*
11767                          * More frags after this one.  Get another copy
11768                          * of the header.
11769                          */
11770                         if (carve_mp->b_datap->db_ref == 1 &&
11771                             hdr_mp->b_wptr - hdr_mp->b_rptr <
11772                             carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11773                                 /* Inline IP header */
11774                                 carve_mp->b_rptr -= hdr_mp->b_wptr -
11775                                     hdr_mp->b_rptr;
11776                                 bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11777                                     hdr_mp->b_wptr - hdr_mp->b_rptr);
11778                                 mp = carve_mp;
11779                         } else {
11780                                 if (!(mp = copyb(hdr_mp))) {
11781                                         freemsg(carve_mp);
11782                                         break;
11783                                 }
11784                                 /* Get priority marking, if any. */
11785                                 mp->b_band = priority;
11786                                 mp->b_cont = carve_mp;
11787                         }
11788                         ipha = (ipha_t *)mp->b_rptr;
11789                         offset_and_flags = IPH_MF;
11790                 } else {
11791                         /*
11792                          * Last frag.  Consume the header. Set len to
11793                          * the length of this last piece.
11794                          */
11795                         len = ip_data_end - offset;
11796 
11797                         /*
11798                          * Carve off the appropriate amount from the original
11799                          * datagram.
11800                          */
11801                         if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11802                                 mp = NULL;
11803                                 break;
11804                         }
11805                         if (carve_mp->b_datap->db_ref == 1 &&
11806                             hdr_mp->b_wptr - hdr_mp->b_rptr <
11807                             carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11808                                 /* Inline IP header */
11809                                 carve_mp->b_rptr -= hdr_mp->b_wptr -
11810                                     hdr_mp->b_rptr;
11811                                 bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11812                                     hdr_mp->b_wptr - hdr_mp->b_rptr);
11813                                 mp = carve_mp;
11814                                 freeb(hdr_mp);
11815                                 hdr_mp = mp;
11816                         } else {
11817                                 mp = hdr_mp;
11818                                 /* Get priority marking, if any. */
11819                                 mp->b_band = priority;
11820                                 mp->b_cont = carve_mp;
11821                         }
11822                         ipha = (ipha_t *)mp->b_rptr;
11823                         /* A frag of a frag might have IPH_MF non-zero */
11824                         offset_and_flags =
11825                             ntohs(ipha->ipha_fragment_offset_and_flags) &
11826                             IPH_MF;
11827                 }
11828                 offset_and_flags |= (uint16_t)(offset >> 3);
11829                 offset_and_flags |= (uint16_t)frag_flag;
11830                 /* Store the offset and flags in the IP header. */
11831                 ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11832 
11833                 /* Store the length in the IP header. */
11834                 ip_len = (uint16_t)(len + hdr_len);
11835                 ipha->ipha_length = htons(ip_len);
11836 
11837                 /*
11838                  * Set the IP header checksum.  Note that mp is just
11839                  * the header, so this is easy to pass to ip_csum.
11840                  */
11841                 ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11842 
11843                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11844 
11845                 error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11846                     nolzid, ixa_cookie);
11847                 /* All done if we just consumed the hdr_mp. */
11848                 if (mp == hdr_mp) {
11849                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11850                         return (error);
11851                 }
11852                 if (error != 0 && error != EWOULDBLOCK) {
11853                         DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11854                             mblk_t *, hdr_mp);
11855                         /* No point in sending the other fragments */
11856                         break;
11857                 }
11858 
11859                 /* Otherwise, advance and loop. */
11860                 offset += len;
11861         }
11862         /* Clean up following allocation failure. */
11863         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11864         ip_drop_output("FragFails: loop ended", NULL, ill);
11865         if (mp != hdr_mp)
11866                 freeb(hdr_mp);
11867         if (mp != mp_orig)
11868                 freemsg(mp_orig);
11869         return (error);
11870 }
11871 
11872 /*
11873  * Copy the header plus those options which have the copy bit set
11874  */
11875 static mblk_t *
11876 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11877     mblk_t *src)
11878 {
11879         mblk_t  *mp;
11880         uchar_t *up;
11881 
11882         /*
11883          * Quick check if we need to look for options without the copy bit
11884          * set
11885          */
11886         mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11887         if (!mp)
11888                 return (mp);
11889         mp->b_rptr += ipst->ips_ip_wroff_extra;
11890         if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11891                 bcopy(rptr, mp->b_rptr, hdr_len);
11892                 mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11893                 return (mp);
11894         }
11895         up  = mp->b_rptr;
11896         bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11897         up += IP_SIMPLE_HDR_LENGTH;
11898         rptr += IP_SIMPLE_HDR_LENGTH;
11899         hdr_len -= IP_SIMPLE_HDR_LENGTH;
11900         while (hdr_len > 0) {
11901                 uint32_t optval;
11902                 uint32_t optlen;
11903 
11904                 optval = *rptr;
11905                 if (optval == IPOPT_EOL)
11906                         break;
11907                 if (optval == IPOPT_NOP)
11908                         optlen = 1;
11909                 else
11910                         optlen = rptr[1];
11911                 if (optval & IPOPT_COPY) {
11912                         bcopy(rptr, up, optlen);
11913                         up += optlen;
11914                 }
11915                 rptr += optlen;
11916                 hdr_len -= optlen;
11917         }
11918         /*
11919          * Make sure that we drop an even number of words by filling
11920          * with EOL to the next word boundary.
11921          */
11922         for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11923             hdr_len & 0x3; hdr_len++)
11924                 *up++ = IPOPT_EOL;
11925         mp->b_wptr = up;
11926         /* Update header length */
11927         mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11928         return (mp);
11929 }
11930 
11931 /*
11932  * Update any source route, record route, or timestamp options when
11933  * sending a packet back to ourselves.
11934  * Check that we are at end of strict source route.
11935  * The options have been sanity checked by ip_output_options().
11936  */
11937 void
11938 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11939 {
11940         ipoptp_t        opts;
11941         uchar_t         *opt;
11942         uint8_t         optval;
11943         uint8_t         optlen;
11944         ipaddr_t        dst;
11945         uint32_t        ts;
11946         timestruc_t     now;
11947 
11948         for (optval = ipoptp_first(&opts, ipha);
11949             optval != IPOPT_EOL;
11950             optval = ipoptp_next(&opts)) {
11951                 opt = opts.ipoptp_cur;
11952                 optlen = opts.ipoptp_len;
11953                 ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11954                 switch (optval) {
11955                         uint32_t off;
11956                 case IPOPT_SSRR:
11957                 case IPOPT_LSRR:
11958                         off = opt[IPOPT_OFFSET];
11959                         off--;
11960                         if (optlen < IP_ADDR_LEN ||
11961                             off > optlen - IP_ADDR_LEN) {
11962                                 /* End of source route */
11963                                 break;
11964                         }
11965                         /*
11966                          * This will only happen if two consecutive entries
11967                          * in the source route contains our address or if
11968                          * it is a packet with a loose source route which
11969                          * reaches us before consuming the whole source route
11970                          */
11971 
11972                         if (optval == IPOPT_SSRR) {
11973                                 return;
11974                         }
11975                         /*
11976                          * Hack: instead of dropping the packet truncate the
11977                          * source route to what has been used by filling the
11978                          * rest with IPOPT_NOP.
11979                          */
11980                         opt[IPOPT_OLEN] = (uint8_t)off;
11981                         while (off < optlen) {
11982                                 opt[off++] = IPOPT_NOP;
11983                         }
11984                         break;
11985                 case IPOPT_RR:
11986                         off = opt[IPOPT_OFFSET];
11987                         off--;
11988                         if (optlen < IP_ADDR_LEN ||
11989                             off > optlen - IP_ADDR_LEN) {
11990                                 /* No more room - ignore */
11991                                 ip1dbg((
11992                                     "ip_output_local_options: end of RR\n"));
11993                                 break;
11994                         }
11995                         dst = htonl(INADDR_LOOPBACK);
11996                         bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11997                         opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11998                         break;
11999                 case IPOPT_TS:
12000                         /* Insert timestamp if there is romm */
12001                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12002                         case IPOPT_TS_TSONLY:
12003                                 off = IPOPT_TS_TIMELEN;
12004                                 break;
12005                         case IPOPT_TS_PRESPEC:
12006                         case IPOPT_TS_PRESPEC_RFC791:
12007                                 /* Verify that the address matched */
12008                                 off = opt[IPOPT_OFFSET] - 1;
12009                                 bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12010                                 if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12011                                         /* Not for us */
12012                                         break;
12013                                 }
12014                                 /* FALLTHRU */
12015                         case IPOPT_TS_TSANDADDR:
12016                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12017                                 break;
12018                         default:
12019                                 /*
12020                                  * ip_*put_options should have already
12021                                  * dropped this packet.
12022                                  */
12023                                 cmn_err(CE_PANIC, "ip_output_local_options: "
12024                                     "unknown IT - bug in ip_output_options?\n");
12025                                 return; /* Keep "lint" happy */
12026                         }
12027                         if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12028                                 /* Increase overflow counter */
12029                                 off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12030                                 opt[IPOPT_POS_OV_FLG] = (uint8_t)
12031                                     (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12032                                     (off << 4);
12033                                 break;
12034                         }
12035                         off = opt[IPOPT_OFFSET] - 1;
12036                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12037                         case IPOPT_TS_PRESPEC:
12038                         case IPOPT_TS_PRESPEC_RFC791:
12039                         case IPOPT_TS_TSANDADDR:
12040                                 dst = htonl(INADDR_LOOPBACK);
12041                                 bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12042                                 opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12043                                 /* FALLTHRU */
12044                         case IPOPT_TS_TSONLY:
12045                                 off = opt[IPOPT_OFFSET] - 1;
12046                                 /* Compute # of milliseconds since midnight */
12047                                 gethrestime(&now);
12048                                 ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12049                                     NSEC2MSEC(now.tv_nsec);
12050                                 bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12051                                 opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12052                                 break;
12053                         }
12054                         break;
12055                 }
12056         }
12057 }
12058 
12059 /*
12060  * Prepend an M_DATA fastpath header, and if none present prepend a
12061  * DL_UNITDATA_REQ. Frees the mblk on failure.
12062  *
12063  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12064  * If there is a change to them, the nce will be deleted (condemned) and
12065  * a new nce_t will be created when packets are sent. Thus we need no locks
12066  * to access those fields.
12067  *
12068  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12069  * we place b_band in dl_priority.dl_max.
12070  */
12071 static mblk_t *
12072 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12073 {
12074         uint_t  hlen;
12075         mblk_t *mp1;
12076         uint_t  priority;
12077         uchar_t *rptr;
12078 
12079         rptr = mp->b_rptr;
12080 
12081         ASSERT(DB_TYPE(mp) == M_DATA);
12082         priority = mp->b_band;
12083 
12084         ASSERT(nce != NULL);
12085         if ((mp1 = nce->nce_fp_mp) != NULL) {
12086                 hlen = MBLKL(mp1);
12087                 /*
12088                  * Check if we have enough room to prepend fastpath
12089                  * header
12090                  */
12091                 if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12092                         rptr -= hlen;
12093                         bcopy(mp1->b_rptr, rptr, hlen);
12094                         /*
12095                          * Set the b_rptr to the start of the link layer
12096                          * header
12097                          */
12098                         mp->b_rptr = rptr;
12099                         return (mp);
12100                 }
12101                 mp1 = copyb(mp1);
12102                 if (mp1 == NULL) {
12103                         ill_t *ill = nce->nce_ill;
12104 
12105                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12106                         ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12107                         freemsg(mp);
12108                         return (NULL);
12109                 }
12110                 mp1->b_band = priority;
12111                 mp1->b_cont = mp;
12112                 DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12113                 DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12114                 DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12115                 DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12116                 DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12117                 DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12118                 /*
12119                  * XXX disable ICK_VALID and compute checksum
12120                  * here; can happen if nce_fp_mp changes and
12121                  * it can't be copied now due to insufficient
12122                  * space. (unlikely, fp mp can change, but it
12123                  * does not increase in length)
12124                  */
12125                 return (mp1);
12126         }
12127         mp1 = copyb(nce->nce_dlur_mp);
12128 
12129         if (mp1 == NULL) {
12130                 ill_t *ill = nce->nce_ill;
12131 
12132                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12133                 ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12134                 freemsg(mp);
12135                 return (NULL);
12136         }
12137         mp1->b_cont = mp;
12138         if (priority != 0) {
12139                 mp1->b_band = priority;
12140                 ((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12141                     priority;
12142         }
12143         return (mp1);
12144 }
12145 
12146 /*
12147  * Finish the outbound IPsec processing. This function is called from
12148  * ipsec_out_process() if the IPsec packet was processed
12149  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12150  * asynchronously.
12151  *
12152  * This is common to IPv4 and IPv6.
12153  */
12154 int
12155 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12156 {
12157         iaflags_t       ixaflags = ixa->ixa_flags;
12158         uint_t          pktlen;
12159 
12160 
12161         /* AH/ESP don't update ixa_pktlen when they modify the packet */
12162         if (ixaflags & IXAF_IS_IPV4) {
12163                 ipha_t          *ipha = (ipha_t *)mp->b_rptr;
12164 
12165                 ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12166                 pktlen = ntohs(ipha->ipha_length);
12167         } else {
12168                 ip6_t           *ip6h = (ip6_t *)mp->b_rptr;
12169 
12170                 ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12171                 pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12172         }
12173 
12174         /*
12175          * We release any hard reference on the SAs here to make
12176          * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12177          * on the SAs.
12178          * If in the future we want the hard latching of the SAs in the
12179          * ip_xmit_attr_t then we should remove this.
12180          */
12181         if (ixa->ixa_ipsec_esp_sa != NULL) {
12182                 IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12183                 ixa->ixa_ipsec_esp_sa = NULL;
12184         }
12185         if (ixa->ixa_ipsec_ah_sa != NULL) {
12186                 IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12187                 ixa->ixa_ipsec_ah_sa = NULL;
12188         }
12189 
12190         /* Do we need to fragment? */
12191         if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12192             pktlen > ixa->ixa_fragsize) {
12193                 if (ixaflags & IXAF_IS_IPV4) {
12194                         ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12195                         /*
12196                          * We check for the DF case in ipsec_out_process
12197                          * hence this only handles the non-DF case.
12198                          */
12199                         return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12200                             pktlen, ixa->ixa_fragsize,
12201                             ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12202                             ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12203                             &ixa->ixa_cookie));
12204                 } else {
12205                         mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12206                         if (mp == NULL) {
12207                                 /* MIB and ip_drop_output already done */
12208                                 return (ENOMEM);
12209                         }
12210                         pktlen += sizeof (ip6_frag_t);
12211                         if (pktlen > ixa->ixa_fragsize) {
12212                                 return (ip_fragment_v6(mp, ixa->ixa_nce,
12213                                     ixa->ixa_flags, pktlen,
12214                                     ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12215                                     ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12216                                     ixa->ixa_postfragfn, &ixa->ixa_cookie));
12217                         }
12218                 }
12219         }
12220         return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12221             pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12222             ixa->ixa_no_loop_zoneid, NULL));
12223 }
12224 
12225 /*
12226  * Finish the inbound IPsec processing. This function is called from
12227  * ipsec_out_process() if the IPsec packet was processed
12228  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12229  * asynchronously.
12230  *
12231  * This is common to IPv4 and IPv6.
12232  */
12233 void
12234 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12235 {
12236         iaflags_t       iraflags = ira->ira_flags;
12237 
12238         /* Length might have changed */
12239         if (iraflags & IRAF_IS_IPV4) {
12240                 ipha_t          *ipha = (ipha_t *)mp->b_rptr;
12241 
12242                 ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12243                 ira->ira_pktlen = ntohs(ipha->ipha_length);
12244                 ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12245                 ira->ira_protocol = ipha->ipha_protocol;
12246 
12247                 ip_fanout_v4(mp, ipha, ira);
12248         } else {
12249                 ip6_t           *ip6h = (ip6_t *)mp->b_rptr;
12250                 uint8_t         *nexthdrp;
12251 
12252                 ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12253                 ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12254                 if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12255                     &nexthdrp)) {
12256                         /* Malformed packet */
12257                         BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12258                         ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12259                         freemsg(mp);
12260                         return;
12261                 }
12262                 ira->ira_protocol = *nexthdrp;
12263                 ip_fanout_v6(mp, ip6h, ira);
12264         }
12265 }
12266 
12267 /*
12268  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12269  *
12270  * If this function returns B_TRUE, the requested SA's have been filled
12271  * into the ixa_ipsec_*_sa pointers.
12272  *
12273  * If the function returns B_FALSE, the packet has been "consumed", most
12274  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12275  *
12276  * The SA references created by the protocol-specific "select"
12277  * function will be released in ip_output_post_ipsec.
12278  */
12279 static boolean_t
12280 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12281 {
12282         boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12283         ipsec_policy_t *pp;
12284         ipsec_action_t *ap;
12285 
12286         ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12287         ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12288             (ixa->ixa_ipsec_action != NULL));
12289 
12290         ap = ixa->ixa_ipsec_action;
12291         if (ap == NULL) {
12292                 pp = ixa->ixa_ipsec_policy;
12293                 ASSERT(pp != NULL);
12294                 ap = pp->ipsp_act;
12295                 ASSERT(ap != NULL);
12296         }
12297 
12298         /*
12299          * We have an action.  now, let's select SA's.
12300          * A side effect of setting ixa_ipsec_*_sa is that it will
12301          * be cached in the conn_t.
12302          */
12303         if (ap->ipa_want_esp) {
12304                 if (ixa->ixa_ipsec_esp_sa == NULL) {
12305                         need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12306                             IPPROTO_ESP);
12307                 }
12308                 ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12309         }
12310 
12311         if (ap->ipa_want_ah) {
12312                 if (ixa->ixa_ipsec_ah_sa == NULL) {
12313                         need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12314                             IPPROTO_AH);
12315                 }
12316                 ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12317                 /*
12318                  * The ESP and AH processing order needs to be preserved
12319                  * when both protocols are required (ESP should be applied
12320                  * before AH for an outbound packet). Force an ESP ACQUIRE
12321                  * when both ESP and AH are required, and an AH ACQUIRE
12322                  * is needed.
12323                  */
12324                 if (ap->ipa_want_esp && need_ah_acquire)
12325                         need_esp_acquire = B_TRUE;
12326         }
12327 
12328         /*
12329          * Send an ACQUIRE (extended, regular, or both) if we need one.
12330          * Release SAs that got referenced, but will not be used until we
12331          * acquire _all_ of the SAs we need.
12332          */
12333         if (need_ah_acquire || need_esp_acquire) {
12334                 if (ixa->ixa_ipsec_ah_sa != NULL) {
12335                         IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12336                         ixa->ixa_ipsec_ah_sa = NULL;
12337                 }
12338                 if (ixa->ixa_ipsec_esp_sa != NULL) {
12339                         IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12340                         ixa->ixa_ipsec_esp_sa = NULL;
12341                 }
12342 
12343                 sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12344                 return (B_FALSE);
12345         }
12346 
12347         return (B_TRUE);
12348 }
12349 
12350 /*
12351  * Handle IPsec output processing.
12352  * This function is only entered once for a given packet.
12353  * We try to do things synchronously, but if we need to have user-level
12354  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12355  * will be completed
12356  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12357  *  - when asynchronous ESP is done it will do AH
12358  *
12359  * In all cases we come back in ip_output_post_ipsec() to fragment and
12360  * send out the packet.
12361  */
12362 int
12363 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12364 {
12365         ill_t           *ill = ixa->ixa_nce->nce_ill;
12366         ip_stack_t      *ipst = ixa->ixa_ipst;
12367         ipsec_stack_t   *ipss;
12368         ipsec_policy_t  *pp;
12369         ipsec_action_t  *ap;
12370 
12371         ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12372 
12373         ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12374             (ixa->ixa_ipsec_action != NULL));
12375 
12376         ipss = ipst->ips_netstack->netstack_ipsec;
12377         if (!ipsec_loaded(ipss)) {
12378                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12379                 ip_drop_packet(mp, B_TRUE, ill,
12380                     DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12381                     &ipss->ipsec_dropper);
12382                 return (ENOTSUP);
12383         }
12384 
12385         ap = ixa->ixa_ipsec_action;
12386         if (ap == NULL) {
12387                 pp = ixa->ixa_ipsec_policy;
12388                 ASSERT(pp != NULL);
12389                 ap = pp->ipsp_act;
12390                 ASSERT(ap != NULL);
12391         }
12392 
12393         /* Handle explicit drop action and bypass. */
12394         switch (ap->ipa_act.ipa_type) {
12395         case IPSEC_ACT_DISCARD:
12396         case IPSEC_ACT_REJECT:
12397                 ip_drop_packet(mp, B_FALSE, ill,
12398                     DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12399                 return (EHOSTUNREACH);  /* IPsec policy failure */
12400         case IPSEC_ACT_BYPASS:
12401                 return (ip_output_post_ipsec(mp, ixa));
12402         }
12403 
12404         /*
12405          * The order of processing is first insert a IP header if needed.
12406          * Then insert the ESP header and then the AH header.
12407          */
12408         if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12409                 /*
12410                  * First get the outer IP header before sending
12411                  * it to ESP.
12412                  */
12413                 ipha_t *oipha, *iipha;
12414                 mblk_t *outer_mp, *inner_mp;
12415 
12416                 if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12417                         (void) mi_strlog(ill->ill_rq, 0,
12418                             SL_ERROR|SL_TRACE|SL_CONSOLE,
12419                             "ipsec_out_process: "
12420                             "Self-Encapsulation failed: Out of memory\n");
12421                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12422                         ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12423                         freemsg(mp);
12424                         return (ENOBUFS);
12425                 }
12426                 inner_mp = mp;
12427                 ASSERT(inner_mp->b_datap->db_type == M_DATA);
12428                 oipha = (ipha_t *)outer_mp->b_rptr;
12429                 iipha = (ipha_t *)inner_mp->b_rptr;
12430                 *oipha = *iipha;
12431                 outer_mp->b_wptr += sizeof (ipha_t);
12432                 oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12433                     sizeof (ipha_t));
12434                 oipha->ipha_protocol = IPPROTO_ENCAP;
12435                 oipha->ipha_version_and_hdr_length =
12436                     IP_SIMPLE_HDR_VERSION;
12437                 oipha->ipha_hdr_checksum = 0;
12438                 oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12439                 outer_mp->b_cont = inner_mp;
12440                 mp = outer_mp;
12441 
12442                 ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12443         }
12444 
12445         /* If we need to wait for a SA then we can't return any errno */
12446         if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12447             (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12448             !ipsec_out_select_sa(mp, ixa))
12449                 return (0);
12450 
12451         /*
12452          * By now, we know what SA's to use.  Toss over to ESP & AH
12453          * to do the heavy lifting.
12454          */
12455         if (ap->ipa_want_esp) {
12456                 ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12457 
12458                 mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12459                 if (mp == NULL) {
12460                         /*
12461                          * Either it failed or is pending. In the former case
12462                          * ipIfStatsInDiscards was increased.
12463                          */
12464                         return (0);
12465                 }
12466         }
12467 
12468         if (ap->ipa_want_ah) {
12469                 ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12470 
12471                 mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12472                 if (mp == NULL) {
12473                         /*
12474                          * Either it failed or is pending. In the former case
12475                          * ipIfStatsInDiscards was increased.
12476                          */
12477                         return (0);
12478                 }
12479         }
12480         /*
12481          * We are done with IPsec processing. Send it over
12482          * the wire.
12483          */
12484         return (ip_output_post_ipsec(mp, ixa));
12485 }
12486 
12487 /*
12488  * ioctls that go through a down/up sequence may need to wait for the down
12489  * to complete. This involves waiting for the ire and ipif refcnts to go down
12490  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12491  */
12492 /* ARGSUSED */
12493 void
12494 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12495 {
12496         struct iocblk *iocp;
12497         mblk_t *mp1;
12498         ip_ioctl_cmd_t *ipip;
12499         int err;
12500         sin_t   *sin;
12501         struct lifreq *lifr;
12502         struct ifreq *ifr;
12503 
12504         iocp = (struct iocblk *)mp->b_rptr;
12505         ASSERT(ipsq != NULL);
12506         /* Existence of mp1 verified in ip_wput_nondata */
12507         mp1 = mp->b_cont->b_cont;
12508         ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12509         if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12510                 /*
12511                  * Special case where ipx_current_ipif is not set:
12512                  * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12513                  * We are here as were not able to complete the operation in
12514                  * ipif_set_values because we could not become exclusive on
12515                  * the new ipsq.
12516                  */
12517                 ill_t *ill = q->q_ptr;
12518                 ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12519         }
12520         ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12521 
12522         if (ipip->ipi_cmd_type == IF_CMD) {
12523                 /* This a old style SIOC[GS]IF* command */
12524                 ifr = (struct ifreq *)mp1->b_rptr;
12525                 sin = (sin_t *)&ifr->ifr_addr;
12526         } else if (ipip->ipi_cmd_type == LIF_CMD) {
12527                 /* This a new style SIOC[GS]LIF* command */
12528                 lifr = (struct lifreq *)mp1->b_rptr;
12529                 sin = (sin_t *)&lifr->lifr_addr;
12530         } else {
12531                 sin = NULL;
12532         }
12533 
12534         err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12535             q, mp, ipip, mp1->b_rptr);
12536 
12537         DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12538             int, ipip->ipi_cmd,
12539             ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12540             ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12541 
12542         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12543 }
12544 
12545 /*
12546  * ioctl processing
12547  *
12548  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12549  * the ioctl command in the ioctl tables, determines the copyin data size
12550  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12551  *
12552  * ioctl processing then continues when the M_IOCDATA makes its way down to
12553  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12554  * associated 'conn' is refheld till the end of the ioctl and the general
12555  * ioctl processing function ip_process_ioctl() is called to extract the
12556  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12557  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12558  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12559  * is used to extract the ioctl's arguments.
12560  *
12561  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12562  * so goes thru the serialization primitive ipsq_try_enter. Then the
12563  * appropriate function to handle the ioctl is called based on the entry in
12564  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12565  * which also refreleases the 'conn' that was refheld at the start of the
12566  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12567  *
12568  * Many exclusive ioctls go thru an internal down up sequence as part of
12569  * the operation. For example an attempt to change the IP address of an
12570  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12571  * does all the cleanup such as deleting all ires that use this address.
12572  * Then we need to wait till all references to the interface go away.
12573  */
12574 void
12575 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12576 {
12577         struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12578         ip_ioctl_cmd_t *ipip = arg;
12579         ip_extract_func_t *extract_funcp;
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          * A return value of EINPROGRESS means the ioctl is
12701          * either queued and waiting for some reason or has
12702          * already completed.
12703          */
12704         err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12705 
12706         DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12707             int, ipip->ipi_cmd,
12708             ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12709             ipif_t *, ci.ci_ipif);
12710         ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12711 
12712         if (entered_ipsq)
12713                 ipsq_exit(ipsq);
12714 }
12715 
12716 /*
12717  * Complete the ioctl. Typically ioctls use the mi package and need to
12718  * do mi_copyout/mi_copy_done.
12719  */
12720 void
12721 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12722 {
12723         conn_t  *connp = NULL;
12724 
12725         if (err == EINPROGRESS)
12726                 return;
12727 
12728         if (CONN_Q(q)) {
12729                 connp = Q_TO_CONN(q);
12730                 ASSERT(connp->conn_ref >= 2);
12731         }
12732 
12733         switch (mode) {
12734         case COPYOUT:
12735                 if (err == 0)
12736                         mi_copyout(q, mp);
12737                 else
12738                         mi_copy_done(q, mp, err);
12739                 break;
12740 
12741         case NO_COPYOUT:
12742                 mi_copy_done(q, mp, err);
12743                 break;
12744 
12745         default:
12746                 ASSERT(mode == CONN_CLOSE);     /* aborted through CONN_CLOSE */
12747                 break;
12748         }
12749 
12750         /*
12751          * The conn refhold and ioctlref placed on the conn at the start of the
12752          * ioctl are released here.
12753          */
12754         if (connp != NULL) {
12755                 CONN_DEC_IOCTLREF(connp);
12756                 CONN_OPER_PENDING_DONE(connp);
12757         }
12758 
12759         if (ipsq != NULL)
12760                 ipsq_current_finish(ipsq);
12761 }
12762 
12763 /* Handles all non data messages */
12764 void
12765 ip_wput_nondata(queue_t *q, mblk_t *mp)
12766 {
12767         mblk_t          *mp1;
12768         struct iocblk   *iocp;
12769         ip_ioctl_cmd_t  *ipip;
12770         conn_t          *connp;
12771         cred_t          *cr;
12772         char            *proto_str;
12773 
12774         if (CONN_Q(q))
12775                 connp = Q_TO_CONN(q);
12776         else
12777                 connp = NULL;
12778 
12779         switch (DB_TYPE(mp)) {
12780         case M_IOCTL:
12781                 /*
12782                  * IOCTL processing begins in ip_sioctl_copyin_setup which
12783                  * will arrange to copy in associated control structures.
12784                  */
12785                 ip_sioctl_copyin_setup(q, mp);
12786                 return;
12787         case M_IOCDATA:
12788                 /*
12789                  * Ensure that this is associated with one of our trans-
12790                  * parent ioctls.  If it's not ours, discard it if we're
12791                  * running as a driver, or pass it on if we're a module.
12792                  */
12793                 iocp = (struct iocblk *)mp->b_rptr;
12794                 ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12795                 if (ipip == NULL) {
12796                         if (q->q_next == NULL) {
12797                                 goto nak;
12798                         } else {
12799                                 putnext(q, mp);
12800                         }
12801                         return;
12802                 }
12803                 if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12804                         /*
12805                          * The ioctl is one we recognise, but is not consumed
12806                          * by IP as a module and we are a module, so we drop
12807                          */
12808                         goto nak;
12809                 }
12810 
12811                 /* IOCTL continuation following copyin or copyout. */
12812                 if (mi_copy_state(q, mp, NULL) == -1) {
12813                         /*
12814                          * The copy operation failed.  mi_copy_state already
12815                          * cleaned up, so we're out of here.
12816                          */
12817                         return;
12818                 }
12819                 /*
12820                  * If we just completed a copy in, we become writer and
12821                  * continue processing in ip_sioctl_copyin_done.  If it
12822                  * was a copy out, we call mi_copyout again.  If there is
12823                  * nothing more to copy out, it will complete the IOCTL.
12824                  */
12825                 if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12826                         if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12827                                 mi_copy_done(q, mp, EPROTO);
12828                                 return;
12829                         }
12830                         /*
12831                          * Check for cases that need more copying.  A return
12832                          * value of 0 means a second copyin has been started,
12833                          * so we return; a return value of 1 means no more
12834                          * copying is needed, so we continue.
12835                          */
12836                         if (ipip->ipi_cmd_type == MSFILT_CMD &&
12837                             MI_COPY_COUNT(mp) == 1) {
12838                                 if (ip_copyin_msfilter(q, mp) == 0)
12839                                         return;
12840                         }
12841                         /*
12842                          * Refhold the conn, till the ioctl completes. This is
12843                          * needed in case the ioctl ends up in the pending mp
12844                          * list. Every mp in the ipx_pending_mp list must have
12845                          * a refhold on the conn to resume processing. The
12846                          * refhold is released when the ioctl completes
12847                          * (whether normally or abnormally). An ioctlref is also
12848                          * placed on the conn to prevent TCP from removing the
12849                          * queue needed to send the ioctl reply back.
12850                          * In all cases ip_ioctl_finish is called to finish
12851                          * the ioctl and release the refholds.
12852                          */
12853                         if (connp != NULL) {
12854                                 /* This is not a reentry */
12855                                 CONN_INC_REF(connp);
12856                                 CONN_INC_IOCTLREF(connp);
12857                         } else {
12858                                 if (!(ipip->ipi_flags & IPI_MODOK)) {
12859                                         mi_copy_done(q, mp, EINVAL);
12860                                         return;
12861                                 }
12862                         }
12863 
12864                         ip_process_ioctl(NULL, q, mp, ipip);
12865 
12866                 } else {
12867                         mi_copyout(q, mp);
12868                 }
12869                 return;
12870 
12871         case M_IOCNAK:
12872                 /*
12873                  * The only way we could get here is if a resolver didn't like
12874                  * an IOCTL we sent it.  This shouldn't happen.
12875                  */
12876                 (void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12877                     "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12878                     ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12879                 freemsg(mp);
12880                 return;
12881         case M_IOCACK:
12882                 /* /dev/ip shouldn't see this */
12883                 goto nak;
12884         case M_FLUSH:
12885                 if (*mp->b_rptr & FLUSHW)
12886                         flushq(q, FLUSHALL);
12887                 if (q->q_next) {
12888                         putnext(q, mp);
12889                         return;
12890                 }
12891                 if (*mp->b_rptr & FLUSHR) {
12892                         *mp->b_rptr &= ~FLUSHW;
12893                         qreply(q, mp);
12894                         return;
12895                 }
12896                 freemsg(mp);
12897                 return;
12898         case M_CTL:
12899                 break;
12900         case M_PROTO:
12901         case M_PCPROTO:
12902                 /*
12903                  * The only PROTO messages we expect are SNMP-related.
12904                  */
12905                 switch (((union T_primitives *)mp->b_rptr)->type) {
12906                 case T_SVR4_OPTMGMT_REQ:
12907                         ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12908                             "flags %x\n",
12909                             ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12910 
12911                         if (connp == NULL) {
12912                                 proto_str = "T_SVR4_OPTMGMT_REQ";
12913                                 goto protonak;
12914                         }
12915 
12916                         /*
12917                          * All Solaris components should pass a db_credp
12918                          * for this TPI message, hence we ASSERT.
12919                          * But in case there is some other M_PROTO that looks
12920                          * like a TPI message sent by some other kernel
12921                          * component, we check and return an error.
12922                          */
12923                         cr = msg_getcred(mp, NULL);
12924                         ASSERT(cr != NULL);
12925                         if (cr == NULL) {
12926                                 mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12927                                 if (mp != NULL)
12928                                         qreply(q, mp);
12929                                 return;
12930                         }
12931 
12932                         if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12933                                 proto_str = "Bad SNMPCOM request?";
12934                                 goto protonak;
12935                         }
12936                         return;
12937                 default:
12938                         ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12939                             (int)*(uint_t *)mp->b_rptr));
12940                         freemsg(mp);
12941                         return;
12942                 }
12943         default:
12944                 break;
12945         }
12946         if (q->q_next) {
12947                 putnext(q, mp);
12948         } else
12949                 freemsg(mp);
12950         return;
12951 
12952 nak:
12953         iocp->ioc_error = EINVAL;
12954         mp->b_datap->db_type = M_IOCNAK;
12955         iocp->ioc_count = 0;
12956         qreply(q, mp);
12957         return;
12958 
12959 protonak:
12960         cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12961         if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12962                 qreply(q, mp);
12963 }
12964 
12965 /*
12966  * Process IP options in an outbound packet.  Verify that the nexthop in a
12967  * strict source route is onlink.
12968  * Returns non-zero if something fails in which case an ICMP error has been
12969  * sent and mp freed.
12970  *
12971  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12972  */
12973 int
12974 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12975 {
12976         ipoptp_t        opts;
12977         uchar_t         *opt;
12978         uint8_t         optval;
12979         uint8_t         optlen;
12980         ipaddr_t        dst;
12981         intptr_t        code = 0;
12982         ire_t           *ire;
12983         ip_stack_t      *ipst = ixa->ixa_ipst;
12984         ip_recv_attr_t  iras;
12985 
12986         ip2dbg(("ip_output_options\n"));
12987 
12988         dst = ipha->ipha_dst;
12989         for (optval = ipoptp_first(&opts, ipha);
12990             optval != IPOPT_EOL;
12991             optval = ipoptp_next(&opts)) {
12992                 opt = opts.ipoptp_cur;
12993                 optlen = opts.ipoptp_len;
12994                 ip2dbg(("ip_output_options: opt %d, len %d\n",
12995                     optval, optlen));
12996                 switch (optval) {
12997                         uint32_t off;
12998                 case IPOPT_SSRR:
12999                 case IPOPT_LSRR:
13000                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13001                                 ip1dbg((
13002                                     "ip_output_options: bad option offset\n"));
13003                                 code = (char *)&opt[IPOPT_OLEN] -
13004                                     (char *)ipha;
13005                                 goto param_prob;
13006                         }
13007                         off = opt[IPOPT_OFFSET];
13008                         ip1dbg(("ip_output_options: next hop 0x%x\n",
13009                             ntohl(dst)));
13010                         /*
13011                          * For strict: verify that dst is directly
13012                          * reachable.
13013                          */
13014                         if (optval == IPOPT_SSRR) {
13015                                 ire = ire_ftable_lookup_v4(dst, 0, 0,
13016                                     IRE_INTERFACE, NULL, ALL_ZONES,
13017                                     ixa->ixa_tsl,
13018                                     MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13019                                     NULL);
13020                                 if (ire == NULL) {
13021                                         ip1dbg(("ip_output_options: SSRR not"
13022                                             " directly reachable: 0x%x\n",
13023                                             ntohl(dst)));
13024                                         goto bad_src_route;
13025                                 }
13026                                 ire_refrele(ire);
13027                         }
13028                         break;
13029                 case IPOPT_RR:
13030                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13031                                 ip1dbg((
13032                                     "ip_output_options: bad option offset\n"));
13033                                 code = (char *)&opt[IPOPT_OLEN] -
13034                                     (char *)ipha;
13035                                 goto param_prob;
13036                         }
13037                         break;
13038                 case IPOPT_TS:
13039                         /*
13040                          * Verify that length >=5 and that there is either
13041                          * room for another timestamp or that the overflow
13042                          * counter is not maxed out.
13043                          */
13044                         code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13045                         if (optlen < IPOPT_MINLEN_IT) {
13046                                 goto param_prob;
13047                         }
13048                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13049                                 ip1dbg((
13050                                     "ip_output_options: bad option offset\n"));
13051                                 code = (char *)&opt[IPOPT_OFFSET] -
13052                                     (char *)ipha;
13053                                 goto param_prob;
13054                         }
13055                         switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13056                         case IPOPT_TS_TSONLY:
13057                                 off = IPOPT_TS_TIMELEN;
13058                                 break;
13059                         case IPOPT_TS_TSANDADDR:
13060                         case IPOPT_TS_PRESPEC:
13061                         case IPOPT_TS_PRESPEC_RFC791:
13062                                 off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13063                                 break;
13064                         default:
13065                                 code = (char *)&opt[IPOPT_POS_OV_FLG] -
13066                                     (char *)ipha;
13067                                 goto param_prob;
13068                         }
13069                         if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13070                             (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13071                                 /*
13072                                  * No room and the overflow counter is 15
13073                                  * already.
13074                                  */
13075                                 goto param_prob;
13076                         }
13077                         break;
13078                 }
13079         }
13080 
13081         if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13082                 return (0);
13083 
13084         ip1dbg(("ip_output_options: error processing IP options."));
13085         code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13086 
13087 param_prob:
13088         bzero(&iras, sizeof (iras));
13089         iras.ira_ill = iras.ira_rill = ill;
13090         iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13091         iras.ira_rifindex = iras.ira_ruifindex;
13092         iras.ira_flags = IRAF_IS_IPV4;
13093 
13094         ip_drop_output("ip_output_options", mp, ill);
13095         icmp_param_problem(mp, (uint8_t)code, &iras);
13096         ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13097         return (-1);
13098 
13099 bad_src_route:
13100         bzero(&iras, sizeof (iras));
13101         iras.ira_ill = iras.ira_rill = ill;
13102         iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13103         iras.ira_rifindex = iras.ira_ruifindex;
13104         iras.ira_flags = IRAF_IS_IPV4;
13105 
13106         ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13107         icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13108         ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13109         return (-1);
13110 }
13111 
13112 /*
13113  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13114  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13115  * thru /etc/system.
13116  */
13117 #define CONN_MAXDRAINCNT        64
13118 
13119 static void
13120 conn_drain_init(ip_stack_t *ipst)
13121 {
13122         int i, j;
13123         idl_tx_list_t *itl_tx;
13124 
13125         ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13126 
13127         if ((ipst->ips_conn_drain_list_cnt == 0) ||
13128             (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13129                 /*
13130                  * Default value of the number of drainers is the
13131                  * number of cpus, subject to maximum of 8 drainers.
13132                  */
13133                 if (boot_max_ncpus != -1)
13134                         ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13135                 else
13136                         ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13137         }
13138 
13139         ipst->ips_idl_tx_list =
13140             kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13141         for (i = 0; i < TX_FANOUT_SIZE; i++) {
13142                 itl_tx =  &ipst->ips_idl_tx_list[i];
13143                 itl_tx->txl_drain_list =
13144                     kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13145                     sizeof (idl_t), KM_SLEEP);
13146                 mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13147                 for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13148                         mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13149                             MUTEX_DEFAULT, NULL);
13150                         itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13151                 }
13152         }
13153 }
13154 
13155 static void
13156 conn_drain_fini(ip_stack_t *ipst)
13157 {
13158         int i;
13159         idl_tx_list_t *itl_tx;
13160 
13161         for (i = 0; i < TX_FANOUT_SIZE; i++) {
13162                 itl_tx =  &ipst->ips_idl_tx_list[i];
13163                 kmem_free(itl_tx->txl_drain_list,
13164                     ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13165         }
13166         kmem_free(ipst->ips_idl_tx_list,
13167             TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13168         ipst->ips_idl_tx_list = NULL;
13169 }
13170 
13171 /*
13172  * Flow control has blocked us from proceeding.  Insert the given conn in one
13173  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13174  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13175  * will call conn_walk_drain().  See the flow control notes at the top of this
13176  * file for more details.
13177  */
13178 void
13179 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13180 {
13181         idl_t   *idl = tx_list->txl_drain_list;
13182         uint_t  index;
13183         ip_stack_t      *ipst = connp->conn_netstack->netstack_ip;
13184 
13185         mutex_enter(&connp->conn_lock);
13186         if (connp->conn_state_flags & CONN_CLOSING) {
13187                 /*
13188                  * The conn is closing as a result of which CONN_CLOSING
13189                  * is set. Return.
13190                  */
13191                 mutex_exit(&connp->conn_lock);
13192                 return;
13193         } else if (connp->conn_idl == NULL) {
13194                 /*
13195                  * Assign the next drain list round robin. We dont' use
13196                  * a lock, and thus it may not be strictly round robin.
13197                  * Atomicity of load/stores is enough to make sure that
13198                  * conn_drain_list_index is always within bounds.
13199                  */
13200                 index = tx_list->txl_drain_index;
13201                 ASSERT(index < ipst->ips_conn_drain_list_cnt);
13202                 connp->conn_idl = &tx_list->txl_drain_list[index];
13203                 index++;
13204                 if (index == ipst->ips_conn_drain_list_cnt)
13205                         index = 0;
13206                 tx_list->txl_drain_index = index;
13207         } else {
13208                 ASSERT(connp->conn_idl->idl_itl == tx_list);
13209         }
13210         mutex_exit(&connp->conn_lock);
13211 
13212         idl = connp->conn_idl;
13213         mutex_enter(&idl->idl_lock);
13214         if ((connp->conn_drain_prev != NULL) ||
13215             (connp->conn_state_flags & CONN_CLOSING)) {
13216                 /*
13217                  * The conn is either already in the drain list or closing.
13218                  * (We needed to check for CONN_CLOSING again since close can
13219                  * sneak in between dropping conn_lock and acquiring idl_lock.)
13220                  */
13221                 mutex_exit(&idl->idl_lock);
13222                 return;
13223         }
13224 
13225         /*
13226          * The conn is not in the drain list. Insert it at the
13227          * tail of the drain list. The drain list is circular
13228          * and doubly linked. idl_conn points to the 1st element
13229          * in the list.
13230          */
13231         if (idl->idl_conn == NULL) {
13232                 idl->idl_conn = connp;
13233                 connp->conn_drain_next = connp;
13234                 connp->conn_drain_prev = connp;
13235         } else {
13236                 conn_t *head = idl->idl_conn;
13237 
13238                 connp->conn_drain_next = head;
13239                 connp->conn_drain_prev = head->conn_drain_prev;
13240                 head->conn_drain_prev->conn_drain_next = connp;
13241                 head->conn_drain_prev = connp;
13242         }
13243         /*
13244          * For non streams based sockets assert flow control.
13245          */
13246         conn_setqfull(connp, NULL);
13247         mutex_exit(&idl->idl_lock);
13248 }
13249 
13250 static void
13251 conn_drain_remove(conn_t *connp)
13252 {
13253         idl_t *idl = connp->conn_idl;
13254 
13255         if (idl != NULL) {
13256                 /*
13257                  * Remove ourself from the drain list.
13258                  */
13259                 if (connp->conn_drain_next == connp) {
13260                         /* Singleton in the list */
13261                         ASSERT(connp->conn_drain_prev == connp);
13262                         idl->idl_conn = NULL;
13263                 } else {
13264                         connp->conn_drain_prev->conn_drain_next =
13265                             connp->conn_drain_next;
13266                         connp->conn_drain_next->conn_drain_prev =
13267                             connp->conn_drain_prev;
13268                         if (idl->idl_conn == connp)
13269                                 idl->idl_conn = connp->conn_drain_next;
13270                 }
13271 
13272                 /*
13273                  * NOTE: because conn_idl is associated with a specific drain
13274                  * list which in turn is tied to the index the TX ring
13275                  * (txl_cookie) hashes to, and because the TX ring can change
13276                  * over the lifetime of the conn_t, we must clear conn_idl so
13277                  * a subsequent conn_drain_insert() will set conn_idl again
13278                  * based on the latest txl_cookie.
13279                  */
13280                 connp->conn_idl = NULL;
13281         }
13282         connp->conn_drain_next = NULL;
13283         connp->conn_drain_prev = NULL;
13284 
13285         conn_clrqfull(connp, NULL);
13286         /*
13287          * For streams based sockets open up flow control.
13288          */
13289         if (!IPCL_IS_NONSTR(connp))
13290                 enableok(connp->conn_wq);
13291 }
13292 
13293 /*
13294  * This conn is closing, and we are called from ip_close. OR
13295  * this conn is draining because flow-control on the ill has been relieved.
13296  *
13297  * We must also need to remove conn's on this idl from the list, and also
13298  * inform the sockfs upcalls about the change in flow-control.
13299  */
13300 static void
13301 conn_drain(conn_t *connp, boolean_t closing)
13302 {
13303         idl_t *idl;
13304         conn_t *next_connp;
13305 
13306         /*
13307          * connp->conn_idl is stable at this point, and no lock is needed
13308          * to check it. If we are called from ip_close, close has already
13309          * set CONN_CLOSING, thus freezing the value of conn_idl, and
13310          * called us only because conn_idl is non-null. If we are called thru
13311          * service, conn_idl could be null, but it cannot change because
13312          * service is single-threaded per queue, and there cannot be another
13313          * instance of service trying to call conn_drain_insert on this conn
13314          * now.
13315          */
13316         ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13317 
13318         /*
13319          * If the conn doesn't exist or is not on a drain list, bail.
13320          */
13321         if (connp == NULL || connp->conn_idl == NULL ||
13322             connp->conn_drain_prev == NULL) {
13323                 return;
13324         }
13325 
13326         idl = connp->conn_idl;
13327         ASSERT(MUTEX_HELD(&idl->idl_lock));
13328 
13329         if (!closing) {
13330                 next_connp = connp->conn_drain_next;
13331                 while (next_connp != connp) {
13332                         conn_t *delconnp = next_connp;
13333 
13334                         next_connp = next_connp->conn_drain_next;
13335                         conn_drain_remove(delconnp);
13336                 }
13337                 ASSERT(connp->conn_drain_next == idl->idl_conn);
13338         }
13339         conn_drain_remove(connp);
13340 }
13341 
13342 /*
13343  * Write service routine. Shared perimeter entry point.
13344  * The device queue's messages has fallen below the low water mark and STREAMS
13345  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13346  * each waiting conn.
13347  */
13348 void
13349 ip_wsrv(queue_t *q)
13350 {
13351         ill_t   *ill;
13352 
13353         ill = (ill_t *)q->q_ptr;
13354         if (ill->ill_state_flags == 0) {
13355                 ip_stack_t *ipst = ill->ill_ipst;
13356 
13357                 /*
13358                  * The device flow control has opened up.
13359                  * Walk through conn drain lists and qenable the
13360                  * first conn in each list. This makes sense only
13361                  * if the stream is fully plumbed and setup.
13362                  * Hence the ill_state_flags check above.
13363                  */
13364                 ip1dbg(("ip_wsrv: walking\n"));
13365                 conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13366                 enableok(ill->ill_wq);
13367         }
13368 }
13369 
13370 /*
13371  * Callback to disable flow control in IP.
13372  *
13373  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13374  * is enabled.
13375  *
13376  * When MAC_TX() is not able to send any more packets, dld sets its queue
13377  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13378  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13379  * function and wakes up corresponding mac worker threads, which in turn
13380  * calls this callback function, and disables flow control.
13381  */
13382 void
13383 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13384 {
13385         ill_t *ill = (ill_t *)arg;
13386         ip_stack_t *ipst = ill->ill_ipst;
13387         idl_tx_list_t *idl_txl;
13388 
13389         idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13390         mutex_enter(&idl_txl->txl_lock);
13391         /* add code to to set a flag to indicate idl_txl is enabled */
13392         conn_walk_drain(ipst, idl_txl);
13393         mutex_exit(&idl_txl->txl_lock);
13394 }
13395 
13396 /*
13397  * Flow control has been relieved and STREAMS has backenabled us; drain
13398  * all the conn lists on `tx_list'.
13399  */
13400 static void
13401 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13402 {
13403         int i;
13404         idl_t *idl;
13405 
13406         IP_STAT(ipst, ip_conn_walk_drain);
13407 
13408         for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13409                 idl = &tx_list->txl_drain_list[i];
13410                 mutex_enter(&idl->idl_lock);
13411                 conn_drain(idl->idl_conn, B_FALSE);
13412                 mutex_exit(&idl->idl_lock);
13413         }
13414 }
13415 
13416 /*
13417  * Determine if the ill and multicast aspects of that packets
13418  * "matches" the conn.
13419  */
13420 boolean_t
13421 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13422 {
13423         ill_t           *ill = ira->ira_rill;
13424         zoneid_t        zoneid = ira->ira_zoneid;
13425         uint_t          in_ifindex;
13426         ipaddr_t        dst, src;
13427 
13428         dst = ipha->ipha_dst;
13429         src = ipha->ipha_src;
13430 
13431         /*
13432          * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13433          * unicast, broadcast and multicast reception to
13434          * conn_incoming_ifindex.
13435          * conn_wantpacket is called for unicast, broadcast and
13436          * multicast packets.
13437          */
13438         in_ifindex = connp->conn_incoming_ifindex;
13439 
13440         /* mpathd can bind to the under IPMP interface, which we allow */
13441         if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13442                 if (!IS_UNDER_IPMP(ill))
13443                         return (B_FALSE);
13444 
13445                 if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13446                         return (B_FALSE);
13447         }
13448 
13449         if (!IPCL_ZONE_MATCH(connp, zoneid))
13450                 return (B_FALSE);
13451 
13452         if (!(ira->ira_flags & IRAF_MULTICAST))
13453                 return (B_TRUE);
13454 
13455         if (connp->conn_multi_router) {
13456                 /* multicast packet and multicast router socket: send up */
13457                 return (B_TRUE);
13458         }
13459 
13460         if (ipha->ipha_protocol == IPPROTO_PIM ||
13461             ipha->ipha_protocol == IPPROTO_RSVP)
13462                 return (B_TRUE);
13463 
13464         return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13465 }
13466 
13467 void
13468 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13469 {
13470         if (IPCL_IS_NONSTR(connp)) {
13471                 (*connp->conn_upcalls->su_txq_full)
13472                     (connp->conn_upper_handle, B_TRUE);
13473                 if (flow_stopped != NULL)
13474                         *flow_stopped = B_TRUE;
13475         } else {
13476                 queue_t *q = connp->conn_wq;
13477 
13478                 ASSERT(q != NULL);
13479                 if (!(q->q_flag & QFULL)) {
13480                         mutex_enter(QLOCK(q));
13481                         if (!(q->q_flag & QFULL)) {
13482                                 /* still need to set QFULL */
13483                                 q->q_flag |= QFULL;
13484                                 /* set flow_stopped to true under QLOCK */
13485                                 if (flow_stopped != NULL)
13486                                         *flow_stopped = B_TRUE;
13487                                 mutex_exit(QLOCK(q));
13488                         } else {
13489                                 /* flow_stopped is left unchanged */
13490                                 mutex_exit(QLOCK(q));
13491                         }
13492                 }
13493         }
13494 }
13495 
13496 void
13497 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13498 {
13499         if (IPCL_IS_NONSTR(connp)) {
13500                 (*connp->conn_upcalls->su_txq_full)
13501                     (connp->conn_upper_handle, B_FALSE);
13502                 if (flow_stopped != NULL)
13503                         *flow_stopped = B_FALSE;
13504         } else {
13505                 queue_t *q = connp->conn_wq;
13506 
13507                 ASSERT(q != NULL);
13508                 if (q->q_flag & QFULL) {
13509                         mutex_enter(QLOCK(q));
13510                         if (q->q_flag & QFULL) {
13511                                 q->q_flag &= ~QFULL;
13512                                 /* set flow_stopped to false under QLOCK */
13513                                 if (flow_stopped != NULL)
13514                                         *flow_stopped = B_FALSE;
13515                                 mutex_exit(QLOCK(q));
13516                                 if (q->q_flag & QWANTW)
13517                                         qbackenable(q, 0);
13518                         } else {
13519                                 /* flow_stopped is left unchanged */
13520                                 mutex_exit(QLOCK(q));
13521                         }
13522                 }
13523         }
13524 
13525         mutex_enter(&connp->conn_lock);
13526         connp->conn_blocked = B_FALSE;
13527         mutex_exit(&connp->conn_lock);
13528 }
13529 
13530 /*
13531  * Return the length in bytes of the IPv4 headers (base header, label, and
13532  * other IP options) that will be needed based on the
13533  * ip_pkt_t structure passed by the caller.
13534  *
13535  * The returned length does not include the length of the upper level
13536  * protocol (ULP) header.
13537  * The caller needs to check that the length doesn't exceed the max for IPv4.
13538  */
13539 int
13540 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13541 {
13542         int len;
13543 
13544         len = IP_SIMPLE_HDR_LENGTH;
13545         if (ipp->ipp_fields & IPPF_LABEL_V4) {
13546                 ASSERT(ipp->ipp_label_len_v4 != 0);
13547                 /* We need to round up here */
13548                 len += (ipp->ipp_label_len_v4 + 3) & ~3;
13549         }
13550 
13551         if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13552                 ASSERT(ipp->ipp_ipv4_options_len != 0);
13553                 ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13554                 len += ipp->ipp_ipv4_options_len;
13555         }
13556         return (len);
13557 }
13558 
13559 /*
13560  * All-purpose routine to build an IPv4 header with options based
13561  * on the abstract ip_pkt_t.
13562  *
13563  * The caller has to set the source and destination address as well as
13564  * ipha_length. The caller has to massage any source route and compensate
13565  * for the ULP pseudo-header checksum due to the source route.
13566  */
13567 void
13568 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13569     uint8_t protocol)
13570 {
13571         ipha_t  *ipha = (ipha_t *)buf;
13572         uint8_t *cp;
13573 
13574         /* Initialize IPv4 header */
13575         ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13576         ipha->ipha_length = 0;       /* Caller will set later */
13577         ipha->ipha_ident = 0;
13578         ipha->ipha_fragment_offset_and_flags = 0;
13579         ipha->ipha_ttl = ipp->ipp_unicast_hops;
13580         ipha->ipha_protocol = protocol;
13581         ipha->ipha_hdr_checksum = 0;
13582 
13583         if ((ipp->ipp_fields & IPPF_ADDR) &&
13584             IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13585                 ipha->ipha_src = ipp->ipp_addr_v4;
13586 
13587         cp = (uint8_t *)&ipha[1];
13588         if (ipp->ipp_fields & IPPF_LABEL_V4) {
13589                 ASSERT(ipp->ipp_label_len_v4 != 0);
13590                 bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13591                 cp += ipp->ipp_label_len_v4;
13592                 /* We need to round up here */
13593                 while ((uintptr_t)cp & 0x3) {
13594                         *cp++ = IPOPT_NOP;
13595                 }
13596         }
13597 
13598         if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13599                 ASSERT(ipp->ipp_ipv4_options_len != 0);
13600                 ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13601                 bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13602                 cp += ipp->ipp_ipv4_options_len;
13603         }
13604         ipha->ipha_version_and_hdr_length =
13605             (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13606 
13607         ASSERT((int)(cp - buf) == buf_len);
13608 }
13609 
13610 /* Allocate the private structure */
13611 static int
13612 ip_priv_alloc(void **bufp)
13613 {
13614         void    *buf;
13615 
13616         if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13617                 return (ENOMEM);
13618 
13619         *bufp = buf;
13620         return (0);
13621 }
13622 
13623 /* Function to delete the private structure */
13624 void
13625 ip_priv_free(void *buf)
13626 {
13627         ASSERT(buf != NULL);
13628         kmem_free(buf, sizeof (ip_priv_t));
13629 }
13630 
13631 /*
13632  * The entry point for IPPF processing.
13633  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13634  * routine just returns.
13635  *
13636  * When called, ip_process generates an ipp_packet_t structure
13637  * which holds the state information for this packet and invokes the
13638  * the classifier (via ipp_packet_process). The classification, depending on
13639  * configured filters, results in a list of actions for this packet. Invoking
13640  * an action may cause the packet to be dropped, in which case we return NULL.
13641  * proc indicates the callout position for
13642  * this packet and ill is the interface this packet arrived on or will leave
13643  * on (inbound and outbound resp.).
13644  *
13645  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13646  * on the ill corrsponding to the destination IP address.
13647  */
13648 mblk_t *
13649 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13650 {
13651         ip_priv_t       *priv;
13652         ipp_action_id_t aid;
13653         int             rc = 0;
13654         ipp_packet_t    *pp;
13655 
13656         /* If the classifier is not loaded, return  */
13657         if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13658                 return (mp);
13659         }
13660 
13661         ASSERT(mp != NULL);
13662 
13663         /* Allocate the packet structure */
13664         rc = ipp_packet_alloc(&pp, "ip", aid);
13665         if (rc != 0)
13666                 goto drop;
13667 
13668         /* Allocate the private structure */
13669         rc = ip_priv_alloc((void **)&priv);
13670         if (rc != 0) {
13671                 ipp_packet_free(pp);
13672                 goto drop;
13673         }
13674         priv->proc = proc;
13675         priv->ill_index = ill_get_upper_ifindex(rill);
13676 
13677         ipp_packet_set_private(pp, priv, ip_priv_free);
13678         ipp_packet_set_data(pp, mp);
13679 
13680         /* Invoke the classifier */
13681         rc = ipp_packet_process(&pp);
13682         if (pp != NULL) {
13683                 mp = ipp_packet_get_data(pp);
13684                 ipp_packet_free(pp);
13685                 if (rc != 0)
13686                         goto drop;
13687                 return (mp);
13688         } else {
13689                 /* No mp to trace in ip_drop_input/ip_drop_output  */
13690                 mp = NULL;
13691         }
13692 drop:
13693         if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13694                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13695                 ip_drop_input("ip_process", mp, ill);
13696         } else {
13697                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13698                 ip_drop_output("ip_process", mp, ill);
13699         }
13700         freemsg(mp);
13701         return (NULL);
13702 }
13703 
13704 /*
13705  * Propagate a multicast group membership operation (add/drop) on
13706  * all the interfaces crossed by the related multirt routes.
13707  * The call is considered successful if the operation succeeds
13708  * on at least one interface.
13709  *
13710  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13711  * multicast addresses with the ire argument being the first one.
13712  * We walk the bucket to find all the of those.
13713  *
13714  * Common to IPv4 and IPv6.
13715  */
13716 static int
13717 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13718     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13719     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13720     mcast_record_t fmode, const in6_addr_t *v6src)
13721 {
13722         ire_t           *ire_gw;
13723         irb_t           *irb;
13724         int             ifindex;
13725         int             error = 0;
13726         int             result;
13727         ip_stack_t      *ipst = ire->ire_ipst;
13728         ipaddr_t        group;
13729         boolean_t       isv6;
13730         int             match_flags;
13731 
13732         if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13733                 IN6_V4MAPPED_TO_IPADDR(v6group, group);
13734                 isv6 = B_FALSE;
13735         } else {
13736                 isv6 = B_TRUE;
13737         }
13738 
13739         irb = ire->ire_bucket;
13740         ASSERT(irb != NULL);
13741 
13742         result = 0;
13743         irb_refhold(irb);
13744         for (; ire != NULL; ire = ire->ire_next) {
13745                 if ((ire->ire_flags & RTF_MULTIRT) == 0)
13746                         continue;
13747 
13748                 /* We handle -ifp routes by matching on the ill if set */
13749                 match_flags = MATCH_IRE_TYPE;
13750                 if (ire->ire_ill != NULL)
13751                         match_flags |= MATCH_IRE_ILL;
13752 
13753                 if (isv6) {
13754                         if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13755                                 continue;
13756 
13757                         ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13758                             0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13759                             match_flags, 0, ipst, NULL);
13760                 } else {
13761                         if (ire->ire_addr != group)
13762                                 continue;
13763 
13764                         ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13765                             0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13766                             match_flags, 0, ipst, NULL);
13767                 }
13768                 /* No interface route exists for the gateway; skip this ire. */
13769                 if (ire_gw == NULL)
13770                         continue;
13771                 if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13772                         ire_refrele(ire_gw);
13773                         continue;
13774                 }
13775                 ASSERT(ire_gw->ire_ill != NULL);     /* IRE_INTERFACE */
13776                 ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13777 
13778                 /*
13779                  * The operation is considered a success if
13780                  * it succeeds at least once on any one interface.
13781                  */
13782                 error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13783                     fmode, v6src);
13784                 if (error == 0)
13785                         result = CGTP_MCAST_SUCCESS;
13786 
13787                 ire_refrele(ire_gw);
13788         }
13789         irb_refrele(irb);
13790         /*
13791          * Consider the call as successful if we succeeded on at least
13792          * one interface. Otherwise, return the last encountered error.
13793          */
13794         return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13795 }
13796 
13797 /*
13798  * Return the expected CGTP hooks version number.
13799  */
13800 int
13801 ip_cgtp_filter_supported(void)
13802 {
13803         return (ip_cgtp_filter_rev);
13804 }
13805 
13806 /*
13807  * CGTP hooks can be registered by invoking this function.
13808  * Checks that the version number matches.
13809  */
13810 int
13811 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13812 {
13813         netstack_t *ns;
13814         ip_stack_t *ipst;
13815 
13816         if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13817                 return (ENOTSUP);
13818 
13819         ns = netstack_find_by_stackid(stackid);
13820         if (ns == NULL)
13821                 return (EINVAL);
13822         ipst = ns->netstack_ip;
13823         ASSERT(ipst != NULL);
13824 
13825         if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13826                 netstack_rele(ns);
13827                 return (EALREADY);
13828         }
13829 
13830         ipst->ips_ip_cgtp_filter_ops = ops;
13831 
13832         ill_set_inputfn_all(ipst);
13833 
13834         netstack_rele(ns);
13835         return (0);
13836 }
13837 
13838 /*
13839  * CGTP hooks can be unregistered by invoking this function.
13840  * Returns ENXIO if there was no registration.
13841  * Returns EBUSY if the ndd variable has not been turned off.
13842  */
13843 int
13844 ip_cgtp_filter_unregister(netstackid_t stackid)
13845 {
13846         netstack_t *ns;
13847         ip_stack_t *ipst;
13848 
13849         ns = netstack_find_by_stackid(stackid);
13850         if (ns == NULL)
13851                 return (EINVAL);
13852         ipst = ns->netstack_ip;
13853         ASSERT(ipst != NULL);
13854 
13855         if (ipst->ips_ip_cgtp_filter) {
13856                 netstack_rele(ns);
13857                 return (EBUSY);
13858         }
13859 
13860         if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13861                 netstack_rele(ns);
13862                 return (ENXIO);
13863         }
13864         ipst->ips_ip_cgtp_filter_ops = NULL;
13865 
13866         ill_set_inputfn_all(ipst);
13867 
13868         netstack_rele(ns);
13869         return (0);
13870 }
13871 
13872 /*
13873  * Check whether there is a CGTP filter registration.
13874  * Returns non-zero if there is a registration, otherwise returns zero.
13875  * Note: returns zero if bad stackid.
13876  */
13877 int
13878 ip_cgtp_filter_is_registered(netstackid_t stackid)
13879 {
13880         netstack_t *ns;
13881         ip_stack_t *ipst;
13882         int ret;
13883 
13884         ns = netstack_find_by_stackid(stackid);
13885         if (ns == NULL)
13886                 return (0);
13887         ipst = ns->netstack_ip;
13888         ASSERT(ipst != NULL);
13889 
13890         if (ipst->ips_ip_cgtp_filter_ops != NULL)
13891                 ret = 1;
13892         else
13893                 ret = 0;
13894 
13895         netstack_rele(ns);
13896         return (ret);
13897 }
13898 
13899 static int
13900 ip_squeue_switch(int val)
13901 {
13902         int rval;
13903 
13904         switch (val) {
13905         case IP_SQUEUE_ENTER_NODRAIN:
13906                 rval = SQ_NODRAIN;
13907                 break;
13908         case IP_SQUEUE_ENTER:
13909                 rval = SQ_PROCESS;
13910                 break;
13911         case IP_SQUEUE_FILL:
13912         default:
13913                 rval = SQ_FILL;
13914                 break;
13915         }
13916         return (rval);
13917 }
13918 
13919 static void *
13920 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13921 {
13922         kstat_t *ksp;
13923 
13924         ip_stat_t template = {
13925                 { "ip_udp_fannorm",             KSTAT_DATA_UINT64 },
13926                 { "ip_udp_fanmb",               KSTAT_DATA_UINT64 },
13927                 { "ip_recv_pullup",             KSTAT_DATA_UINT64 },
13928                 { "ip_db_ref",                  KSTAT_DATA_UINT64 },
13929                 { "ip_notaligned",              KSTAT_DATA_UINT64 },
13930                 { "ip_multimblk",               KSTAT_DATA_UINT64 },
13931                 { "ip_opt",                     KSTAT_DATA_UINT64 },
13932                 { "ipsec_proto_ahesp",          KSTAT_DATA_UINT64 },
13933                 { "ip_conn_flputbq",            KSTAT_DATA_UINT64 },
13934                 { "ip_conn_walk_drain",         KSTAT_DATA_UINT64 },
13935                 { "ip_out_sw_cksum",            KSTAT_DATA_UINT64 },
13936                 { "ip_out_sw_cksum_bytes",      KSTAT_DATA_UINT64 },
13937                 { "ip_in_sw_cksum",             KSTAT_DATA_UINT64 },
13938                 { "ip_ire_reclaim_calls",       KSTAT_DATA_UINT64 },
13939                 { "ip_ire_reclaim_deleted",     KSTAT_DATA_UINT64 },
13940                 { "ip_nce_reclaim_calls",       KSTAT_DATA_UINT64 },
13941                 { "ip_nce_reclaim_deleted",     KSTAT_DATA_UINT64 },
13942                 { "ip_dce_reclaim_calls",       KSTAT_DATA_UINT64 },
13943                 { "ip_dce_reclaim_deleted",     KSTAT_DATA_UINT64 },
13944                 { "ip_tcp_in_full_hw_cksum_err",        KSTAT_DATA_UINT64 },
13945                 { "ip_tcp_in_part_hw_cksum_err",        KSTAT_DATA_UINT64 },
13946                 { "ip_tcp_in_sw_cksum_err",             KSTAT_DATA_UINT64 },
13947                 { "ip_udp_in_full_hw_cksum_err",        KSTAT_DATA_UINT64 },
13948                 { "ip_udp_in_part_hw_cksum_err",        KSTAT_DATA_UINT64 },
13949                 { "ip_udp_in_sw_cksum_err",     KSTAT_DATA_UINT64 },
13950                 { "conn_in_recvdstaddr",        KSTAT_DATA_UINT64 },
13951                 { "conn_in_recvopts",           KSTAT_DATA_UINT64 },
13952                 { "conn_in_recvif",             KSTAT_DATA_UINT64 },
13953                 { "conn_in_recvslla",           KSTAT_DATA_UINT64 },
13954                 { "conn_in_recvucred",          KSTAT_DATA_UINT64 },
13955                 { "conn_in_recvttl",            KSTAT_DATA_UINT64 },
13956                 { "conn_in_recvhopopts",        KSTAT_DATA_UINT64 },
13957                 { "conn_in_recvhoplimit",       KSTAT_DATA_UINT64 },
13958                 { "conn_in_recvdstopts",        KSTAT_DATA_UINT64 },
13959                 { "conn_in_recvrthdrdstopts",   KSTAT_DATA_UINT64 },
13960                 { "conn_in_recvrthdr",          KSTAT_DATA_UINT64 },
13961                 { "conn_in_recvpktinfo",        KSTAT_DATA_UINT64 },
13962                 { "conn_in_recvtclass",         KSTAT_DATA_UINT64 },
13963                 { "conn_in_timestamp",          KSTAT_DATA_UINT64 },
13964         };
13965 
13966         ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13967             KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13968             KSTAT_FLAG_VIRTUAL, stackid);
13969 
13970         if (ksp == NULL)
13971                 return (NULL);
13972 
13973         bcopy(&template, ip_statisticsp, sizeof (template));
13974         ksp->ks_data = (void *)ip_statisticsp;
13975         ksp->ks_private = (void *)(uintptr_t)stackid;
13976 
13977         kstat_install(ksp);
13978         return (ksp);
13979 }
13980 
13981 static void
13982 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13983 {
13984         if (ksp != NULL) {
13985                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13986                 kstat_delete_netstack(ksp, stackid);
13987         }
13988 }
13989 
13990 static void *
13991 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13992 {
13993         kstat_t *ksp;
13994 
13995         ip_named_kstat_t template = {
13996                 { "forwarding",         KSTAT_DATA_UINT32, 0 },
13997                 { "defaultTTL",         KSTAT_DATA_UINT32, 0 },
13998                 { "inReceives",         KSTAT_DATA_UINT64, 0 },
13999                 { "inHdrErrors",        KSTAT_DATA_UINT32, 0 },
14000                 { "inAddrErrors",       KSTAT_DATA_UINT32, 0 },
14001                 { "forwDatagrams",      KSTAT_DATA_UINT64, 0 },
14002                 { "inUnknownProtos",    KSTAT_DATA_UINT32, 0 },
14003                 { "inDiscards",         KSTAT_DATA_UINT32, 0 },
14004                 { "inDelivers",         KSTAT_DATA_UINT64, 0 },
14005                 { "outRequests",        KSTAT_DATA_UINT64, 0 },
14006                 { "outDiscards",        KSTAT_DATA_UINT32, 0 },
14007                 { "outNoRoutes",        KSTAT_DATA_UINT32, 0 },
14008                 { "reasmTimeout",       KSTAT_DATA_UINT32, 0 },
14009                 { "reasmReqds",         KSTAT_DATA_UINT32, 0 },
14010                 { "reasmOKs",           KSTAT_DATA_UINT32, 0 },
14011                 { "reasmFails",         KSTAT_DATA_UINT32, 0 },
14012                 { "fragOKs",            KSTAT_DATA_UINT32, 0 },
14013                 { "fragFails",          KSTAT_DATA_UINT32, 0 },
14014                 { "fragCreates",        KSTAT_DATA_UINT32, 0 },
14015                 { "addrEntrySize",      KSTAT_DATA_INT32, 0 },
14016                 { "routeEntrySize",     KSTAT_DATA_INT32, 0 },
14017                 { "netToMediaEntrySize",        KSTAT_DATA_INT32, 0 },
14018                 { "routingDiscards",    KSTAT_DATA_UINT32, 0 },
14019                 { "inErrs",             KSTAT_DATA_UINT32, 0 },
14020                 { "noPorts",            KSTAT_DATA_UINT32, 0 },
14021                 { "inCksumErrs",        KSTAT_DATA_UINT32, 0 },
14022                 { "reasmDuplicates",    KSTAT_DATA_UINT32, 0 },
14023                 { "reasmPartDups",      KSTAT_DATA_UINT32, 0 },
14024                 { "forwProhibits",      KSTAT_DATA_UINT32, 0 },
14025                 { "udpInCksumErrs",     KSTAT_DATA_UINT32, 0 },
14026                 { "udpInOverflows",     KSTAT_DATA_UINT32, 0 },
14027                 { "rawipInOverflows",   KSTAT_DATA_UINT32, 0 },
14028                 { "ipsecInSucceeded",   KSTAT_DATA_UINT32, 0 },
14029                 { "ipsecInFailed",      KSTAT_DATA_INT32, 0 },
14030                 { "memberEntrySize",    KSTAT_DATA_INT32, 0 },
14031                 { "inIPv6",             KSTAT_DATA_UINT32, 0 },
14032                 { "outIPv6",            KSTAT_DATA_UINT32, 0 },
14033                 { "outSwitchIPv6",      KSTAT_DATA_UINT32, 0 },
14034         };
14035 
14036         ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14037             NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14038         if (ksp == NULL || ksp->ks_data == NULL)
14039                 return (NULL);
14040 
14041         template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14042         template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14043         template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
14044         template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14045         template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14046 
14047         template.netToMediaEntrySize.value.i32 =
14048             sizeof (mib2_ipNetToMediaEntry_t);
14049 
14050         template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14051 
14052         bcopy(&template, ksp->ks_data, sizeof (template));
14053         ksp->ks_update = ip_kstat_update;
14054         ksp->ks_private = (void *)(uintptr_t)stackid;
14055 
14056         kstat_install(ksp);
14057         return (ksp);
14058 }
14059 
14060 static void
14061 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14062 {
14063         if (ksp != NULL) {
14064                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14065                 kstat_delete_netstack(ksp, stackid);
14066         }
14067 }
14068 
14069 static int
14070 ip_kstat_update(kstat_t *kp, int rw)
14071 {
14072         ip_named_kstat_t *ipkp;
14073         mib2_ipIfStatsEntry_t ipmib;
14074         ill_walk_context_t ctx;
14075         ill_t *ill;
14076         netstackid_t    stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14077         netstack_t      *ns;
14078         ip_stack_t      *ipst;
14079 
14080         if (kp == NULL || kp->ks_data == NULL)
14081                 return (EIO);
14082 
14083         if (rw == KSTAT_WRITE)
14084                 return (EACCES);
14085 
14086         ns = netstack_find_by_stackid(stackid);
14087         if (ns == NULL)
14088                 return (-1);
14089         ipst = ns->netstack_ip;
14090         if (ipst == NULL) {
14091                 netstack_rele(ns);
14092                 return (-1);
14093         }
14094         ipkp = (ip_named_kstat_t *)kp->ks_data;
14095 
14096         bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14097         rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14098         ill = ILL_START_WALK_V4(&ctx, ipst);
14099         for (; ill != NULL; ill = ill_next(&ctx, ill))
14100                 ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14101         rw_exit(&ipst->ips_ill_g_lock);
14102 
14103         ipkp->forwarding.value.ui32 =                ipmib.ipIfStatsForwarding;
14104         ipkp->defaultTTL.value.ui32 =                ipmib.ipIfStatsDefaultTTL;
14105         ipkp->inReceives.value.ui64 =                ipmib.ipIfStatsHCInReceives;
14106         ipkp->inHdrErrors.value.ui32 =               ipmib.ipIfStatsInHdrErrors;
14107         ipkp->inAddrErrors.value.ui32 =              ipmib.ipIfStatsInAddrErrors;
14108         ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14109         ipkp->inUnknownProtos.value.ui32 =   ipmib.ipIfStatsInUnknownProtos;
14110         ipkp->inDiscards.value.ui32 =                ipmib.ipIfStatsInDiscards;
14111         ipkp->inDelivers.value.ui64 =                ipmib.ipIfStatsHCInDelivers;
14112         ipkp->outRequests.value.ui64 =               ipmib.ipIfStatsHCOutRequests;
14113         ipkp->outDiscards.value.ui32 =               ipmib.ipIfStatsOutDiscards;
14114         ipkp->outNoRoutes.value.ui32 =               ipmib.ipIfStatsOutNoRoutes;
14115         ipkp->reasmTimeout.value.ui32 =              ipst->ips_ip_reassembly_timeout;
14116         ipkp->reasmReqds.value.ui32 =                ipmib.ipIfStatsReasmReqds;
14117         ipkp->reasmOKs.value.ui32 =          ipmib.ipIfStatsReasmOKs;
14118         ipkp->reasmFails.value.ui32 =                ipmib.ipIfStatsReasmFails;
14119         ipkp->fragOKs.value.ui32 =           ipmib.ipIfStatsOutFragOKs;
14120         ipkp->fragFails.value.ui32 =         ipmib.ipIfStatsOutFragFails;
14121         ipkp->fragCreates.value.ui32 =               ipmib.ipIfStatsOutFragCreates;
14122 
14123         ipkp->routingDiscards.value.ui32 =   0;
14124         ipkp->inErrs.value.ui32 =            ipmib.tcpIfStatsInErrs;
14125         ipkp->noPorts.value.ui32 =           ipmib.udpIfStatsNoPorts;
14126         ipkp->inCksumErrs.value.ui32 =               ipmib.ipIfStatsInCksumErrs;
14127         ipkp->reasmDuplicates.value.ui32 =   ipmib.ipIfStatsReasmDuplicates;
14128         ipkp->reasmPartDups.value.ui32 =     ipmib.ipIfStatsReasmPartDups;
14129         ipkp->forwProhibits.value.ui32 =     ipmib.ipIfStatsForwProhibits;
14130         ipkp->udpInCksumErrs.value.ui32 =    ipmib.udpIfStatsInCksumErrs;
14131         ipkp->udpInOverflows.value.ui32 =    ipmib.udpIfStatsInOverflows;
14132         ipkp->rawipInOverflows.value.ui32 =  ipmib.rawipIfStatsInOverflows;
14133         ipkp->ipsecInSucceeded.value.ui32 =  ipmib.ipsecIfStatsInSucceeded;
14134         ipkp->ipsecInFailed.value.i32 =              ipmib.ipsecIfStatsInFailed;
14135 
14136         ipkp->inIPv6.value.ui32 =    ipmib.ipIfStatsInWrongIPVersion;
14137         ipkp->outIPv6.value.ui32 =   ipmib.ipIfStatsOutWrongIPVersion;
14138         ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14139 
14140         netstack_rele(ns);
14141 
14142         return (0);
14143 }
14144 
14145 static void *
14146 icmp_kstat_init(netstackid_t stackid)
14147 {
14148         kstat_t *ksp;
14149 
14150         icmp_named_kstat_t template = {
14151                 { "inMsgs",             KSTAT_DATA_UINT32 },
14152                 { "inErrors",           KSTAT_DATA_UINT32 },
14153                 { "inDestUnreachs",     KSTAT_DATA_UINT32 },
14154                 { "inTimeExcds",        KSTAT_DATA_UINT32 },
14155                 { "inParmProbs",        KSTAT_DATA_UINT32 },
14156                 { "inSrcQuenchs",       KSTAT_DATA_UINT32 },
14157                 { "inRedirects",        KSTAT_DATA_UINT32 },
14158                 { "inEchos",            KSTAT_DATA_UINT32 },
14159                 { "inEchoReps",         KSTAT_DATA_UINT32 },
14160                 { "inTimestamps",       KSTAT_DATA_UINT32 },
14161                 { "inTimestampReps",    KSTAT_DATA_UINT32 },
14162                 { "inAddrMasks",        KSTAT_DATA_UINT32 },
14163                 { "inAddrMaskReps",     KSTAT_DATA_UINT32 },
14164                 { "outMsgs",            KSTAT_DATA_UINT32 },
14165                 { "outErrors",          KSTAT_DATA_UINT32 },
14166                 { "outDestUnreachs",    KSTAT_DATA_UINT32 },
14167                 { "outTimeExcds",       KSTAT_DATA_UINT32 },
14168                 { "outParmProbs",       KSTAT_DATA_UINT32 },
14169                 { "outSrcQuenchs",      KSTAT_DATA_UINT32 },
14170                 { "outRedirects",       KSTAT_DATA_UINT32 },
14171                 { "outEchos",           KSTAT_DATA_UINT32 },
14172                 { "outEchoReps",        KSTAT_DATA_UINT32 },
14173                 { "outTimestamps",      KSTAT_DATA_UINT32 },
14174                 { "outTimestampReps",   KSTAT_DATA_UINT32 },
14175                 { "outAddrMasks",       KSTAT_DATA_UINT32 },
14176                 { "outAddrMaskReps",    KSTAT_DATA_UINT32 },
14177                 { "inChksumErrs",       KSTAT_DATA_UINT32 },
14178                 { "inUnknowns",         KSTAT_DATA_UINT32 },
14179                 { "inFragNeeded",       KSTAT_DATA_UINT32 },
14180                 { "outFragNeeded",      KSTAT_DATA_UINT32 },
14181                 { "outDrops",           KSTAT_DATA_UINT32 },
14182                 { "inOverFlows",        KSTAT_DATA_UINT32 },
14183                 { "inBadRedirects",     KSTAT_DATA_UINT32 },
14184         };
14185 
14186         ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14187             NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14188         if (ksp == NULL || ksp->ks_data == NULL)
14189                 return (NULL);
14190 
14191         bcopy(&template, ksp->ks_data, sizeof (template));
14192 
14193         ksp->ks_update = icmp_kstat_update;
14194         ksp->ks_private = (void *)(uintptr_t)stackid;
14195 
14196         kstat_install(ksp);
14197         return (ksp);
14198 }
14199 
14200 static void
14201 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14202 {
14203         if (ksp != NULL) {
14204                 ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14205                 kstat_delete_netstack(ksp, stackid);
14206         }
14207 }
14208 
14209 static int
14210 icmp_kstat_update(kstat_t *kp, int rw)
14211 {
14212         icmp_named_kstat_t *icmpkp;
14213         netstackid_t    stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14214         netstack_t      *ns;
14215         ip_stack_t      *ipst;
14216 
14217         if ((kp == NULL) || (kp->ks_data == NULL))
14218                 return (EIO);
14219 
14220         if (rw == KSTAT_WRITE)
14221                 return (EACCES);
14222 
14223         ns = netstack_find_by_stackid(stackid);
14224         if (ns == NULL)
14225                 return (-1);
14226         ipst = ns->netstack_ip;
14227         if (ipst == NULL) {
14228                 netstack_rele(ns);
14229                 return (-1);
14230         }
14231         icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14232 
14233         icmpkp->inMsgs.value.ui32 =      ipst->ips_icmp_mib.icmpInMsgs;
14234         icmpkp->inErrors.value.ui32 =            ipst->ips_icmp_mib.icmpInErrors;
14235         icmpkp->inDestUnreachs.value.ui32 =
14236             ipst->ips_icmp_mib.icmpInDestUnreachs;
14237         icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14238         icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14239         icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14240         icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14241         icmpkp->inEchos.value.ui32 =     ipst->ips_icmp_mib.icmpInEchos;
14242         icmpkp->inEchoReps.value.ui32 =          ipst->ips_icmp_mib.icmpInEchoReps;
14243         icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14244         icmpkp->inTimestampReps.value.ui32 =
14245             ipst->ips_icmp_mib.icmpInTimestampReps;
14246         icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14247         icmpkp->inAddrMaskReps.value.ui32 =
14248             ipst->ips_icmp_mib.icmpInAddrMaskReps;
14249         icmpkp->outMsgs.value.ui32 =     ipst->ips_icmp_mib.icmpOutMsgs;
14250         icmpkp->outErrors.value.ui32 =           ipst->ips_icmp_mib.icmpOutErrors;
14251         icmpkp->outDestUnreachs.value.ui32 =
14252             ipst->ips_icmp_mib.icmpOutDestUnreachs;
14253         icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14254         icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14255         icmpkp->outSrcQuenchs.value.ui32 =
14256             ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14257         icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14258         icmpkp->outEchos.value.ui32 =            ipst->ips_icmp_mib.icmpOutEchos;
14259         icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14260         icmpkp->outTimestamps.value.ui32 =
14261             ipst->ips_icmp_mib.icmpOutTimestamps;
14262         icmpkp->outTimestampReps.value.ui32 =
14263             ipst->ips_icmp_mib.icmpOutTimestampReps;
14264         icmpkp->outAddrMasks.value.ui32 =
14265             ipst->ips_icmp_mib.icmpOutAddrMasks;
14266         icmpkp->outAddrMaskReps.value.ui32 =
14267             ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14268         icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14269         icmpkp->inUnknowns.value.ui32 =          ipst->ips_icmp_mib.icmpInUnknowns;
14270         icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14271         icmpkp->outFragNeeded.value.ui32 =
14272             ipst->ips_icmp_mib.icmpOutFragNeeded;
14273         icmpkp->outDrops.value.ui32 =            ipst->ips_icmp_mib.icmpOutDrops;
14274         icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14275         icmpkp->inBadRedirects.value.ui32 =
14276             ipst->ips_icmp_mib.icmpInBadRedirects;
14277 
14278         netstack_rele(ns);
14279         return (0);
14280 }
14281 
14282 /*
14283  * This is the fanout function for raw socket opened for SCTP.  Note
14284  * that it is called after SCTP checks that there is no socket which
14285  * wants a packet.  Then before SCTP handles this out of the blue packet,
14286  * this function is called to see if there is any raw socket for SCTP.
14287  * If there is and it is bound to the correct address, the packet will
14288  * be sent to that socket.  Note that only one raw socket can be bound to
14289  * a port.  This is assured in ipcl_sctp_hash_insert();
14290  */
14291 void
14292 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14293     ip_recv_attr_t *ira)
14294 {
14295         conn_t          *connp;
14296         queue_t         *rq;
14297         boolean_t       secure;
14298         ill_t           *ill = ira->ira_ill;
14299         ip_stack_t      *ipst = ill->ill_ipst;
14300         ipsec_stack_t   *ipss = ipst->ips_netstack->netstack_ipsec;
14301         sctp_stack_t    *sctps = ipst->ips_netstack->netstack_sctp;
14302         iaflags_t       iraflags = ira->ira_flags;
14303         ill_t           *rill = ira->ira_rill;
14304 
14305         secure = iraflags & IRAF_IPSEC_SECURE;
14306 
14307         connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14308             ira, ipst);
14309         if (connp == NULL) {
14310                 /*
14311                  * Although raw sctp is not summed, OOB chunks must be.
14312                  * Drop the packet here if the sctp checksum failed.
14313                  */
14314                 if (iraflags & IRAF_SCTP_CSUM_ERR) {
14315                         SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14316                         freemsg(mp);
14317                         return;
14318                 }
14319                 ira->ira_ill = ira->ira_rill = NULL;
14320                 sctp_ootb_input(mp, ira, ipst);
14321                 ira->ira_ill = ill;
14322                 ira->ira_rill = rill;
14323                 return;
14324         }
14325         rq = connp->conn_rq;
14326         if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14327                 CONN_DEC_REF(connp);
14328                 BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14329                 freemsg(mp);
14330                 return;
14331         }
14332         if (((iraflags & IRAF_IS_IPV4) ?
14333             CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14334             CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14335             secure) {
14336                 mp = ipsec_check_inbound_policy(mp, connp, ipha,
14337                     ip6h, ira);
14338                 if (mp == NULL) {
14339                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14340                         /* Note that mp is NULL */
14341                         ip_drop_input("ipIfStatsInDiscards", mp, ill);
14342                         CONN_DEC_REF(connp);
14343                         return;
14344                 }
14345         }
14346 
14347         if (iraflags & IRAF_ICMP_ERROR) {
14348                 (connp->conn_recvicmp)(connp, mp, NULL, ira);
14349         } else {
14350                 ill_t *rill = ira->ira_rill;
14351 
14352                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14353                 /* This is the SOCK_RAW, IPPROTO_SCTP case. */
14354                 ira->ira_ill = ira->ira_rill = NULL;
14355                 (connp->conn_recv)(connp, mp, NULL, ira);
14356                 ira->ira_ill = ill;
14357                 ira->ira_rill = rill;
14358         }
14359         CONN_DEC_REF(connp);
14360 }
14361 
14362 /*
14363  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14364  * header before the ip payload.
14365  */
14366 static void
14367 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14368 {
14369         int len = (mp->b_wptr - mp->b_rptr);
14370         mblk_t *ip_mp;
14371 
14372         BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14373         if (is_fp_mp || len != fp_mp_len) {
14374                 if (len > fp_mp_len) {
14375                         /*
14376                          * fastpath header and ip header in the first mblk
14377                          */
14378                         mp->b_rptr += fp_mp_len;
14379                 } else {
14380                         /*
14381                          * ip_xmit_attach_llhdr had to prepend an mblk to
14382                          * attach the fastpath header before ip header.
14383                          */
14384                         ip_mp = mp->b_cont;
14385                         freeb(mp);
14386                         mp = ip_mp;
14387                         mp->b_rptr += (fp_mp_len - len);
14388                 }
14389         } else {
14390                 ip_mp = mp->b_cont;
14391                 freeb(mp);
14392                 mp = ip_mp;
14393         }
14394         ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14395         freemsg(mp);
14396 }
14397 
14398 /*
14399  * Normal post fragmentation function.
14400  *
14401  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14402  * using the same state machine.
14403  *
14404  * We return an error on failure. In particular we return EWOULDBLOCK
14405  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14406  * (currently by canputnext failure resulting in backenabling from GLD.)
14407  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14408  * indication that they can flow control until ip_wsrv() tells then to restart.
14409  *
14410  * If the nce passed by caller is incomplete, this function
14411  * queues the packet and if necessary, sends ARP request and bails.
14412  * If the Neighbor Cache passed is fully resolved, we simply prepend
14413  * the link-layer header to the packet, do ipsec hw acceleration
14414  * work if necessary, and send the packet out on the wire.
14415  */
14416 /* ARGSUSED6 */
14417 int
14418 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14419     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14420 {
14421         queue_t         *wq;
14422         ill_t           *ill = nce->nce_ill;
14423         ip_stack_t      *ipst = ill->ill_ipst;
14424         uint64_t        delta;
14425         boolean_t       isv6 = ill->ill_isv6;
14426         boolean_t       fp_mp;
14427         ncec_t          *ncec = nce->nce_common;
14428         int64_t         now = LBOLT_FASTPATH64;
14429         boolean_t       is_probe;
14430 
14431         DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14432 
14433         ASSERT(mp != NULL);
14434         ASSERT(mp->b_datap->db_type == M_DATA);
14435         ASSERT(pkt_len == msgdsize(mp));
14436 
14437         /*
14438          * If we have already been here and are coming back after ARP/ND.
14439          * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14440          * in that case since they have seen the packet when it came here
14441          * the first time.
14442          */
14443         if (ixaflags & IXAF_NO_TRACE)
14444                 goto sendit;
14445 
14446         if (ixaflags & IXAF_IS_IPV4) {
14447                 ipha_t *ipha = (ipha_t *)mp->b_rptr;
14448 
14449                 ASSERT(!isv6);
14450                 ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14451                 if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14452                     !(ixaflags & IXAF_NO_PFHOOK)) {
14453                         int     error;
14454 
14455                         FW_HOOKS(ipst->ips_ip4_physical_out_event,
14456                             ipst->ips_ipv4firewall_physical_out,
14457                             NULL, ill, ipha, mp, mp, 0, ipst, error);
14458                         DTRACE_PROBE1(ip4__physical__out__end,
14459                             mblk_t *, mp);
14460                         if (mp == NULL)
14461                                 return (error);
14462 
14463                         /* The length could have changed */
14464                         pkt_len = msgdsize(mp);
14465                 }
14466                 if (ipst->ips_ip4_observe.he_interested) {
14467                         /*
14468                          * Note that for TX the zoneid is the sending
14469                          * zone, whether or not MLP is in play.
14470                          * Since the szone argument is the IP zoneid (i.e.,
14471                          * zero for exclusive-IP zones) and ipobs wants
14472                          * the system zoneid, we map it here.
14473                          */
14474                         szone = IP_REAL_ZONEID(szone, ipst);
14475 
14476                         /*
14477                          * On the outbound path the destination zone will be
14478                          * unknown as we're sending this packet out on the
14479                          * wire.
14480                          */
14481                         ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14482                             ill, ipst);
14483                 }
14484                 DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14485                     void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14486                     ipha_t *, ipha, ip6_t *, NULL, int, 0);
14487         } else {
14488                 ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14489 
14490                 ASSERT(isv6);
14491                 ASSERT(pkt_len ==
14492                     ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14493                 if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14494                     !(ixaflags & IXAF_NO_PFHOOK)) {
14495                         int     error;
14496 
14497                         FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14498                             ipst->ips_ipv6firewall_physical_out,
14499                             NULL, ill, ip6h, mp, mp, 0, ipst, error);
14500                         DTRACE_PROBE1(ip6__physical__out__end,
14501                             mblk_t *, mp);
14502                         if (mp == NULL)
14503                                 return (error);
14504 
14505                         /* The length could have changed */
14506                         pkt_len = msgdsize(mp);
14507                 }
14508                 if (ipst->ips_ip6_observe.he_interested) {
14509                         /* See above */
14510                         szone = IP_REAL_ZONEID(szone, ipst);
14511 
14512                         ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14513                             ill, ipst);
14514                 }
14515                 DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14516                     void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14517                     ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14518         }
14519 
14520 sendit:
14521         /*
14522          * We check the state without a lock because the state can never
14523          * move "backwards" to initial or incomplete.
14524          */
14525         switch (ncec->ncec_state) {
14526         case ND_REACHABLE:
14527         case ND_STALE:
14528         case ND_DELAY:
14529         case ND_PROBE:
14530                 mp = ip_xmit_attach_llhdr(mp, nce);
14531                 if (mp == NULL) {
14532                         /*
14533                          * ip_xmit_attach_llhdr has increased
14534                          * ipIfStatsOutDiscards and called ip_drop_output()
14535                          */
14536                         return (ENOBUFS);
14537                 }
14538                 /*
14539                  * check if nce_fastpath completed and we tagged on a
14540                  * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14541                  */
14542                 fp_mp = (mp->b_datap->db_type == M_DATA);
14543 
14544                 if (fp_mp &&
14545                     (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14546                         ill_dld_direct_t *idd;
14547 
14548                         idd = &ill->ill_dld_capab->idc_direct;
14549                         /*
14550                          * Send the packet directly to DLD, where it
14551                          * may be queued depending on the availability
14552                          * of transmit resources at the media layer.
14553                          * Return value should be taken into
14554                          * account and flow control the TCP.
14555                          */
14556                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14557                         UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14558                             pkt_len);
14559 
14560                         if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14561                                 (void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14562                                     (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14563                         } else {
14564                                 uintptr_t cookie;
14565 
14566                                 if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14567                                     mp, (uintptr_t)xmit_hint, 0)) != 0) {
14568                                         if (ixacookie != NULL)
14569                                                 *ixacookie = cookie;
14570                                         return (EWOULDBLOCK);
14571                                 }
14572                         }
14573                 } else {
14574                         wq = ill->ill_wq;
14575 
14576                         if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14577                             !canputnext(wq)) {
14578                                 if (ixacookie != NULL)
14579                                         *ixacookie = 0;
14580                                 ip_xmit_flowctl_drop(ill, mp, fp_mp,
14581                                     nce->nce_fp_mp != NULL ?
14582                                     MBLKL(nce->nce_fp_mp) : 0);
14583                                 return (EWOULDBLOCK);
14584                         }
14585                         BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14586                         UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14587                             pkt_len);
14588                         putnext(wq, mp);
14589                 }
14590 
14591                 /*
14592                  * The rest of this function implements Neighbor Unreachability
14593                  * detection. Determine if the ncec is eligible for NUD.
14594                  */
14595                 if (ncec->ncec_flags & NCE_F_NONUD)
14596                         return (0);
14597 
14598                 ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14599 
14600                 /*
14601                  * Check for upper layer advice
14602                  */
14603                 if (ixaflags & IXAF_REACH_CONF) {
14604                         timeout_id_t tid;
14605 
14606                         /*
14607                          * It should be o.k. to check the state without
14608                          * a lock here, at most we lose an advice.
14609                          */
14610                         ncec->ncec_last = TICK_TO_MSEC(now);
14611                         if (ncec->ncec_state != ND_REACHABLE) {
14612                                 mutex_enter(&ncec->ncec_lock);
14613                                 ncec->ncec_state = ND_REACHABLE;
14614                                 tid = ncec->ncec_timeout_id;
14615                                 ncec->ncec_timeout_id = 0;
14616                                 mutex_exit(&ncec->ncec_lock);
14617                                 (void) untimeout(tid);
14618                                 if (ip_debug > 2) {
14619                                         /* ip1dbg */
14620                                         pr_addr_dbg("ip_xmit: state"
14621                                             " for %s changed to"
14622                                             " REACHABLE\n", AF_INET6,
14623                                             &ncec->ncec_addr);
14624                                 }
14625                         }
14626                         return (0);
14627                 }
14628 
14629                 delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14630                 ip1dbg(("ip_xmit: delta = %" PRId64
14631                     " ill_reachable_time = %d \n", delta,
14632                     ill->ill_reachable_time));
14633                 if (delta > (uint64_t)ill->ill_reachable_time) {
14634                         mutex_enter(&ncec->ncec_lock);
14635                         switch (ncec->ncec_state) {
14636                         case ND_REACHABLE:
14637                                 ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14638                                 /* FALLTHROUGH */
14639                         case ND_STALE:
14640                                 /*
14641                                  * ND_REACHABLE is identical to
14642                                  * ND_STALE in this specific case. If
14643                                  * reachable time has expired for this
14644                                  * neighbor (delta is greater than
14645                                  * reachable time), conceptually, the
14646                                  * neighbor cache is no longer in
14647                                  * REACHABLE state, but already in
14648                                  * STALE state.  So the correct
14649                                  * transition here is to ND_DELAY.
14650                                  */
14651                                 ncec->ncec_state = ND_DELAY;
14652                                 mutex_exit(&ncec->ncec_lock);
14653                                 nce_restart_timer(ncec,
14654                                     ipst->ips_delay_first_probe_time);
14655                                 if (ip_debug > 3) {
14656                                         /* ip2dbg */
14657                                         pr_addr_dbg("ip_xmit: state"
14658                                             " for %s changed to"
14659                                             " DELAY\n", AF_INET6,
14660                                             &ncec->ncec_addr);
14661                                 }
14662                                 break;
14663                         case ND_DELAY:
14664                         case ND_PROBE:
14665                                 mutex_exit(&ncec->ncec_lock);
14666                                 /* Timers have already started */
14667                                 break;
14668                         case ND_UNREACHABLE:
14669                                 /*
14670                                  * nce_timer has detected that this ncec
14671                                  * is unreachable and initiated deleting
14672                                  * this ncec.
14673                                  * This is a harmless race where we found the
14674                                  * ncec before it was deleted and have
14675                                  * just sent out a packet using this
14676                                  * unreachable ncec.
14677                                  */
14678                                 mutex_exit(&ncec->ncec_lock);
14679                                 break;
14680                         default:
14681                                 ASSERT(0);
14682                                 mutex_exit(&ncec->ncec_lock);
14683                         }
14684                 }
14685                 return (0);
14686 
14687         case ND_INCOMPLETE:
14688                 /*
14689                  * the state could have changed since we didn't hold the lock.
14690                  * Re-verify state under lock.
14691                  */
14692                 is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14693                 mutex_enter(&ncec->ncec_lock);
14694                 if (NCE_ISREACHABLE(ncec)) {
14695                         mutex_exit(&ncec->ncec_lock);
14696                         goto sendit;
14697                 }
14698                 /* queue the packet */
14699                 nce_queue_mp(ncec, mp, is_probe);
14700                 mutex_exit(&ncec->ncec_lock);
14701                 DTRACE_PROBE2(ip__xmit__incomplete,
14702                     (ncec_t *), ncec, (mblk_t *), mp);
14703                 return (0);
14704 
14705         case ND_INITIAL:
14706                 /*
14707                  * State could have changed since we didn't hold the lock, so
14708                  * re-verify state.
14709                  */
14710                 is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14711                 mutex_enter(&ncec->ncec_lock);
14712                 if (NCE_ISREACHABLE(ncec))  {
14713                         mutex_exit(&ncec->ncec_lock);
14714                         goto sendit;
14715                 }
14716                 nce_queue_mp(ncec, mp, is_probe);
14717                 if (ncec->ncec_state == ND_INITIAL) {
14718                         ncec->ncec_state = ND_INCOMPLETE;
14719                         mutex_exit(&ncec->ncec_lock);
14720                         /*
14721                          * figure out the source we want to use
14722                          * and resolve it.
14723                          */
14724                         ip_ndp_resolve(ncec);
14725                 } else  {
14726                         mutex_exit(&ncec->ncec_lock);
14727                 }
14728                 return (0);
14729 
14730         case ND_UNREACHABLE:
14731                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14732                 ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14733                     mp, ill);
14734                 freemsg(mp);
14735                 return (0);
14736 
14737         default:
14738                 ASSERT(0);
14739                 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14740                 ip_drop_output("ipIfStatsOutDiscards - ND_other",
14741                     mp, ill);
14742                 freemsg(mp);
14743                 return (ENETUNREACH);
14744         }
14745 }
14746 
14747 /*
14748  * Return B_TRUE if the buffers differ in length or content.
14749  * This is used for comparing extension header buffers.
14750  * Note that an extension header would be declared different
14751  * even if all that changed was the next header value in that header i.e.
14752  * what really changed is the next extension header.
14753  */
14754 boolean_t
14755 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14756     uint_t blen)
14757 {
14758         if (!b_valid)
14759                 blen = 0;
14760 
14761         if (alen != blen)
14762                 return (B_TRUE);
14763         if (alen == 0)
14764                 return (B_FALSE);       /* Both zero length */
14765         return (bcmp(abuf, bbuf, alen));
14766 }
14767 
14768 /*
14769  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14770  * Return B_FALSE if memory allocation fails - don't change any state!
14771  */
14772 boolean_t
14773 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14774     const void *src, uint_t srclen)
14775 {
14776         void *dst;
14777 
14778         if (!src_valid)
14779                 srclen = 0;
14780 
14781         ASSERT(*dstlenp == 0);
14782         if (src != NULL && srclen != 0) {
14783                 dst = mi_alloc(srclen, BPRI_MED);
14784                 if (dst == NULL)
14785                         return (B_FALSE);
14786         } else {
14787                 dst = NULL;
14788         }
14789         if (*dstp != NULL)
14790                 mi_free(*dstp);
14791         *dstp = dst;
14792         *dstlenp = dst == NULL ? 0 : srclen;
14793         return (B_TRUE);
14794 }
14795 
14796 /*
14797  * Replace what is in *dst, *dstlen with the source.
14798  * Assumes ip_allocbuf has already been called.
14799  */
14800 void
14801 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14802     const void *src, uint_t srclen)
14803 {
14804         if (!src_valid)
14805                 srclen = 0;
14806 
14807         ASSERT(*dstlenp == srclen);
14808         if (src != NULL && srclen != 0)
14809                 bcopy(src, *dstp, srclen);
14810 }
14811 
14812 /*
14813  * Free the storage pointed to by the members of an ip_pkt_t.
14814  */
14815 void
14816 ip_pkt_free(ip_pkt_t *ipp)
14817 {
14818         uint_t  fields = ipp->ipp_fields;
14819 
14820         if (fields & IPPF_HOPOPTS) {
14821                 kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14822                 ipp->ipp_hopopts = NULL;
14823                 ipp->ipp_hopoptslen = 0;
14824         }
14825         if (fields & IPPF_RTHDRDSTOPTS) {
14826                 kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14827                 ipp->ipp_rthdrdstopts = NULL;
14828                 ipp->ipp_rthdrdstoptslen = 0;
14829         }
14830         if (fields & IPPF_DSTOPTS) {
14831                 kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14832                 ipp->ipp_dstopts = NULL;
14833                 ipp->ipp_dstoptslen = 0;
14834         }
14835         if (fields & IPPF_RTHDR) {
14836                 kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14837                 ipp->ipp_rthdr = NULL;
14838                 ipp->ipp_rthdrlen = 0;
14839         }
14840         if (fields & IPPF_IPV4_OPTIONS) {
14841                 kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14842                 ipp->ipp_ipv4_options = NULL;
14843                 ipp->ipp_ipv4_options_len = 0;
14844         }
14845         if (fields & IPPF_LABEL_V4) {
14846                 kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14847                 ipp->ipp_label_v4 = NULL;
14848                 ipp->ipp_label_len_v4 = 0;
14849         }
14850         if (fields & IPPF_LABEL_V6) {
14851                 kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14852                 ipp->ipp_label_v6 = NULL;
14853                 ipp->ipp_label_len_v6 = 0;
14854         }
14855         ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14856             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14857 }
14858 
14859 /*
14860  * Copy from src to dst and allocate as needed.
14861  * Returns zero or ENOMEM.
14862  *
14863  * The caller must initialize dst to zero.
14864  */
14865 int
14866 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14867 {
14868         uint_t  fields = src->ipp_fields;
14869 
14870         /* Start with fields that don't require memory allocation */
14871         dst->ipp_fields = fields &
14872             ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14873             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14874 
14875         dst->ipp_addr = src->ipp_addr;
14876         dst->ipp_unicast_hops = src->ipp_unicast_hops;
14877         dst->ipp_hoplimit = src->ipp_hoplimit;
14878         dst->ipp_tclass = src->ipp_tclass;
14879         dst->ipp_type_of_service = src->ipp_type_of_service;
14880 
14881         if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14882             IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14883                 return (0);
14884 
14885         if (fields & IPPF_HOPOPTS) {
14886                 dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14887                 if (dst->ipp_hopopts == NULL) {
14888                         ip_pkt_free(dst);
14889                         return (ENOMEM);
14890                 }
14891                 dst->ipp_fields |= IPPF_HOPOPTS;
14892                 bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14893                     src->ipp_hopoptslen);
14894                 dst->ipp_hopoptslen = src->ipp_hopoptslen;
14895         }
14896         if (fields & IPPF_RTHDRDSTOPTS) {
14897                 dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14898                     kmflag);
14899                 if (dst->ipp_rthdrdstopts == NULL) {
14900                         ip_pkt_free(dst);
14901                         return (ENOMEM);
14902                 }
14903                 dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14904                 bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14905                     src->ipp_rthdrdstoptslen);
14906                 dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14907         }
14908         if (fields & IPPF_DSTOPTS) {
14909                 dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14910                 if (dst->ipp_dstopts == NULL) {
14911                         ip_pkt_free(dst);
14912                         return (ENOMEM);
14913                 }
14914                 dst->ipp_fields |= IPPF_DSTOPTS;
14915                 bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14916                     src->ipp_dstoptslen);
14917                 dst->ipp_dstoptslen = src->ipp_dstoptslen;
14918         }
14919         if (fields & IPPF_RTHDR) {
14920                 dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14921                 if (dst->ipp_rthdr == NULL) {
14922                         ip_pkt_free(dst);
14923                         return (ENOMEM);
14924                 }
14925                 dst->ipp_fields |= IPPF_RTHDR;
14926                 bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14927                     src->ipp_rthdrlen);
14928                 dst->ipp_rthdrlen = src->ipp_rthdrlen;
14929         }
14930         if (fields & IPPF_IPV4_OPTIONS) {
14931                 dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14932                     kmflag);
14933                 if (dst->ipp_ipv4_options == NULL) {
14934                         ip_pkt_free(dst);
14935                         return (ENOMEM);
14936                 }
14937                 dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14938                 bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14939                     src->ipp_ipv4_options_len);
14940                 dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14941         }
14942         if (fields & IPPF_LABEL_V4) {
14943                 dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14944                 if (dst->ipp_label_v4 == NULL) {
14945                         ip_pkt_free(dst);
14946                         return (ENOMEM);
14947                 }
14948                 dst->ipp_fields |= IPPF_LABEL_V4;
14949                 bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14950                     src->ipp_label_len_v4);
14951                 dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14952         }
14953         if (fields & IPPF_LABEL_V6) {
14954                 dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14955                 if (dst->ipp_label_v6 == NULL) {
14956                         ip_pkt_free(dst);
14957                         return (ENOMEM);
14958                 }
14959                 dst->ipp_fields |= IPPF_LABEL_V6;
14960                 bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14961                     src->ipp_label_len_v6);
14962                 dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14963         }
14964         if (fields & IPPF_FRAGHDR) {
14965                 dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14966                 if (dst->ipp_fraghdr == NULL) {
14967                         ip_pkt_free(dst);
14968                         return (ENOMEM);
14969                 }
14970                 dst->ipp_fields |= IPPF_FRAGHDR;
14971                 bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14972                     src->ipp_fraghdrlen);
14973                 dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14974         }
14975         return (0);
14976 }
14977 
14978 /*
14979  * Returns INADDR_ANY if no source route
14980  */
14981 ipaddr_t
14982 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14983 {
14984         ipaddr_t        nexthop = INADDR_ANY;
14985         ipoptp_t        opts;
14986         uchar_t         *opt;
14987         uint8_t         optval;
14988         uint8_t         optlen;
14989         uint32_t        totallen;
14990 
14991         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14992                 return (INADDR_ANY);
14993 
14994         totallen = ipp->ipp_ipv4_options_len;
14995         if (totallen & 0x3)
14996                 return (INADDR_ANY);
14997 
14998         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14999             optval != IPOPT_EOL;
15000             optval = ipoptp_next(&opts)) {
15001                 opt = opts.ipoptp_cur;
15002                 switch (optval) {
15003                         uint8_t off;
15004                 case IPOPT_SSRR:
15005                 case IPOPT_LSRR:
15006                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15007                                 break;
15008                         }
15009                         optlen = opts.ipoptp_len;
15010                         off = opt[IPOPT_OFFSET];
15011                         off--;
15012                         if (optlen < IP_ADDR_LEN ||
15013                             off > optlen - IP_ADDR_LEN) {
15014                                 /* End of source route */
15015                                 break;
15016                         }
15017                         bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15018                         if (nexthop == htonl(INADDR_LOOPBACK)) {
15019                                 /* Ignore */
15020                                 nexthop = INADDR_ANY;
15021                                 break;
15022                         }
15023                         break;
15024                 }
15025         }
15026         return (nexthop);
15027 }
15028 
15029 /*
15030  * Reverse a source route.
15031  */
15032 void
15033 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15034 {
15035         ipaddr_t        tmp;
15036         ipoptp_t        opts;
15037         uchar_t         *opt;
15038         uint8_t         optval;
15039         uint32_t        totallen;
15040 
15041         if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15042                 return;
15043 
15044         totallen = ipp->ipp_ipv4_options_len;
15045         if (totallen & 0x3)
15046                 return;
15047 
15048         for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15049             optval != IPOPT_EOL;
15050             optval = ipoptp_next(&opts)) {
15051                 uint8_t off1, off2;
15052 
15053                 opt = opts.ipoptp_cur;
15054                 switch (optval) {
15055                 case IPOPT_SSRR:
15056                 case IPOPT_LSRR:
15057                         if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15058                                 break;
15059                         }
15060                         off1 = IPOPT_MINOFF_SR - 1;
15061                         off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15062                         while (off2 > off1) {
15063                                 bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15064                                 bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15065                                 bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15066                                 off2 -= IP_ADDR_LEN;
15067                                 off1 += IP_ADDR_LEN;
15068                         }
15069                         opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15070                         break;
15071                 }
15072         }
15073 }
15074 
15075 /*
15076  * Returns NULL if no routing header
15077  */
15078 in6_addr_t *
15079 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15080 {
15081         in6_addr_t      *nexthop = NULL;
15082         ip6_rthdr0_t    *rthdr;
15083 
15084         if (!(ipp->ipp_fields & IPPF_RTHDR))
15085                 return (NULL);
15086 
15087         rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15088         if (rthdr->ip6r0_segleft == 0)
15089                 return (NULL);
15090 
15091         nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15092         return (nexthop);
15093 }
15094 
15095 zoneid_t
15096 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15097     zoneid_t lookup_zoneid)
15098 {
15099         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
15100         ire_t           *ire;
15101         int             ire_flags = MATCH_IRE_TYPE;
15102         zoneid_t        zoneid = ALL_ZONES;
15103 
15104         if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15105                 return (ALL_ZONES);
15106 
15107         if (lookup_zoneid != ALL_ZONES)
15108                 ire_flags |= MATCH_IRE_ZONEONLY;
15109         ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15110             NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15111         if (ire != NULL) {
15112                 zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15113                 ire_refrele(ire);
15114         }
15115         return (zoneid);
15116 }
15117 
15118 zoneid_t
15119 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15120     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15121 {
15122         ip_stack_t      *ipst = ira->ira_ill->ill_ipst;
15123         ire_t           *ire;
15124         int             ire_flags = MATCH_IRE_TYPE;
15125         zoneid_t        zoneid = ALL_ZONES;
15126 
15127         if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15128                 return (ALL_ZONES);
15129 
15130         if (IN6_IS_ADDR_LINKLOCAL(addr))
15131                 ire_flags |= MATCH_IRE_ILL;
15132 
15133         if (lookup_zoneid != ALL_ZONES)
15134                 ire_flags |= MATCH_IRE_ZONEONLY;
15135         ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15136             ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15137         if (ire != NULL) {
15138                 zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15139                 ire_refrele(ire);
15140         }
15141         return (zoneid);
15142 }
15143 
15144 /*
15145  * IP obserability hook support functions.
15146  */
15147 static void
15148 ipobs_init(ip_stack_t *ipst)
15149 {
15150         netid_t id;
15151 
15152         id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15153 
15154         ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15155         VERIFY(ipst->ips_ip4_observe_pr != NULL);
15156 
15157         ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15158         VERIFY(ipst->ips_ip6_observe_pr != NULL);
15159 }
15160 
15161 static void
15162 ipobs_fini(ip_stack_t *ipst)
15163 {
15164 
15165         VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15166         VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15167 }
15168 
15169 /*
15170  * hook_pkt_observe_t is composed in network byte order so that the
15171  * entire mblk_t chain handed into hook_run can be used as-is.
15172  * The caveat is that use of the fields, such as the zone fields,
15173  * requires conversion into host byte order first.
15174  */
15175 void
15176 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15177     const ill_t *ill, ip_stack_t *ipst)
15178 {
15179         hook_pkt_observe_t *hdr;
15180         uint64_t grifindex;
15181         mblk_t *imp;
15182 
15183         imp = allocb(sizeof (*hdr), BPRI_HI);
15184         if (imp == NULL)
15185                 return;
15186 
15187         hdr = (hook_pkt_observe_t *)imp->b_rptr;
15188         /*
15189          * b_wptr is set to make the apparent size of the data in the mblk_t
15190          * to exclude the pointers at the end of hook_pkt_observer_t.
15191          */
15192         imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15193         imp->b_cont = mp;
15194 
15195         ASSERT(DB_TYPE(mp) == M_DATA);
15196 
15197         if (IS_UNDER_IPMP(ill))
15198                 grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15199         else
15200                 grifindex = 0;
15201 
15202         hdr->hpo_version = 1;
15203         hdr->hpo_htype = htons(htype);
15204         hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15205         hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15206         hdr->hpo_grifindex = htonl(grifindex);
15207         hdr->hpo_zsrc = htonl(zsrc);
15208         hdr->hpo_zdst = htonl(zdst);
15209         hdr->hpo_pkt = imp;
15210         hdr->hpo_ctx = ipst->ips_netstack;
15211 
15212         if (ill->ill_isv6) {
15213                 hdr->hpo_family = AF_INET6;
15214                 (void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15215                     ipst->ips_ipv6observing, (hook_data_t)hdr);
15216         } else {
15217                 hdr->hpo_family = AF_INET;
15218                 (void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15219                     ipst->ips_ipv4observing, (hook_data_t)hdr);
15220         }
15221 
15222         imp->b_cont = NULL;
15223         freemsg(imp);
15224 }
15225 
15226 /*
15227  * Utility routine that checks if `v4srcp' is a valid address on underlying
15228  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15229  * associated with `v4srcp' on success.  NOTE: if this is not called from
15230  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15231  * group during or after this lookup.
15232  */
15233 boolean_t
15234 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15235 {
15236         ipif_t *ipif;
15237 
15238         ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15239         if (ipif != NULL) {
15240                 if (ipifp != NULL)
15241                         *ipifp = ipif;
15242                 else
15243                         ipif_refrele(ipif);
15244                 return (B_TRUE);
15245         }
15246 
15247         ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15248             *v4srcp));
15249         return (B_FALSE);
15250 }
15251 
15252 /*
15253  * Transport protocol call back function for CPU state change.
15254  */
15255 /* ARGSUSED */
15256 static int
15257 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15258 {
15259         processorid_t cpu_seqid;
15260         netstack_handle_t nh;
15261         netstack_t *ns;
15262 
15263         ASSERT(MUTEX_HELD(&cpu_lock));
15264 
15265         switch (what) {
15266         case CPU_CONFIG:
15267         case CPU_ON:
15268         case CPU_INIT:
15269         case CPU_CPUPART_IN:
15270                 cpu_seqid = cpu[id]->cpu_seqid;
15271                 netstack_next_init(&nh);
15272                 while ((ns = netstack_next(&nh)) != NULL) {
15273                         tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15274                         sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15275                         udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15276                         netstack_rele(ns);
15277                 }
15278                 netstack_next_fini(&nh);
15279                 break;
15280         case CPU_UNCONFIG:
15281         case CPU_OFF:
15282         case CPU_CPUPART_OUT:
15283                 /*
15284                  * Nothing to do.  We don't remove the per CPU stats from
15285                  * the IP stack even when the CPU goes offline.
15286                  */
15287                 break;
15288         default:
15289                 break;
15290         }
15291         return (0);
15292 }