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  */
  25 /* Copyright (c) 1990 Mentat Inc. */
  26 
  27 #include <sys/types.h>
  28 #include <sys/stream.h>
  29 #include <sys/strsun.h>
  30 #include <sys/strsubr.h>
  31 #include <sys/stropts.h>
  32 #include <sys/strlog.h>
  33 #define _SUN_TPI_VERSION 2
  34 #include <sys/tihdr.h>
  35 #include <sys/timod.h>
  36 #include <sys/ddi.h>
  37 #include <sys/sunddi.h>
  38 #include <sys/suntpi.h>
  39 #include <sys/xti_inet.h>
  40 #include <sys/cmn_err.h>
  41 #include <sys/debug.h>
  42 #include <sys/sdt.h>
  43 #include <sys/vtrace.h>
  44 #include <sys/kmem.h>
  45 #include <sys/ethernet.h>
  46 #include <sys/cpuvar.h>
  47 #include <sys/dlpi.h>
  48 #include <sys/pattr.h>
  49 #include <sys/policy.h>
  50 #include <sys/priv.h>
  51 #include <sys/zone.h>
  52 #include <sys/sunldi.h>
  53 
  54 #include <sys/errno.h>
  55 #include <sys/signal.h>
  56 #include <sys/socket.h>
  57 #include <sys/socketvar.h>
  58 #include <sys/sockio.h>
  59 #include <sys/isa_defs.h>
  60 #include <sys/md5.h>
  61 #include <sys/random.h>
  62 #include <sys/uio.h>
  63 #include <sys/systm.h>
  64 #include <netinet/in.h>
  65 #include <netinet/tcp.h>
  66 #include <netinet/ip6.h>
  67 #include <netinet/icmp6.h>
  68 #include <net/if.h>
  69 #include <net/route.h>
  70 #include <inet/ipsec_impl.h>
  71 
  72 #include <inet/common.h>
  73 #include <inet/ip.h>
  74 #include <inet/ip_impl.h>
  75 #include <inet/ip6.h>
  76 #include <inet/ip_ndp.h>
  77 #include <inet/proto_set.h>
  78 #include <inet/mib2.h>
  79 #include <inet/optcom.h>
  80 #include <inet/snmpcom.h>
  81 #include <inet/kstatcom.h>
  82 #include <inet/tcp.h>
  83 #include <inet/tcp_impl.h>
  84 #include <inet/tcp_cluster.h>
  85 #include <inet/udp_impl.h>
  86 #include <net/pfkeyv2.h>
  87 #include <inet/ipdrop.h>
  88 
  89 #include <inet/ipclassifier.h>
  90 #include <inet/ip_ire.h>
  91 #include <inet/ip_ftable.h>
  92 #include <inet/ip_if.h>
  93 #include <inet/ipp_common.h>
  94 #include <inet/ip_rts.h>
  95 #include <inet/ip_netinfo.h>
  96 #include <sys/squeue_impl.h>
  97 #include <sys/squeue.h>
  98 #include <sys/tsol/label.h>
  99 #include <sys/tsol/tnet.h>
 100 #include <rpc/pmap_prot.h>
 101 #include <sys/callo.h>
 102 
 103 /*
 104  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
 105  *
 106  * (Read the detailed design doc in PSARC case directory)
 107  *
 108  * The entire tcp state is contained in tcp_t and conn_t structure
 109  * which are allocated in tandem using ipcl_conn_create() and passing
 110  * IPCL_TCPCONN as a flag. We use 'conn_ref' and 'conn_lock' to protect
 111  * the references on the tcp_t. The tcp_t structure is never compressed
 112  * and packets always land on the correct TCP perimeter from the time
 113  * eager is created till the time tcp_t dies (as such the old mentat
 114  * TCP global queue is not used for detached state and no IPSEC checking
 115  * is required). The global queue is still allocated to send out resets
 116  * for connection which have no listeners and IP directly calls
 117  * tcp_xmit_listeners_reset() which does any policy check.
 118  *
 119  * Protection and Synchronisation mechanism:
 120  *
 121  * The tcp data structure does not use any kind of lock for protecting
 122  * its state but instead uses 'squeues' for mutual exclusion from various
 123  * read and write side threads. To access a tcp member, the thread should
 124  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
 125  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
 126  * can pass any tcp function having prototype of edesc_t as argument
 127  * (different from traditional STREAMs model where packets come in only
 128  * designated entry points). The list of functions that can be directly
 129  * called via squeue are listed before the usual function prototype.
 130  *
 131  * Referencing:
 132  *
 133  * TCP is MT-Hot and we use a reference based scheme to make sure that the
 134  * tcp structure doesn't disappear when its needed. When the application
 135  * creates an outgoing connection or accepts an incoming connection, we
 136  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
 137  * The IP reference is just a symbolic reference since ip_tcpclose()
 138  * looks at tcp structure after tcp_close_output() returns which could
 139  * have dropped the last TCP reference. So as long as the connection is
 140  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
 141  * conn_t. The classifier puts its own reference when the connection is
 142  * inserted in listen or connected hash. Anytime a thread needs to enter
 143  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
 144  * on write side or by doing a classify on read side and then puts a
 145  * reference on the conn before doing squeue_enter/tryenter/fill. For
 146  * read side, the classifier itself puts the reference under fanout lock
 147  * to make sure that tcp can't disappear before it gets processed. The
 148  * squeue will drop this reference automatically so the called function
 149  * doesn't have to do a DEC_REF.
 150  *
 151  * Opening a new connection:
 152  *
 153  * The outgoing connection open is pretty simple. tcp_open() does the
 154  * work in creating the conn/tcp structure and initializing it. The
 155  * squeue assignment is done based on the CPU the application
 156  * is running on. So for outbound connections, processing is always done
 157  * on application CPU which might be different from the incoming CPU
 158  * being interrupted by the NIC. An optimal way would be to figure out
 159  * the NIC <-> CPU binding at listen time, and assign the outgoing
 160  * connection to the squeue attached to the CPU that will be interrupted
 161  * for incoming packets (we know the NIC based on the bind IP address).
 162  * This might seem like a problem if more data is going out but the
 163  * fact is that in most cases the transmit is ACK driven transmit where
 164  * the outgoing data normally sits on TCP's xmit queue waiting to be
 165  * transmitted.
 166  *
 167  * Accepting a connection:
 168  *
 169  * This is a more interesting case because of various races involved in
 170  * establishing a eager in its own perimeter. Read the meta comment on
 171  * top of tcp_input_listener(). But briefly, the squeue is picked by
 172  * ip_fanout based on the ring or the sender (if loopback).
 173  *
 174  * Closing a connection:
 175  *
 176  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
 177  * via squeue to do the close and mark the tcp as detached if the connection
 178  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
 179  * reference but tcp_close() drop IP's reference always. So if tcp was
 180  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
 181  * and 1 because it is in classifier's connected hash. This is the condition
 182  * we use to determine that its OK to clean up the tcp outside of squeue
 183  * when time wait expires (check the ref under fanout and conn_lock and
 184  * if it is 2, remove it from fanout hash and kill it).
 185  *
 186  * Although close just drops the necessary references and marks the
 187  * tcp_detached state, tcp_close needs to know the tcp_detached has been
 188  * set (under squeue) before letting the STREAM go away (because a
 189  * inbound packet might attempt to go up the STREAM while the close
 190  * has happened and tcp_detached is not set). So a special lock and
 191  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
 192  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
 193  * tcp_detached.
 194  *
 195  * Special provisions and fast paths:
 196  *
 197  * We make special provisions for sockfs by marking tcp_issocket
 198  * whenever we have only sockfs on top of TCP. This allows us to skip
 199  * putting the tcp in acceptor hash since a sockfs listener can never
 200  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
 201  * since eager has already been allocated and the accept now happens
 202  * on acceptor STREAM. There is a big blob of comment on top of
 203  * tcp_input_listener explaining the new accept. When socket is POP'd,
 204  * sockfs sends us an ioctl to mark the fact and we go back to old
 205  * behaviour. Once tcp_issocket is unset, its never set for the
 206  * life of that connection.
 207  *
 208  * IPsec notes :
 209  *
 210  * Since a packet is always executed on the correct TCP perimeter
 211  * all IPsec processing is defered to IP including checking new
 212  * connections and setting IPSEC policies for new connection. The
 213  * only exception is tcp_xmit_listeners_reset() which is called
 214  * directly from IP and needs to policy check to see if TH_RST
 215  * can be sent out.
 216  */
 217 
 218 /*
 219  * Values for squeue switch:
 220  * 1: SQ_NODRAIN
 221  * 2: SQ_PROCESS
 222  * 3: SQ_FILL
 223  */
 224 int tcp_squeue_wput = 2;        /* /etc/systems */
 225 int tcp_squeue_flag;
 226 
 227 /*
 228  * To prevent memory hog, limit the number of entries in tcp_free_list
 229  * to 1% of available memory / number of cpus
 230  */
 231 uint_t tcp_free_list_max_cnt = 0;
 232 
 233 #define TCP_XMIT_LOWATER        4096
 234 #define TCP_XMIT_HIWATER        49152
 235 #define TCP_RECV_LOWATER        2048
 236 #define TCP_RECV_HIWATER        128000
 237 
 238 #define TIDUSZ  4096    /* transport interface data unit size */
 239 
 240 /*
 241  * Size of acceptor hash list.  It has to be a power of 2 for hashing.
 242  */
 243 #define TCP_ACCEPTOR_FANOUT_SIZE                256
 244 
 245 #ifdef  _ILP32
 246 #define TCP_ACCEPTOR_HASH(accid)                                        \
 247                 (((uint_t)(accid) >> 8) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
 248 #else
 249 #define TCP_ACCEPTOR_HASH(accid)                                        \
 250                 ((uint_t)(accid) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
 251 #endif  /* _ILP32 */
 252 
 253 /*
 254  * Minimum number of connections which can be created per listener.  Used
 255  * when the listener connection count is in effect.
 256  */
 257 static uint32_t tcp_min_conn_listener = 2;
 258 
 259 uint32_t tcp_early_abort = 30;
 260 
 261 /* TCP Timer control structure */
 262 typedef struct tcpt_s {
 263         pfv_t   tcpt_pfv;       /* The routine we are to call */
 264         tcp_t   *tcpt_tcp;      /* The parameter we are to pass in */
 265 } tcpt_t;
 266 
 267 /*
 268  * Functions called directly via squeue having a prototype of edesc_t.
 269  */
 270 void            tcp_input_listener(void *arg, mblk_t *mp, void *arg2,
 271     ip_recv_attr_t *ira);
 272 void            tcp_input_data(void *arg, mblk_t *mp, void *arg2,
 273     ip_recv_attr_t *ira);
 274 static void     tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2,
 275     ip_recv_attr_t *dummy);
 276 
 277 
 278 /* Prototype for TCP functions */
 279 static void     tcp_random_init(void);
 280 int             tcp_random(void);
 281 static int      tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
 282                     in_port_t dstport, uint_t srcid);
 283 static int      tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
 284                     in_port_t dstport, uint32_t flowinfo,
 285                     uint_t srcid, uint32_t scope_id);
 286 static void     tcp_iss_init(tcp_t *tcp);
 287 static void     tcp_reinit(tcp_t *tcp);
 288 static void     tcp_reinit_values(tcp_t *tcp);
 289 
 290 static void     tcp_wsrv(queue_t *q);
 291 static void     tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa);
 292 static void     tcp_update_zcopy(tcp_t *tcp);
 293 static void     tcp_notify(void *, ip_xmit_attr_t *, ixa_notify_type_t,
 294     ixa_notify_arg_t);
 295 static void     *tcp_stack_init(netstackid_t stackid, netstack_t *ns);
 296 static void     tcp_stack_fini(netstackid_t stackid, void *arg);
 297 
 298 static int      tcp_squeue_switch(int);
 299 
 300 static int      tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
 301 static int      tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
 302 static int      tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
 303 
 304 static void     tcp_squeue_add(squeue_t *);
 305 
 306 struct module_info tcp_rinfo =  {
 307         TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
 308 };
 309 
 310 static struct module_info tcp_winfo =  {
 311         TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
 312 };
 313 
 314 /*
 315  * Entry points for TCP as a device. The normal case which supports
 316  * the TCP functionality.
 317  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
 318  */
 319 struct qinit tcp_rinitv4 = {
 320         NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
 321 };
 322 
 323 struct qinit tcp_rinitv6 = {
 324         NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
 325 };
 326 
 327 struct qinit tcp_winit = {
 328         (pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
 329 };
 330 
 331 /* Initial entry point for TCP in socket mode. */
 332 struct qinit tcp_sock_winit = {
 333         (pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
 334 };
 335 
 336 /* TCP entry point during fallback */
 337 struct qinit tcp_fallback_sock_winit = {
 338         (pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
 339 };
 340 
 341 /*
 342  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
 343  * an accept. Avoid allocating data structures since eager has already
 344  * been created.
 345  */
 346 struct qinit tcp_acceptor_rinit = {
 347         NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
 348 };
 349 
 350 struct qinit tcp_acceptor_winit = {
 351         (pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
 352 };
 353 
 354 /* For AF_INET aka /dev/tcp */
 355 struct streamtab tcpinfov4 = {
 356         &tcp_rinitv4, &tcp_winit
 357 };
 358 
 359 /* For AF_INET6 aka /dev/tcp6 */
 360 struct streamtab tcpinfov6 = {
 361         &tcp_rinitv6, &tcp_winit
 362 };
 363 
 364 /*
 365  * Following assumes TPI alignment requirements stay along 32 bit
 366  * boundaries
 367  */
 368 #define ROUNDUP32(x) \
 369         (((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
 370 
 371 /* Template for response to info request. */
 372 struct T_info_ack tcp_g_t_info_ack = {
 373         T_INFO_ACK,             /* PRIM_type */
 374         0,                      /* TSDU_size */
 375         T_INFINITE,             /* ETSDU_size */
 376         T_INVALID,              /* CDATA_size */
 377         T_INVALID,              /* DDATA_size */
 378         sizeof (sin_t),         /* ADDR_size */
 379         0,                      /* OPT_size - not initialized here */
 380         TIDUSZ,                 /* TIDU_size */
 381         T_COTS_ORD,             /* SERV_type */
 382         TCPS_IDLE,              /* CURRENT_state */
 383         (XPG4_1|EXPINLINE)      /* PROVIDER_flag */
 384 };
 385 
 386 struct T_info_ack tcp_g_t_info_ack_v6 = {
 387         T_INFO_ACK,             /* PRIM_type */
 388         0,                      /* TSDU_size */
 389         T_INFINITE,             /* ETSDU_size */
 390         T_INVALID,              /* CDATA_size */
 391         T_INVALID,              /* DDATA_size */
 392         sizeof (sin6_t),        /* ADDR_size */
 393         0,                      /* OPT_size - not initialized here */
 394         TIDUSZ,         /* TIDU_size */
 395         T_COTS_ORD,             /* SERV_type */
 396         TCPS_IDLE,              /* CURRENT_state */
 397         (XPG4_1|EXPINLINE)      /* PROVIDER_flag */
 398 };
 399 
 400 /*
 401  * TCP tunables related declarations. Definitions are in tcp_tunables.c
 402  */
 403 extern mod_prop_info_t tcp_propinfo_tbl[];
 404 extern int tcp_propinfo_count;
 405 
 406 #define IS_VMLOANED_MBLK(mp) \
 407         (((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
 408 
 409 uint32_t do_tcpzcopy = 1;               /* 0: disable, 1: enable, 2: force */
 410 
 411 /*
 412  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
 413  * tunable settable via NDD.  Otherwise, the per-connection behavior is
 414  * determined dynamically during tcp_set_destination(), which is the default.
 415  */
 416 boolean_t tcp_static_maxpsz = B_FALSE;
 417 
 418 /*
 419  * If the receive buffer size is changed, this function is called to update
 420  * the upper socket layer on the new delayed receive wake up threshold.
 421  */
 422 static void
 423 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
 424 {
 425         uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
 426 
 427         if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
 428                 conn_t *connp = tcp->tcp_connp;
 429                 struct sock_proto_props sopp;
 430 
 431                 /*
 432                  * only increase rcvthresh upto default_threshold
 433                  */
 434                 if (new_rcvthresh > default_threshold)
 435                         new_rcvthresh = default_threshold;
 436 
 437                 sopp.sopp_flags = SOCKOPT_RCVTHRESH;
 438                 sopp.sopp_rcvthresh = new_rcvthresh;
 439 
 440                 (*connp->conn_upcalls->su_set_proto_props)
 441                     (connp->conn_upper_handle, &sopp);
 442         }
 443 }
 444 
 445 /*
 446  * Figure out the value of window scale opton.  Note that the rwnd is
 447  * ASSUMED to be rounded up to the nearest MSS before the calculation.
 448  * We cannot find the scale value and then do a round up of tcp_rwnd
 449  * because the scale value may not be correct after that.
 450  *
 451  * Set the compiler flag to make this function inline.
 452  */
 453 void
 454 tcp_set_ws_value(tcp_t *tcp)
 455 {
 456         int i;
 457         uint32_t rwnd = tcp->tcp_rwnd;
 458 
 459         for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
 460             i++, rwnd >>= 1)
 461                 ;
 462         tcp->tcp_rcv_ws = i;
 463 }
 464 
 465 /*
 466  * Remove cached/latched IPsec references.
 467  */
 468 void
 469 tcp_ipsec_cleanup(tcp_t *tcp)
 470 {
 471         conn_t          *connp = tcp->tcp_connp;
 472 
 473         ASSERT(connp->conn_flags & IPCL_TCPCONN);
 474 
 475         if (connp->conn_latch != NULL) {
 476                 IPLATCH_REFRELE(connp->conn_latch);
 477                 connp->conn_latch = NULL;
 478         }
 479         if (connp->conn_latch_in_policy != NULL) {
 480                 IPPOL_REFRELE(connp->conn_latch_in_policy);
 481                 connp->conn_latch_in_policy = NULL;
 482         }
 483         if (connp->conn_latch_in_action != NULL) {
 484                 IPACT_REFRELE(connp->conn_latch_in_action);
 485                 connp->conn_latch_in_action = NULL;
 486         }
 487         if (connp->conn_policy != NULL) {
 488                 IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
 489                 connp->conn_policy = NULL;
 490         }
 491 }
 492 
 493 /*
 494  * Cleaup before placing on free list.
 495  * Disassociate from the netstack/tcp_stack_t since the freelist
 496  * is per squeue and not per netstack.
 497  */
 498 void
 499 tcp_cleanup(tcp_t *tcp)
 500 {
 501         mblk_t          *mp;
 502         conn_t          *connp = tcp->tcp_connp;
 503         tcp_stack_t     *tcps = tcp->tcp_tcps;
 504         netstack_t      *ns = tcps->tcps_netstack;
 505         mblk_t          *tcp_rsrv_mp;
 506 
 507         tcp_bind_hash_remove(tcp);
 508 
 509         /* Cleanup that which needs the netstack first */
 510         tcp_ipsec_cleanup(tcp);
 511         ixa_cleanup(connp->conn_ixa);
 512 
 513         if (connp->conn_ht_iphc != NULL) {
 514                 kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
 515                 connp->conn_ht_iphc = NULL;
 516                 connp->conn_ht_iphc_allocated = 0;
 517                 connp->conn_ht_iphc_len = 0;
 518                 connp->conn_ht_ulp = NULL;
 519                 connp->conn_ht_ulp_len = 0;
 520                 tcp->tcp_ipha = NULL;
 521                 tcp->tcp_ip6h = NULL;
 522                 tcp->tcp_tcpha = NULL;
 523         }
 524 
 525         /* We clear any IP_OPTIONS and extension headers */
 526         ip_pkt_free(&connp->conn_xmit_ipp);
 527 
 528         tcp_free(tcp);
 529 
 530         /*
 531          * Since we will bzero the entire structure, we need to
 532          * remove it and reinsert it in global hash list. We
 533          * know the walkers can't get to this conn because we
 534          * had set CONDEMNED flag earlier and checked reference
 535          * under conn_lock so walker won't pick it and when we
 536          * go the ipcl_globalhash_remove() below, no walker
 537          * can get to it.
 538          */
 539         ipcl_globalhash_remove(connp);
 540 
 541         /* Save some state */
 542         mp = tcp->tcp_timercache;
 543 
 544         tcp_rsrv_mp = tcp->tcp_rsrv_mp;
 545 
 546         if (connp->conn_cred != NULL) {
 547                 crfree(connp->conn_cred);
 548                 connp->conn_cred = NULL;
 549         }
 550         ipcl_conn_cleanup(connp);
 551         connp->conn_flags = IPCL_TCPCONN;
 552 
 553         /*
 554          * Now it is safe to decrement the reference counts.
 555          * This might be the last reference on the netstack
 556          * in which case it will cause the freeing of the IP Instance.
 557          */
 558         connp->conn_netstack = NULL;
 559         connp->conn_ixa->ixa_ipst = NULL;
 560         netstack_rele(ns);
 561         ASSERT(tcps != NULL);
 562         tcp->tcp_tcps = NULL;
 563 
 564         bzero(tcp, sizeof (tcp_t));
 565 
 566         /* restore the state */
 567         tcp->tcp_timercache = mp;
 568 
 569         tcp->tcp_rsrv_mp = tcp_rsrv_mp;
 570 
 571         tcp->tcp_connp = connp;
 572 
 573         ASSERT(connp->conn_tcp == tcp);
 574         ASSERT(connp->conn_flags & IPCL_TCPCONN);
 575         connp->conn_state_flags = CONN_INCIPIENT;
 576         ASSERT(connp->conn_proto == IPPROTO_TCP);
 577         ASSERT(connp->conn_ref == 1);
 578 }
 579 
 580 /*
 581  * Adapt to the information, such as rtt and rtt_sd, provided from the
 582  * DCE and IRE maintained by IP.
 583  *
 584  * Checks for multicast and broadcast destination address.
 585  * Returns zero if ok; an errno on failure.
 586  *
 587  * Note that the MSS calculation here is based on the info given in
 588  * the DCE and IRE.  We do not do any calculation based on TCP options.  They
 589  * will be handled in tcp_input_data() when TCP knows which options to use.
 590  *
 591  * Note on how TCP gets its parameters for a connection.
 592  *
 593  * When a tcp_t structure is allocated, it gets all the default parameters.
 594  * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
 595  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
 596  * default.
 597  *
 598  * An incoming SYN with a multicast or broadcast destination address is dropped
 599  * in ip_fanout_v4/v6.
 600  *
 601  * An incoming SYN with a multicast or broadcast source address is always
 602  * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
 603  * conn_connect.
 604  * The same logic in tcp_set_destination also serves to
 605  * reject an attempt to connect to a broadcast or multicast (destination)
 606  * address.
 607  */
 608 int
 609 tcp_set_destination(tcp_t *tcp)
 610 {
 611         uint32_t        mss_max;
 612         uint32_t        mss;
 613         boolean_t       tcp_detached = TCP_IS_DETACHED(tcp);
 614         conn_t          *connp = tcp->tcp_connp;
 615         tcp_stack_t     *tcps = tcp->tcp_tcps;
 616         iulp_t          uinfo;
 617         int             error;
 618         uint32_t        flags;
 619 
 620         flags = IPDF_LSO | IPDF_ZCOPY;
 621         /*
 622          * Make sure we have a dce for the destination to avoid dce_ident
 623          * contention for connected sockets.
 624          */
 625         flags |= IPDF_UNIQUE_DCE;
 626 
 627         if (!tcps->tcps_ignore_path_mtu)
 628                 connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
 629 
 630         /* Use conn_lock to satify ASSERT; tcp is already serialized */
 631         mutex_enter(&connp->conn_lock);
 632         error = conn_connect(connp, &uinfo, flags);
 633         mutex_exit(&connp->conn_lock);
 634         if (error != 0)
 635                 return (error);
 636 
 637         error = tcp_build_hdrs(tcp);
 638         if (error != 0)
 639                 return (error);
 640 
 641         tcp->tcp_localnet = uinfo.iulp_localnet;
 642 
 643         if (uinfo.iulp_rtt != 0) {
 644                 clock_t rto;
 645 
 646                 tcp->tcp_rtt_sa = uinfo.iulp_rtt;
 647                 tcp->tcp_rtt_sd = uinfo.iulp_rtt_sd;
 648                 rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
 649                     tcps->tcps_rexmit_interval_extra +
 650                     (tcp->tcp_rtt_sa >> 5);
 651 
 652                 TCP_SET_RTO(tcp, rto);
 653         }
 654         if (uinfo.iulp_ssthresh != 0)
 655                 tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
 656         else
 657                 tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
 658         if (uinfo.iulp_spipe > 0) {
 659                 connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
 660                     tcps->tcps_max_buf);
 661                 if (tcps->tcps_snd_lowat_fraction != 0) {
 662                         connp->conn_sndlowat = connp->conn_sndbuf /
 663                             tcps->tcps_snd_lowat_fraction;
 664                 }
 665                 (void) tcp_maxpsz_set(tcp, B_TRUE);
 666         }
 667         /*
 668          * Note that up till now, acceptor always inherits receive
 669          * window from the listener.  But if there is a metrics
 670          * associated with a host, we should use that instead of
 671          * inheriting it from listener. Thus we need to pass this
 672          * info back to the caller.
 673          */
 674         if (uinfo.iulp_rpipe > 0) {
 675                 tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
 676                     tcps->tcps_max_buf);
 677         }
 678 
 679         if (uinfo.iulp_rtomax > 0) {
 680                 tcp->tcp_second_timer_threshold =
 681                     uinfo.iulp_rtomax;
 682         }
 683 
 684         /*
 685          * Use the metric option settings, iulp_tstamp_ok and
 686          * iulp_wscale_ok, only for active open. What this means
 687          * is that if the other side uses timestamp or window
 688          * scale option, TCP will also use those options. That
 689          * is for passive open.  If the application sets a
 690          * large window, window scale is enabled regardless of
 691          * the value in iulp_wscale_ok.  This is the behavior
 692          * since 2.6.  So we keep it.
 693          * The only case left in passive open processing is the
 694          * check for SACK.
 695          * For ECN, it should probably be like SACK.  But the
 696          * current value is binary, so we treat it like the other
 697          * cases.  The metric only controls active open.For passive
 698          * open, the ndd param, tcp_ecn_permitted, controls the
 699          * behavior.
 700          */
 701         if (!tcp_detached) {
 702                 /*
 703                  * The if check means that the following can only
 704                  * be turned on by the metrics only IRE, but not off.
 705                  */
 706                 if (uinfo.iulp_tstamp_ok)
 707                         tcp->tcp_snd_ts_ok = B_TRUE;
 708                 if (uinfo.iulp_wscale_ok)
 709                         tcp->tcp_snd_ws_ok = B_TRUE;
 710                 if (uinfo.iulp_sack == 2)
 711                         tcp->tcp_snd_sack_ok = B_TRUE;
 712                 if (uinfo.iulp_ecn_ok)
 713                         tcp->tcp_ecn_ok = B_TRUE;
 714         } else {
 715                 /*
 716                  * Passive open.
 717                  *
 718                  * As above, the if check means that SACK can only be
 719                  * turned on by the metric only IRE.
 720                  */
 721                 if (uinfo.iulp_sack > 0) {
 722                         tcp->tcp_snd_sack_ok = B_TRUE;
 723                 }
 724         }
 725 
 726         /*
 727          * XXX Note that currently, iulp_mtu can be as small as 68
 728          * because of PMTUd.  So tcp_mss may go to negative if combined
 729          * length of all those options exceeds 28 bytes.  But because
 730          * of the tcp_mss_min check below, we may not have a problem if
 731          * tcp_mss_min is of a reasonable value.  The default is 1 so
 732          * the negative problem still exists.  And the check defeats PMTUd.
 733          * In fact, if PMTUd finds that the MSS should be smaller than
 734          * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
 735          * value.
 736          *
 737          * We do not deal with that now.  All those problems related to
 738          * PMTUd will be fixed later.
 739          */
 740         ASSERT(uinfo.iulp_mtu != 0);
 741         mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
 742 
 743         /* Sanity check for MSS value. */
 744         if (connp->conn_ipversion == IPV4_VERSION)
 745                 mss_max = tcps->tcps_mss_max_ipv4;
 746         else
 747                 mss_max = tcps->tcps_mss_max_ipv6;
 748 
 749         if (tcp->tcp_ipsec_overhead == 0)
 750                 tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
 751 
 752         mss -= tcp->tcp_ipsec_overhead;
 753 
 754         if (mss < tcps->tcps_mss_min)
 755                 mss = tcps->tcps_mss_min;
 756         if (mss > mss_max)
 757                 mss = mss_max;
 758 
 759         /* Note that this is the maximum MSS, excluding all options. */
 760         tcp->tcp_mss = mss;
 761 
 762         /*
 763          * Update the tcp connection with LSO capability.
 764          */
 765         tcp_update_lso(tcp, connp->conn_ixa);
 766 
 767         /*
 768          * Initialize the ISS here now that we have the full connection ID.
 769          * The RFC 1948 method of initial sequence number generation requires
 770          * knowledge of the full connection ID before setting the ISS.
 771          */
 772         tcp_iss_init(tcp);
 773 
 774         tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
 775 
 776         /*
 777          * Make sure that conn is not marked incipient
 778          * for incoming connections. A blind
 779          * removal of incipient flag is cheaper than
 780          * check and removal.
 781          */
 782         mutex_enter(&connp->conn_lock);
 783         connp->conn_state_flags &= ~CONN_INCIPIENT;
 784         mutex_exit(&connp->conn_lock);
 785         return (0);
 786 }
 787 
 788 /*
 789  * tcp_clean_death / tcp_close_detached must not be called more than once
 790  * on a tcp. Thus every function that potentially calls tcp_clean_death
 791  * must check for the tcp state before calling tcp_clean_death.
 792  * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
 793  * tcp_timer_handler, all check for the tcp state.
 794  */
 795 /* ARGSUSED */
 796 void
 797 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
 798     ip_recv_attr_t *dummy)
 799 {
 800         tcp_t   *tcp = ((conn_t *)arg)->conn_tcp;
 801 
 802         freemsg(mp);
 803         if (tcp->tcp_state > TCPS_BOUND)
 804                 (void) tcp_clean_death(((conn_t *)arg)->conn_tcp, ETIMEDOUT);
 805 }
 806 
 807 /*
 808  * We are dying for some reason.  Try to do it gracefully.  (May be called
 809  * as writer.)
 810  *
 811  * Return -1 if the structure was not cleaned up (if the cleanup had to be
 812  * done by a service procedure).
 813  * TBD - Should the return value distinguish between the tcp_t being
 814  * freed and it being reinitialized?
 815  */
 816 int
 817 tcp_clean_death(tcp_t *tcp, int err)
 818 {
 819         mblk_t  *mp;
 820         queue_t *q;
 821         conn_t  *connp = tcp->tcp_connp;
 822         tcp_stack_t     *tcps = tcp->tcp_tcps;
 823 
 824         if (tcp->tcp_fused)
 825                 tcp_unfuse(tcp);
 826 
 827         if (tcp->tcp_linger_tid != 0 &&
 828             TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
 829                 tcp_stop_lingering(tcp);
 830         }
 831 
 832         ASSERT(tcp != NULL);
 833         ASSERT((connp->conn_family == AF_INET &&
 834             connp->conn_ipversion == IPV4_VERSION) ||
 835             (connp->conn_family == AF_INET6 &&
 836             (connp->conn_ipversion == IPV4_VERSION ||
 837             connp->conn_ipversion == IPV6_VERSION)));
 838 
 839         if (TCP_IS_DETACHED(tcp)) {
 840                 if (tcp->tcp_hard_binding) {
 841                         /*
 842                          * Its an eager that we are dealing with. We close the
 843                          * eager but in case a conn_ind has already gone to the
 844                          * listener, let tcp_accept_finish() send a discon_ind
 845                          * to the listener and drop the last reference. If the
 846                          * listener doesn't even know about the eager i.e. the
 847                          * conn_ind hasn't gone up, blow away the eager and drop
 848                          * the last reference as well. If the conn_ind has gone
 849                          * up, state should be BOUND. tcp_accept_finish
 850                          * will figure out that the connection has received a
 851                          * RST and will send a DISCON_IND to the application.
 852                          */
 853                         tcp_closei_local(tcp);
 854                         if (!tcp->tcp_tconnind_started) {
 855                                 CONN_DEC_REF(connp);
 856                         } else {
 857                                 tcp->tcp_state = TCPS_BOUND;
 858                                 DTRACE_TCP6(state__change, void, NULL,
 859                                     ip_xmit_attr_t *, connp->conn_ixa,
 860                                     void, NULL, tcp_t *, tcp, void, NULL,
 861                                     int32_t, TCPS_CLOSED);
 862                         }
 863                 } else {
 864                         tcp_close_detached(tcp);
 865                 }
 866                 return (0);
 867         }
 868 
 869         TCP_STAT(tcps, tcp_clean_death_nondetached);
 870 
 871         /*
 872          * The connection is dead.  Decrement listener connection counter if
 873          * necessary.
 874          */
 875         if (tcp->tcp_listen_cnt != NULL)
 876                 TCP_DECR_LISTEN_CNT(tcp);
 877 
 878         /*
 879          * When a connection is moved to TIME_WAIT state, the connection
 880          * counter is already decremented.  So no need to decrement here
 881          * again.  See SET_TIME_WAIT() macro.
 882          */
 883         if (tcp->tcp_state >= TCPS_ESTABLISHED &&
 884             tcp->tcp_state < TCPS_TIME_WAIT) {
 885                 TCPS_CONN_DEC(tcps);
 886         }
 887 
 888         q = connp->conn_rq;
 889 
 890         /* Trash all inbound data */
 891         if (!IPCL_IS_NONSTR(connp)) {
 892                 ASSERT(q != NULL);
 893                 flushq(q, FLUSHALL);
 894         }
 895 
 896         /*
 897          * If we are at least part way open and there is error
 898          * (err==0 implies no error)
 899          * notify our client by a T_DISCON_IND.
 900          */
 901         if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
 902                 if (tcp->tcp_state >= TCPS_ESTABLISHED &&
 903                     !TCP_IS_SOCKET(tcp)) {
 904                         /*
 905                          * Send M_FLUSH according to TPI. Because sockets will
 906                          * (and must) ignore FLUSHR we do that only for TPI
 907                          * endpoints and sockets in STREAMS mode.
 908                          */
 909                         (void) putnextctl1(q, M_FLUSH, FLUSHR);
 910                 }
 911                 if (connp->conn_debug) {
 912                         (void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
 913                             "tcp_clean_death: discon err %d", err);
 914                 }
 915                 if (IPCL_IS_NONSTR(connp)) {
 916                         /* Direct socket, use upcall */
 917                         (*connp->conn_upcalls->su_disconnected)(
 918                             connp->conn_upper_handle, tcp->tcp_connid, err);
 919                 } else {
 920                         mp = mi_tpi_discon_ind(NULL, err, 0);
 921                         if (mp != NULL) {
 922                                 putnext(q, mp);
 923                         } else {
 924                                 if (connp->conn_debug) {
 925                                         (void) strlog(TCP_MOD_ID, 0, 1,
 926                                             SL_ERROR|SL_TRACE,
 927                                             "tcp_clean_death, sending M_ERROR");
 928                                 }
 929                                 (void) putnextctl1(q, M_ERROR, EPROTO);
 930                         }
 931                 }
 932                 if (tcp->tcp_state <= TCPS_SYN_RCVD) {
 933                         /* SYN_SENT or SYN_RCVD */
 934                         TCPS_BUMP_MIB(tcps, tcpAttemptFails);
 935                 } else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
 936                         /* ESTABLISHED or CLOSE_WAIT */
 937                         TCPS_BUMP_MIB(tcps, tcpEstabResets);
 938                 }
 939         }
 940 
 941         /*
 942          * ESTABLISHED non-STREAMS eagers are not 'detached' because
 943          * an upper handle is obtained when the SYN-ACK comes in. So it
 944          * should receive the 'disconnected' upcall, but tcp_reinit should
 945          * not be called since this is an eager.
 946          */
 947         if (tcp->tcp_listener != NULL && IPCL_IS_NONSTR(connp)) {
 948                 tcp_closei_local(tcp);
 949                 tcp->tcp_state = TCPS_BOUND;
 950                 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
 951                     connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
 952                     int32_t, TCPS_CLOSED);
 953                 return (0);
 954         }
 955 
 956         tcp_reinit(tcp);
 957         if (IPCL_IS_NONSTR(connp))
 958                 (void) tcp_do_unbind(connp);
 959 
 960         return (-1);
 961 }
 962 
 963 /*
 964  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
 965  * to expire, stop the wait and finish the close.
 966  */
 967 void
 968 tcp_stop_lingering(tcp_t *tcp)
 969 {
 970         clock_t delta = 0;
 971         tcp_stack_t     *tcps = tcp->tcp_tcps;
 972         conn_t          *connp = tcp->tcp_connp;
 973 
 974         tcp->tcp_linger_tid = 0;
 975         if (tcp->tcp_state > TCPS_LISTEN) {
 976                 tcp_acceptor_hash_remove(tcp);
 977                 mutex_enter(&tcp->tcp_non_sq_lock);
 978                 if (tcp->tcp_flow_stopped) {
 979                         tcp_clrqfull(tcp);
 980                 }
 981                 mutex_exit(&tcp->tcp_non_sq_lock);
 982 
 983                 if (tcp->tcp_timer_tid != 0) {
 984                         delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
 985                         tcp->tcp_timer_tid = 0;
 986                 }
 987                 /*
 988                  * Need to cancel those timers which will not be used when
 989                  * TCP is detached.  This has to be done before the conn_wq
 990                  * is cleared.
 991                  */
 992                 tcp_timers_stop(tcp);
 993 
 994                 tcp->tcp_detached = B_TRUE;
 995                 connp->conn_rq = NULL;
 996                 connp->conn_wq = NULL;
 997 
 998                 if (tcp->tcp_state == TCPS_TIME_WAIT) {
 999                         tcp_time_wait_append(tcp);
1000                         TCP_DBGSTAT(tcps, tcp_detach_time_wait);
1001                         goto finish;
1002                 }
1003 
1004                 /*
1005                  * If delta is zero the timer event wasn't executed and was
1006                  * successfully canceled. In this case we need to restart it
1007                  * with the minimal delta possible.
1008                  */
1009                 if (delta >= 0) {
1010                         tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
1011                             delta ? delta : 1);
1012                 }
1013         } else {
1014                 tcp_closei_local(tcp);
1015                 CONN_DEC_REF(connp);
1016         }
1017 finish:
1018         tcp->tcp_detached = B_TRUE;
1019         connp->conn_rq = NULL;
1020         connp->conn_wq = NULL;
1021 
1022         /* Signal closing thread that it can complete close */
1023         mutex_enter(&tcp->tcp_closelock);
1024         tcp->tcp_closed = 1;
1025         cv_signal(&tcp->tcp_closecv);
1026         mutex_exit(&tcp->tcp_closelock);
1027 
1028         /* If we have an upper handle (socket), release it */
1029         if (IPCL_IS_NONSTR(connp)) {
1030                 ASSERT(connp->conn_upper_handle != NULL);
1031                 (*connp->conn_upcalls->su_closed)(connp->conn_upper_handle);
1032                 connp->conn_upper_handle = NULL;
1033                 connp->conn_upcalls = NULL;
1034         }
1035 }
1036 
1037 void
1038 tcp_close_common(conn_t *connp, int flags)
1039 {
1040         tcp_t           *tcp = connp->conn_tcp;
1041         mblk_t          *mp = &tcp->tcp_closemp;
1042         boolean_t       conn_ioctl_cleanup_reqd = B_FALSE;
1043         mblk_t          *bp;
1044 
1045         ASSERT(connp->conn_ref >= 2);
1046 
1047         /*
1048          * Mark the conn as closing. ipsq_pending_mp_add will not
1049          * add any mp to the pending mp list, after this conn has
1050          * started closing.
1051          */
1052         mutex_enter(&connp->conn_lock);
1053         connp->conn_state_flags |= CONN_CLOSING;
1054         if (connp->conn_oper_pending_ill != NULL)
1055                 conn_ioctl_cleanup_reqd = B_TRUE;
1056         CONN_INC_REF_LOCKED(connp);
1057         mutex_exit(&connp->conn_lock);
1058         tcp->tcp_closeflags = (uint8_t)flags;
1059         ASSERT(connp->conn_ref >= 3);
1060 
1061         /*
1062          * tcp_closemp_used is used below without any protection of a lock
1063          * as we don't expect any one else to use it concurrently at this
1064          * point otherwise it would be a major defect.
1065          */
1066 
1067         if (mp->b_prev == NULL)
1068                 tcp->tcp_closemp_used = B_TRUE;
1069         else
1070                 cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
1071                     "connp %p tcp %p\n", (void *)connp, (void *)tcp);
1072 
1073         TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1074 
1075         /*
1076          * Cleanup any queued ioctls here. This must be done before the wq/rq
1077          * are re-written by tcp_close_output().
1078          */
1079         if (conn_ioctl_cleanup_reqd)
1080                 conn_ioctl_cleanup(connp);
1081 
1082         /*
1083          * As CONN_CLOSING is set, no further ioctls should be passed down to
1084          * IP for this conn (see the guards in tcp_ioctl, tcp_wput_ioctl and
1085          * tcp_wput_iocdata). If the ioctl was queued on an ipsq,
1086          * conn_ioctl_cleanup should have found it and removed it. If the ioctl
1087          * was still in flight at the time, we wait for it here. See comments
1088          * for CONN_INC_IOCTLREF in ip.h for details.
1089          */
1090         mutex_enter(&connp->conn_lock);
1091         while (connp->conn_ioctlref > 0)
1092                 cv_wait(&connp->conn_cv, &connp->conn_lock);
1093         ASSERT(connp->conn_ioctlref == 0);
1094         ASSERT(connp->conn_oper_pending_ill == NULL);
1095         mutex_exit(&connp->conn_lock);
1096 
1097         SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
1098             NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
1099 
1100         /*
1101          * For non-STREAMS sockets, the normal case is that the conn makes
1102          * an upcall when it's finally closed, so there is no need to wait
1103          * in the protocol. But in case of SO_LINGER the thread sleeps here
1104          * so it can properly deal with the thread being interrupted.
1105          */
1106         if (IPCL_IS_NONSTR(connp) && connp->conn_linger == 0)
1107                 goto nowait;
1108 
1109         mutex_enter(&tcp->tcp_closelock);
1110         while (!tcp->tcp_closed) {
1111                 if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
1112                         /*
1113                          * The cv_wait_sig() was interrupted. We now do the
1114                          * following:
1115                          *
1116                          * 1) If the endpoint was lingering, we allow this
1117                          * to be interrupted by cancelling the linger timeout
1118                          * and closing normally.
1119                          *
1120                          * 2) Revert to calling cv_wait()
1121                          *
1122                          * We revert to using cv_wait() to avoid an
1123                          * infinite loop which can occur if the calling
1124                          * thread is higher priority than the squeue worker
1125                          * thread and is bound to the same cpu.
1126                          */
1127                         if (connp->conn_linger && connp->conn_lingertime > 0) {
1128                                 mutex_exit(&tcp->tcp_closelock);
1129                                 /* Entering squeue, bump ref count. */
1130                                 CONN_INC_REF(connp);
1131                                 bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
1132                                 SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
1133                                     tcp_linger_interrupted, connp, NULL,
1134                                     tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
1135                                 mutex_enter(&tcp->tcp_closelock);
1136                         }
1137                         break;
1138                 }
1139         }
1140         while (!tcp->tcp_closed)
1141                 cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
1142         mutex_exit(&tcp->tcp_closelock);
1143 
1144         /*
1145          * In the case of listener streams that have eagers in the q or q0
1146          * we wait for the eagers to drop their reference to us. conn_rq and
1147          * conn_wq of the eagers point to our queues. By waiting for the
1148          * refcnt to drop to 1, we are sure that the eagers have cleaned
1149          * up their queue pointers and also dropped their references to us.
1150          *
1151          * For non-STREAMS sockets we do not have to wait here; the
1152          * listener will instead make a su_closed upcall when the last
1153          * reference is dropped.
1154          */
1155         if (tcp->tcp_wait_for_eagers && !IPCL_IS_NONSTR(connp)) {
1156                 mutex_enter(&connp->conn_lock);
1157                 while (connp->conn_ref != 1) {
1158                         cv_wait(&connp->conn_cv, &connp->conn_lock);
1159                 }
1160                 mutex_exit(&connp->conn_lock);
1161         }
1162 
1163 nowait:
1164         connp->conn_cpid = NOPID;
1165 }
1166 
1167 /*
1168  * Called by tcp_close() routine via squeue when lingering is
1169  * interrupted by a signal.
1170  */
1171 
1172 /* ARGSUSED */
1173 static void
1174 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1175 {
1176         conn_t  *connp = (conn_t *)arg;
1177         tcp_t   *tcp = connp->conn_tcp;
1178 
1179         freeb(mp);
1180         if (tcp->tcp_linger_tid != 0 &&
1181             TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
1182                 tcp_stop_lingering(tcp);
1183                 tcp->tcp_client_errno = EINTR;
1184         }
1185 }
1186 
1187 /*
1188  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
1189  * Some stream heads get upset if they see these later on as anything but NULL.
1190  */
1191 void
1192 tcp_close_mpp(mblk_t **mpp)
1193 {
1194         mblk_t  *mp;
1195 
1196         if ((mp = *mpp) != NULL) {
1197                 do {
1198                         mp->b_next = NULL;
1199                         mp->b_prev = NULL;
1200                 } while ((mp = mp->b_cont) != NULL);
1201 
1202                 mp = *mpp;
1203                 *mpp = NULL;
1204                 freemsg(mp);
1205         }
1206 }
1207 
1208 /* Do detached close. */
1209 void
1210 tcp_close_detached(tcp_t *tcp)
1211 {
1212         if (tcp->tcp_fused)
1213                 tcp_unfuse(tcp);
1214 
1215         /*
1216          * Clustering code serializes TCP disconnect callbacks and
1217          * cluster tcp list walks by blocking a TCP disconnect callback
1218          * if a cluster tcp list walk is in progress. This ensures
1219          * accurate accounting of TCPs in the cluster code even though
1220          * the TCP list walk itself is not atomic.
1221          */
1222         tcp_closei_local(tcp);
1223         CONN_DEC_REF(tcp->tcp_connp);
1224 }
1225 
1226 /*
1227  * The tcp_t is going away. Remove it from all lists and set it
1228  * to TCPS_CLOSED. The freeing up of memory is deferred until
1229  * tcp_inactive. This is needed since a thread in tcp_rput might have
1230  * done a CONN_INC_REF on this structure before it was removed from the
1231  * hashes.
1232  */
1233 void
1234 tcp_closei_local(tcp_t *tcp)
1235 {
1236         conn_t          *connp = tcp->tcp_connp;
1237         tcp_stack_t     *tcps = tcp->tcp_tcps;
1238         int32_t         oldstate;
1239 
1240         if (!TCP_IS_SOCKET(tcp))
1241                 tcp_acceptor_hash_remove(tcp);
1242 
1243         TCPS_UPDATE_MIB(tcps, tcpHCInSegs, tcp->tcp_ibsegs);
1244         tcp->tcp_ibsegs = 0;
1245         TCPS_UPDATE_MIB(tcps, tcpHCOutSegs, tcp->tcp_obsegs);
1246         tcp->tcp_obsegs = 0;
1247 
1248         /*
1249          * This can be called via tcp_time_wait_processing() if TCP gets a
1250          * SYN with sequence number outside the TIME-WAIT connection's
1251          * window.  So we need to check for TIME-WAIT state here as the
1252          * connection counter is already decremented.  See SET_TIME_WAIT()
1253          * macro
1254          */
1255         if (tcp->tcp_state >= TCPS_ESTABLISHED &&
1256             tcp->tcp_state < TCPS_TIME_WAIT) {
1257                 TCPS_CONN_DEC(tcps);
1258         }
1259 
1260         /*
1261          * If we are an eager connection hanging off a listener that
1262          * hasn't formally accepted the connection yet, get off his
1263          * list and blow off any data that we have accumulated.
1264          */
1265         if (tcp->tcp_listener != NULL) {
1266                 tcp_t   *listener = tcp->tcp_listener;
1267                 mutex_enter(&listener->tcp_eager_lock);
1268                 /*
1269                  * tcp_tconnind_started == B_TRUE means that the
1270                  * conn_ind has already gone to listener. At
1271                  * this point, eager will be closed but we
1272                  * leave it in listeners eager list so that
1273                  * if listener decides to close without doing
1274                  * accept, we can clean this up. In tcp_tli_accept
1275                  * we take care of the case of accept on closed
1276                  * eager.
1277                  */
1278                 if (!tcp->tcp_tconnind_started) {
1279                         tcp_eager_unlink(tcp);
1280                         mutex_exit(&listener->tcp_eager_lock);
1281                         /*
1282                          * We don't want to have any pointers to the
1283                          * listener queue, after we have released our
1284                          * reference on the listener
1285                          */
1286                         ASSERT(tcp->tcp_detached);
1287                         connp->conn_rq = NULL;
1288                         connp->conn_wq = NULL;
1289                         CONN_DEC_REF(listener->tcp_connp);
1290                 } else {
1291                         mutex_exit(&listener->tcp_eager_lock);
1292                 }
1293         }
1294 
1295         /* Stop all the timers */
1296         tcp_timers_stop(tcp);
1297 
1298         if (tcp->tcp_state == TCPS_LISTEN) {
1299                 if (tcp->tcp_ip_addr_cache) {
1300                         kmem_free((void *)tcp->tcp_ip_addr_cache,
1301                             IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1302                         tcp->tcp_ip_addr_cache = NULL;
1303                 }
1304         }
1305 
1306         /* Decrement listerner connection counter if necessary. */
1307         if (tcp->tcp_listen_cnt != NULL)
1308                 TCP_DECR_LISTEN_CNT(tcp);
1309 
1310         mutex_enter(&tcp->tcp_non_sq_lock);
1311         if (tcp->tcp_flow_stopped)
1312                 tcp_clrqfull(tcp);
1313         mutex_exit(&tcp->tcp_non_sq_lock);
1314 
1315         tcp_bind_hash_remove(tcp);
1316         /*
1317          * If the tcp_time_wait_collector (which runs outside the squeue)
1318          * is trying to remove this tcp from the time wait list, we will
1319          * block in tcp_time_wait_remove while trying to acquire the
1320          * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
1321          * requires the ipcl_hash_remove to be ordered after the
1322          * tcp_time_wait_remove for the refcnt checks to work correctly.
1323          */
1324         if (tcp->tcp_state == TCPS_TIME_WAIT)
1325                 (void) tcp_time_wait_remove(tcp, NULL);
1326         CL_INET_DISCONNECT(connp);
1327         ipcl_hash_remove(connp);
1328         oldstate = tcp->tcp_state;
1329         tcp->tcp_state = TCPS_CLOSED;
1330         /* Need to probe before ixa_cleanup() is called */
1331         DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
1332             connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
1333             int32_t, oldstate);
1334         ixa_cleanup(connp->conn_ixa);
1335 
1336         /*
1337          * Mark the conn as CONDEMNED
1338          */
1339         mutex_enter(&connp->conn_lock);
1340         connp->conn_state_flags |= CONN_CONDEMNED;
1341         mutex_exit(&connp->conn_lock);
1342 
1343         ASSERT(tcp->tcp_time_wait_next == NULL);
1344         ASSERT(tcp->tcp_time_wait_prev == NULL);
1345         ASSERT(tcp->tcp_time_wait_expire == 0);
1346 
1347         tcp_ipsec_cleanup(tcp);
1348 }
1349 
1350 /*
1351  * tcp is dying (called from ipcl_conn_destroy and error cases).
1352  * Free the tcp_t in either case.
1353  */
1354 void
1355 tcp_free(tcp_t *tcp)
1356 {
1357         mblk_t          *mp;
1358         conn_t          *connp = tcp->tcp_connp;
1359 
1360         ASSERT(tcp != NULL);
1361         ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
1362 
1363         connp->conn_rq = NULL;
1364         connp->conn_wq = NULL;
1365 
1366         tcp_close_mpp(&tcp->tcp_xmit_head);
1367         tcp_close_mpp(&tcp->tcp_reass_head);
1368         if (tcp->tcp_rcv_list != NULL) {
1369                 /* Free b_next chain */
1370                 tcp_close_mpp(&tcp->tcp_rcv_list);
1371         }
1372         if ((mp = tcp->tcp_urp_mp) != NULL) {
1373                 freemsg(mp);
1374         }
1375         if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
1376                 freemsg(mp);
1377         }
1378 
1379         if (tcp->tcp_fused_sigurg_mp != NULL) {
1380                 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1381                 freeb(tcp->tcp_fused_sigurg_mp);
1382                 tcp->tcp_fused_sigurg_mp = NULL;
1383         }
1384 
1385         if (tcp->tcp_ordrel_mp != NULL) {
1386                 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1387                 freeb(tcp->tcp_ordrel_mp);
1388                 tcp->tcp_ordrel_mp = NULL;
1389         }
1390 
1391         TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
1392         bzero(&tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
1393 
1394         if (tcp->tcp_hopopts != NULL) {
1395                 mi_free(tcp->tcp_hopopts);
1396                 tcp->tcp_hopopts = NULL;
1397                 tcp->tcp_hopoptslen = 0;
1398         }
1399         ASSERT(tcp->tcp_hopoptslen == 0);
1400         if (tcp->tcp_dstopts != NULL) {
1401                 mi_free(tcp->tcp_dstopts);
1402                 tcp->tcp_dstopts = NULL;
1403                 tcp->tcp_dstoptslen = 0;
1404         }
1405         ASSERT(tcp->tcp_dstoptslen == 0);
1406         if (tcp->tcp_rthdrdstopts != NULL) {
1407                 mi_free(tcp->tcp_rthdrdstopts);
1408                 tcp->tcp_rthdrdstopts = NULL;
1409                 tcp->tcp_rthdrdstoptslen = 0;
1410         }
1411         ASSERT(tcp->tcp_rthdrdstoptslen == 0);
1412         if (tcp->tcp_rthdr != NULL) {
1413                 mi_free(tcp->tcp_rthdr);
1414                 tcp->tcp_rthdr = NULL;
1415                 tcp->tcp_rthdrlen = 0;
1416         }
1417         ASSERT(tcp->tcp_rthdrlen == 0);
1418 
1419         /*
1420          * Following is really a blowing away a union.
1421          * It happens to have exactly two members of identical size
1422          * the following code is enough.
1423          */
1424         tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
1425 
1426         /*
1427          * If this is a non-STREAM socket still holding on to an upper
1428          * handle, release it. As a result of fallback we might also see
1429          * STREAMS based conns with upper handles, in which case there is
1430          * nothing to do other than clearing the field.
1431          */
1432         if (connp->conn_upper_handle != NULL) {
1433                 if (IPCL_IS_NONSTR(connp)) {
1434                         (*connp->conn_upcalls->su_closed)(
1435                             connp->conn_upper_handle);
1436                         tcp->tcp_detached = B_TRUE;
1437                 }
1438                 connp->conn_upper_handle = NULL;
1439                 connp->conn_upcalls = NULL;
1440         }
1441 }
1442 
1443 /*
1444  * tcp_get_conn/tcp_free_conn
1445  *
1446  * tcp_get_conn is used to get a clean tcp connection structure.
1447  * It tries to reuse the connections put on the freelist by the
1448  * time_wait_collector failing which it goes to kmem_cache. This
1449  * way has two benefits compared to just allocating from and
1450  * freeing to kmem_cache.
1451  * 1) The time_wait_collector can free (which includes the cleanup)
1452  * outside the squeue. So when the interrupt comes, we have a clean
1453  * connection sitting in the freelist. Obviously, this buys us
1454  * performance.
1455  *
1456  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
1457  * has multiple disadvantages - tying up the squeue during alloc.
1458  * But allocating the conn/tcp in IP land is also not the best since
1459  * we can't check the 'q' and 'q0' which are protected by squeue and
1460  * blindly allocate memory which might have to be freed here if we are
1461  * not allowed to accept the connection. By using the freelist and
1462  * putting the conn/tcp back in freelist, we don't pay a penalty for
1463  * allocating memory without checking 'q/q0' and freeing it if we can't
1464  * accept the connection.
1465  *
1466  * Care should be taken to put the conn back in the same squeue's freelist
1467  * from which it was allocated. Best results are obtained if conn is
1468  * allocated from listener's squeue and freed to the same. Time wait
1469  * collector will free up the freelist is the connection ends up sitting
1470  * there for too long.
1471  */
1472 void *
1473 tcp_get_conn(void *arg, tcp_stack_t *tcps)
1474 {
1475         tcp_t                   *tcp = NULL;
1476         conn_t                  *connp = NULL;
1477         squeue_t                *sqp = (squeue_t *)arg;
1478         tcp_squeue_priv_t       *tcp_time_wait;
1479         netstack_t              *ns;
1480         mblk_t                  *tcp_rsrv_mp = NULL;
1481 
1482         tcp_time_wait =
1483             *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1484 
1485         mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1486         tcp = tcp_time_wait->tcp_free_list;
1487         ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
1488         if (tcp != NULL) {
1489                 tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1490                 tcp_time_wait->tcp_free_list_cnt--;
1491                 mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1492                 tcp->tcp_time_wait_next = NULL;
1493                 connp = tcp->tcp_connp;
1494                 connp->conn_flags |= IPCL_REUSED;
1495 
1496                 ASSERT(tcp->tcp_tcps == NULL);
1497                 ASSERT(connp->conn_netstack == NULL);
1498                 ASSERT(tcp->tcp_rsrv_mp != NULL);
1499                 ns = tcps->tcps_netstack;
1500                 netstack_hold(ns);
1501                 connp->conn_netstack = ns;
1502                 connp->conn_ixa->ixa_ipst = ns->netstack_ip;
1503                 tcp->tcp_tcps = tcps;
1504                 ipcl_globalhash_insert(connp);
1505 
1506                 connp->conn_ixa->ixa_notify_cookie = tcp;
1507                 ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
1508                 connp->conn_recv = tcp_input_data;
1509                 ASSERT(connp->conn_recvicmp == tcp_icmp_input);
1510                 ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
1511                 return ((void *)connp);
1512         }
1513         mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1514         /*
1515          * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
1516          * this conn_t/tcp_t is freed at ipcl_conn_destroy().
1517          */
1518         tcp_rsrv_mp = allocb(0, BPRI_HI);
1519         if (tcp_rsrv_mp == NULL)
1520                 return (NULL);
1521 
1522         if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
1523             tcps->tcps_netstack)) == NULL) {
1524                 freeb(tcp_rsrv_mp);
1525                 return (NULL);
1526         }
1527 
1528         tcp = connp->conn_tcp;
1529         tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1530         mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
1531 
1532         tcp->tcp_tcps = tcps;
1533 
1534         connp->conn_recv = tcp_input_data;
1535         connp->conn_recvicmp = tcp_icmp_input;
1536         connp->conn_verifyicmp = tcp_verifyicmp;
1537 
1538         /*
1539          * Register tcp_notify to listen to capability changes detected by IP.
1540          * This upcall is made in the context of the call to conn_ip_output
1541          * thus it is inside the squeue.
1542          */
1543         connp->conn_ixa->ixa_notify = tcp_notify;
1544         connp->conn_ixa->ixa_notify_cookie = tcp;
1545 
1546         return ((void *)connp);
1547 }
1548 
1549 /*
1550  * Handle connect to IPv4 destinations, including connections for AF_INET6
1551  * sockets connecting to IPv4 mapped IPv6 destinations.
1552  * Returns zero if OK, a positive errno, or a negative TLI error.
1553  */
1554 static int
1555 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
1556     uint_t srcid)
1557 {
1558         ipaddr_t        dstaddr = *dstaddrp;
1559         uint16_t        lport;
1560         conn_t          *connp = tcp->tcp_connp;
1561         tcp_stack_t     *tcps = tcp->tcp_tcps;
1562         int             error;
1563 
1564         ASSERT(connp->conn_ipversion == IPV4_VERSION);
1565 
1566         /* Check for attempt to connect to INADDR_ANY */
1567         if (dstaddr == INADDR_ANY)  {
1568                 /*
1569                  * SunOS 4.x and 4.3 BSD allow an application
1570                  * to connect a TCP socket to INADDR_ANY.
1571                  * When they do this, the kernel picks the
1572                  * address of one interface and uses it
1573                  * instead.  The kernel usually ends up
1574                  * picking the address of the loopback
1575                  * interface.  This is an undocumented feature.
1576                  * However, we provide the same thing here
1577                  * in order to have source and binary
1578                  * compatibility with SunOS 4.x.
1579                  * Update the T_CONN_REQ (sin/sin6) since it is used to
1580                  * generate the T_CONN_CON.
1581                  */
1582                 dstaddr = htonl(INADDR_LOOPBACK);
1583                 *dstaddrp = dstaddr;
1584         }
1585 
1586         /* Handle __sin6_src_id if socket not bound to an IP address */
1587         if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
1588                 ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
1589                     IPCL_ZONEID(connp), tcps->tcps_netstack);
1590                 connp->conn_saddr_v6 = connp->conn_laddr_v6;
1591         }
1592 
1593         IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
1594         connp->conn_fport = dstport;
1595 
1596         /*
1597          * At this point the remote destination address and remote port fields
1598          * in the tcp-four-tuple have been filled in the tcp structure. Now we
1599          * have to see which state tcp was in so we can take appropriate action.
1600          */
1601         if (tcp->tcp_state == TCPS_IDLE) {
1602                 /*
1603                  * We support a quick connect capability here, allowing
1604                  * clients to transition directly from IDLE to SYN_SENT
1605                  * tcp_bindi will pick an unused port, insert the connection
1606                  * in the bind hash and transition to BOUND state.
1607                  */
1608                 lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
1609                     tcp, B_TRUE);
1610                 lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
1611                     B_FALSE, B_FALSE);
1612                 if (lport == 0)
1613                         return (-TNOADDR);
1614         }
1615 
1616         /*
1617          * Lookup the route to determine a source address and the uinfo.
1618          * Setup TCP parameters based on the metrics/DCE.
1619          */
1620         error = tcp_set_destination(tcp);
1621         if (error != 0)
1622                 return (error);
1623 
1624         /*
1625          * Don't let an endpoint connect to itself.
1626          */
1627         if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
1628             connp->conn_fport == connp->conn_lport)
1629                 return (-TBADADDR);
1630 
1631         tcp->tcp_state = TCPS_SYN_SENT;
1632 
1633         return (ipcl_conn_insert_v4(connp));
1634 }
1635 
1636 /*
1637  * Handle connect to IPv6 destinations.
1638  * Returns zero if OK, a positive errno, or a negative TLI error.
1639  */
1640 static int
1641 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
1642     uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
1643 {
1644         uint16_t        lport;
1645         conn_t          *connp = tcp->tcp_connp;
1646         tcp_stack_t     *tcps = tcp->tcp_tcps;
1647         int             error;
1648 
1649         ASSERT(connp->conn_family == AF_INET6);
1650 
1651         /*
1652          * If we're here, it means that the destination address is a native
1653          * IPv6 address.  Return an error if conn_ipversion is not IPv6.  A
1654          * reason why it might not be IPv6 is if the socket was bound to an
1655          * IPv4-mapped IPv6 address.
1656          */
1657         if (connp->conn_ipversion != IPV6_VERSION)
1658                 return (-TBADADDR);
1659 
1660         /*
1661          * Interpret a zero destination to mean loopback.
1662          * Update the T_CONN_REQ (sin/sin6) since it is used to
1663          * generate the T_CONN_CON.
1664          */
1665         if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
1666                 *dstaddrp = ipv6_loopback;
1667 
1668         /* Handle __sin6_src_id if socket not bound to an IP address */
1669         if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
1670                 ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
1671                     IPCL_ZONEID(connp), tcps->tcps_netstack);
1672                 connp->conn_saddr_v6 = connp->conn_laddr_v6;
1673         }
1674 
1675         /*
1676          * Take care of the scope_id now.
1677          */
1678         if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
1679                 connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
1680                 connp->conn_ixa->ixa_scopeid = scope_id;
1681         } else {
1682                 connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
1683         }
1684 
1685         connp->conn_flowinfo = flowinfo;
1686         connp->conn_faddr_v6 = *dstaddrp;
1687         connp->conn_fport = dstport;
1688 
1689         /*
1690          * At this point the remote destination address and remote port fields
1691          * in the tcp-four-tuple have been filled in the tcp structure. Now we
1692          * have to see which state tcp was in so we can take appropriate action.
1693          */
1694         if (tcp->tcp_state == TCPS_IDLE) {
1695                 /*
1696                  * We support a quick connect capability here, allowing
1697                  * clients to transition directly from IDLE to SYN_SENT
1698                  * tcp_bindi will pick an unused port, insert the connection
1699                  * in the bind hash and transition to BOUND state.
1700                  */
1701                 lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
1702                     tcp, B_TRUE);
1703                 lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
1704                     B_FALSE, B_FALSE);
1705                 if (lport == 0)
1706                         return (-TNOADDR);
1707         }
1708 
1709         /*
1710          * Lookup the route to determine a source address and the uinfo.
1711          * Setup TCP parameters based on the metrics/DCE.
1712          */
1713         error = tcp_set_destination(tcp);
1714         if (error != 0)
1715                 return (error);
1716 
1717         /*
1718          * Don't let an endpoint connect to itself.
1719          */
1720         if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
1721             connp->conn_fport == connp->conn_lport)
1722                 return (-TBADADDR);
1723 
1724         tcp->tcp_state = TCPS_SYN_SENT;
1725 
1726         return (ipcl_conn_insert_v6(connp));
1727 }
1728 
1729 /*
1730  * Disconnect
1731  * Note that unlike other functions this returns a positive tli error
1732  * when it fails; it never returns an errno.
1733  */
1734 static int
1735 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
1736 {
1737         conn_t          *lconnp;
1738         tcp_stack_t     *tcps = tcp->tcp_tcps;
1739         conn_t          *connp = tcp->tcp_connp;
1740 
1741         /*
1742          * Right now, upper modules pass down a T_DISCON_REQ to TCP,
1743          * when the stream is in BOUND state. Do not send a reset,
1744          * since the destination IP address is not valid, and it can
1745          * be the initialized value of all zeros (broadcast address).
1746          */
1747         if (tcp->tcp_state <= TCPS_BOUND) {
1748                 if (connp->conn_debug) {
1749                         (void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
1750                             "tcp_disconnect: bad state, %d", tcp->tcp_state);
1751                 }
1752                 return (TOUTSTATE);
1753         } else if (tcp->tcp_state >= TCPS_ESTABLISHED) {
1754                 TCPS_CONN_DEC(tcps);
1755         }
1756 
1757         if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
1758 
1759                 /*
1760                  * According to TPI, for non-listeners, ignore seqnum
1761                  * and disconnect.
1762                  * Following interpretation of -1 seqnum is historical
1763                  * and implied TPI ? (TPI only states that for T_CONN_IND,
1764                  * a valid seqnum should not be -1).
1765                  *
1766                  *      -1 means disconnect everything
1767                  *      regardless even on a listener.
1768                  */
1769 
1770                 int old_state = tcp->tcp_state;
1771                 ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
1772 
1773                 /*
1774                  * The connection can't be on the tcp_time_wait_head list
1775                  * since it is not detached.
1776                  */
1777                 ASSERT(tcp->tcp_time_wait_next == NULL);
1778                 ASSERT(tcp->tcp_time_wait_prev == NULL);
1779                 ASSERT(tcp->tcp_time_wait_expire == 0);
1780                 /*
1781                  * If it used to be a listener, check to make sure no one else
1782                  * has taken the port before switching back to LISTEN state.
1783                  */
1784                 if (connp->conn_ipversion == IPV4_VERSION) {
1785                         lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
1786                             connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
1787                 } else {
1788                         uint_t ifindex = 0;
1789 
1790                         if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
1791                                 ifindex = connp->conn_ixa->ixa_scopeid;
1792 
1793                         /* Allow conn_bound_if listeners? */
1794                         lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
1795                             &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
1796                             ipst);
1797                 }
1798                 if (tcp->tcp_conn_req_max && lconnp == NULL) {
1799                         tcp->tcp_state = TCPS_LISTEN;
1800                         DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
1801                             connp->conn_ixa, void, NULL, tcp_t *, tcp, void,
1802                             NULL, int32_t, old_state);
1803                 } else if (old_state > TCPS_BOUND) {
1804                         tcp->tcp_conn_req_max = 0;
1805                         tcp->tcp_state = TCPS_BOUND;
1806                         DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
1807                             connp->conn_ixa, void, NULL, tcp_t *, tcp, void,
1808                             NULL, int32_t, old_state);
1809 
1810                         /*
1811                          * If this end point is not going to become a listener,
1812                          * decrement the listener connection count if
1813                          * necessary.  Note that we do not do this if it is
1814                          * going to be a listner (the above if case) since
1815                          * then it may remove the counter struct.
1816                          */
1817                         if (tcp->tcp_listen_cnt != NULL)
1818                                 TCP_DECR_LISTEN_CNT(tcp);
1819                 }
1820                 if (lconnp != NULL)
1821                         CONN_DEC_REF(lconnp);
1822                 switch (old_state) {
1823                 case TCPS_SYN_SENT:
1824                 case TCPS_SYN_RCVD:
1825                         TCPS_BUMP_MIB(tcps, tcpAttemptFails);
1826                         break;
1827                 case TCPS_ESTABLISHED:
1828                 case TCPS_CLOSE_WAIT:
1829                         TCPS_BUMP_MIB(tcps, tcpEstabResets);
1830                         break;
1831                 }
1832 
1833                 if (tcp->tcp_fused)
1834                         tcp_unfuse(tcp);
1835 
1836                 mutex_enter(&tcp->tcp_eager_lock);
1837                 if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
1838                     (tcp->tcp_conn_req_cnt_q != 0)) {
1839                         tcp_eager_cleanup(tcp, 0);
1840                 }
1841                 mutex_exit(&tcp->tcp_eager_lock);
1842 
1843                 tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
1844                     tcp->tcp_rnxt, TH_RST | TH_ACK);
1845 
1846                 tcp_reinit(tcp);
1847 
1848                 return (0);
1849         } else if (!tcp_eager_blowoff(tcp, seqnum)) {
1850                 return (TBADSEQ);
1851         }
1852         return (0);
1853 }
1854 
1855 /*
1856  * Our client hereby directs us to reject the connection request
1857  * that tcp_input_listener() marked with 'seqnum'.  Rejection consists
1858  * of sending the appropriate RST, not an ICMP error.
1859  */
1860 void
1861 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
1862 {
1863         t_scalar_t seqnum;
1864         int     error;
1865         conn_t  *connp = tcp->tcp_connp;
1866 
1867         ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
1868         if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
1869                 tcp_err_ack(tcp, mp, TPROTO, 0);
1870                 return;
1871         }
1872         seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
1873         error = tcp_disconnect_common(tcp, seqnum);
1874         if (error != 0)
1875                 tcp_err_ack(tcp, mp, error, 0);
1876         else {
1877                 if (tcp->tcp_state >= TCPS_ESTABLISHED) {
1878                         /* Send M_FLUSH according to TPI */
1879                         (void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
1880                 }
1881                 mp = mi_tpi_ok_ack_alloc(mp);
1882                 if (mp != NULL)
1883                         putnext(connp->conn_rq, mp);
1884         }
1885 }
1886 
1887 /*
1888  * Handle reinitialization of a tcp structure.
1889  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
1890  */
1891 static void
1892 tcp_reinit(tcp_t *tcp)
1893 {
1894         mblk_t          *mp;
1895         tcp_stack_t     *tcps = tcp->tcp_tcps;
1896         conn_t          *connp  = tcp->tcp_connp;
1897         int32_t         oldstate;
1898 
1899         /* tcp_reinit should never be called for detached tcp_t's */
1900         ASSERT(tcp->tcp_listener == NULL);
1901         ASSERT((connp->conn_family == AF_INET &&
1902             connp->conn_ipversion == IPV4_VERSION) ||
1903             (connp->conn_family == AF_INET6 &&
1904             (connp->conn_ipversion == IPV4_VERSION ||
1905             connp->conn_ipversion == IPV6_VERSION)));
1906 
1907         /* Cancel outstanding timers */
1908         tcp_timers_stop(tcp);
1909 
1910         /*
1911          * Reset everything in the state vector, after updating global
1912          * MIB data from instance counters.
1913          */
1914         TCPS_UPDATE_MIB(tcps, tcpHCInSegs, tcp->tcp_ibsegs);
1915         tcp->tcp_ibsegs = 0;
1916         TCPS_UPDATE_MIB(tcps, tcpHCOutSegs, tcp->tcp_obsegs);
1917         tcp->tcp_obsegs = 0;
1918 
1919         tcp_close_mpp(&tcp->tcp_xmit_head);
1920         if (tcp->tcp_snd_zcopy_aware)
1921                 tcp_zcopy_notify(tcp);
1922         tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
1923         tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
1924         mutex_enter(&tcp->tcp_non_sq_lock);
1925         if (tcp->tcp_flow_stopped &&
1926             TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
1927                 tcp_clrqfull(tcp);
1928         }
1929         mutex_exit(&tcp->tcp_non_sq_lock);
1930         tcp_close_mpp(&tcp->tcp_reass_head);
1931         tcp->tcp_reass_tail = NULL;
1932         if (tcp->tcp_rcv_list != NULL) {
1933                 /* Free b_next chain */
1934                 tcp_close_mpp(&tcp->tcp_rcv_list);
1935                 tcp->tcp_rcv_last_head = NULL;
1936                 tcp->tcp_rcv_last_tail = NULL;
1937                 tcp->tcp_rcv_cnt = 0;
1938         }
1939         tcp->tcp_rcv_last_tail = NULL;
1940 
1941         if ((mp = tcp->tcp_urp_mp) != NULL) {
1942                 freemsg(mp);
1943                 tcp->tcp_urp_mp = NULL;
1944         }
1945         if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
1946                 freemsg(mp);
1947                 tcp->tcp_urp_mark_mp = NULL;
1948         }
1949         if (tcp->tcp_fused_sigurg_mp != NULL) {
1950                 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1951                 freeb(tcp->tcp_fused_sigurg_mp);
1952                 tcp->tcp_fused_sigurg_mp = NULL;
1953         }
1954         if (tcp->tcp_ordrel_mp != NULL) {
1955                 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1956                 freeb(tcp->tcp_ordrel_mp);
1957                 tcp->tcp_ordrel_mp = NULL;
1958         }
1959 
1960         /*
1961          * Following is a union with two members which are
1962          * identical types and size so the following cleanup
1963          * is enough.
1964          */
1965         tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
1966 
1967         CL_INET_DISCONNECT(connp);
1968 
1969         /*
1970          * The connection can't be on the tcp_time_wait_head list
1971          * since it is not detached.
1972          */
1973         ASSERT(tcp->tcp_time_wait_next == NULL);
1974         ASSERT(tcp->tcp_time_wait_prev == NULL);
1975         ASSERT(tcp->tcp_time_wait_expire == 0);
1976 
1977         /*
1978          * Reset/preserve other values
1979          */
1980         tcp_reinit_values(tcp);
1981         ipcl_hash_remove(connp);
1982         /* Note that ixa_cred gets cleared in ixa_cleanup */
1983         ixa_cleanup(connp->conn_ixa);
1984         tcp_ipsec_cleanup(tcp);
1985 
1986         connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
1987         connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
1988         oldstate = tcp->tcp_state;
1989 
1990         if (tcp->tcp_conn_req_max != 0) {
1991                 /*
1992                  * This is the case when a TLI program uses the same
1993                  * transport end point to accept a connection.  This
1994                  * makes the TCP both a listener and acceptor.  When
1995                  * this connection is closed, we need to set the state
1996                  * back to TCPS_LISTEN.  Make sure that the eager list
1997                  * is reinitialized.
1998                  *
1999                  * Note that this stream is still bound to the four
2000                  * tuples of the previous connection in IP.  If a new
2001                  * SYN with different foreign address comes in, IP will
2002                  * not find it and will send it to the global queue.  In
2003                  * the global queue, TCP will do a tcp_lookup_listener()
2004                  * to find this stream.  This works because this stream
2005                  * is only removed from connected hash.
2006                  *
2007                  */
2008                 tcp->tcp_state = TCPS_LISTEN;
2009                 tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
2010                 tcp->tcp_eager_next_drop_q0 = tcp;
2011                 tcp->tcp_eager_prev_drop_q0 = tcp;
2012                 /*
2013                  * Initially set conn_recv to tcp_input_listener_unbound to try
2014                  * to pick a good squeue for the listener when the first SYN
2015                  * arrives. tcp_input_listener_unbound sets it to
2016                  * tcp_input_listener on that first SYN.
2017                  */
2018                 connp->conn_recv = tcp_input_listener_unbound;
2019 
2020                 connp->conn_proto = IPPROTO_TCP;
2021                 connp->conn_faddr_v6 = ipv6_all_zeros;
2022                 connp->conn_fport = 0;
2023 
2024                 (void) ipcl_bind_insert(connp);
2025         } else {
2026                 tcp->tcp_state = TCPS_BOUND;
2027         }
2028 
2029         /*
2030          * Initialize to default values
2031          */
2032         tcp_init_values(tcp, NULL);
2033 
2034         DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
2035             connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
2036             int32_t, oldstate);
2037 
2038         ASSERT(tcp->tcp_ptpbhn != NULL);
2039         tcp->tcp_rwnd = connp->conn_rcvbuf;
2040         tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
2041             tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
2042 }
2043 
2044 /*
2045  * Force values to zero that need be zero.
2046  * Do not touch values asociated with the BOUND or LISTEN state
2047  * since the connection will end up in that state after the reinit.
2048  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
2049  * structure!
2050  */
2051 static void
2052 tcp_reinit_values(tcp)
2053         tcp_t *tcp;
2054 {
2055         tcp_stack_t     *tcps = tcp->tcp_tcps;
2056         conn_t          *connp = tcp->tcp_connp;
2057 
2058 #ifndef lint
2059 #define DONTCARE(x)
2060 #define PRESERVE(x)
2061 #else
2062 #define DONTCARE(x)     ((x) = (x))
2063 #define PRESERVE(x)     ((x) = (x))
2064 #endif  /* lint */
2065 
2066         PRESERVE(tcp->tcp_bind_hash_port);
2067         PRESERVE(tcp->tcp_bind_hash);
2068         PRESERVE(tcp->tcp_ptpbhn);
2069         PRESERVE(tcp->tcp_acceptor_hash);
2070         PRESERVE(tcp->tcp_ptpahn);
2071 
2072         /* Should be ASSERT NULL on these with new code! */
2073         ASSERT(tcp->tcp_time_wait_next == NULL);
2074         ASSERT(tcp->tcp_time_wait_prev == NULL);
2075         ASSERT(tcp->tcp_time_wait_expire == 0);
2076         PRESERVE(tcp->tcp_state);
2077         PRESERVE(connp->conn_rq);
2078         PRESERVE(connp->conn_wq);
2079 
2080         ASSERT(tcp->tcp_xmit_head == NULL);
2081         ASSERT(tcp->tcp_xmit_last == NULL);
2082         ASSERT(tcp->tcp_unsent == 0);
2083         ASSERT(tcp->tcp_xmit_tail == NULL);
2084         ASSERT(tcp->tcp_xmit_tail_unsent == 0);
2085 
2086         tcp->tcp_snxt = 0;                   /* Displayed in mib */
2087         tcp->tcp_suna = 0;                   /* Displayed in mib */
2088         tcp->tcp_swnd = 0;
2089         DONTCARE(tcp->tcp_cwnd);     /* Init in tcp_process_options */
2090 
2091         ASSERT(tcp->tcp_ibsegs == 0);
2092         ASSERT(tcp->tcp_obsegs == 0);
2093 
2094         if (connp->conn_ht_iphc != NULL) {
2095                 kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
2096                 connp->conn_ht_iphc = NULL;
2097                 connp->conn_ht_iphc_allocated = 0;
2098                 connp->conn_ht_iphc_len = 0;
2099                 connp->conn_ht_ulp = NULL;
2100                 connp->conn_ht_ulp_len = 0;
2101                 tcp->tcp_ipha = NULL;
2102                 tcp->tcp_ip6h = NULL;
2103                 tcp->tcp_tcpha = NULL;
2104         }
2105 
2106         /* We clear any IP_OPTIONS and extension headers */
2107         ip_pkt_free(&connp->conn_xmit_ipp);
2108 
2109         DONTCARE(tcp->tcp_naglim);           /* Init in tcp_init_values */
2110         DONTCARE(tcp->tcp_ipha);
2111         DONTCARE(tcp->tcp_ip6h);
2112         DONTCARE(tcp->tcp_tcpha);
2113         tcp->tcp_valid_bits = 0;
2114 
2115         DONTCARE(tcp->tcp_timer_backoff);    /* Init in tcp_init_values */
2116         DONTCARE(tcp->tcp_last_recv_time);   /* Init in tcp_init_values */
2117         tcp->tcp_last_rcv_lbolt = 0;
2118 
2119         tcp->tcp_init_cwnd = 0;
2120 
2121         tcp->tcp_urp_last_valid = 0;
2122         tcp->tcp_hard_binding = 0;
2123 
2124         tcp->tcp_fin_acked = 0;
2125         tcp->tcp_fin_rcvd = 0;
2126         tcp->tcp_fin_sent = 0;
2127         tcp->tcp_ordrel_done = 0;
2128 
2129         tcp->tcp_detached = 0;
2130 
2131         tcp->tcp_snd_ws_ok = B_FALSE;
2132         tcp->tcp_snd_ts_ok = B_FALSE;
2133         tcp->tcp_zero_win_probe = 0;
2134 
2135         tcp->tcp_loopback = 0;
2136         tcp->tcp_localnet = 0;
2137         tcp->tcp_syn_defense = 0;
2138         tcp->tcp_set_timer = 0;
2139 
2140         tcp->tcp_active_open = 0;
2141         tcp->tcp_rexmit = B_FALSE;
2142         tcp->tcp_xmit_zc_clean = B_FALSE;
2143 
2144         tcp->tcp_snd_sack_ok = B_FALSE;
2145         tcp->tcp_hwcksum = B_FALSE;
2146 
2147         DONTCARE(tcp->tcp_maxpsz_multiplier);        /* Init in tcp_init_values */
2148 
2149         tcp->tcp_conn_def_q0 = 0;
2150         tcp->tcp_ip_forward_progress = B_FALSE;
2151         tcp->tcp_ecn_ok = B_FALSE;
2152 
2153         tcp->tcp_cwr = B_FALSE;
2154         tcp->tcp_ecn_echo_on = B_FALSE;
2155         tcp->tcp_is_wnd_shrnk = B_FALSE;
2156 
2157         TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
2158         bzero(&tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
2159 
2160         tcp->tcp_rcv_ws = 0;
2161         tcp->tcp_snd_ws = 0;
2162         tcp->tcp_ts_recent = 0;
2163         tcp->tcp_rnxt = 0;                   /* Displayed in mib */
2164         DONTCARE(tcp->tcp_rwnd);             /* Set in tcp_reinit() */
2165         tcp->tcp_initial_pmtu = 0;
2166 
2167         ASSERT(tcp->tcp_reass_head == NULL);
2168         ASSERT(tcp->tcp_reass_tail == NULL);
2169 
2170         tcp->tcp_cwnd_cnt = 0;
2171 
2172         ASSERT(tcp->tcp_rcv_list == NULL);
2173         ASSERT(tcp->tcp_rcv_last_head == NULL);
2174         ASSERT(tcp->tcp_rcv_last_tail == NULL);
2175         ASSERT(tcp->tcp_rcv_cnt == 0);
2176 
2177         DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
2178         DONTCARE(tcp->tcp_cwnd_max);         /* Init in tcp_init_values */
2179         tcp->tcp_csuna = 0;
2180 
2181         tcp->tcp_rto = 0;                    /* Displayed in MIB */
2182         DONTCARE(tcp->tcp_rtt_sa);           /* Init in tcp_init_values */
2183         DONTCARE(tcp->tcp_rtt_sd);           /* Init in tcp_init_values */
2184         tcp->tcp_rtt_update = 0;
2185 
2186         DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
2187         DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
2188 
2189         tcp->tcp_rack = 0;                   /* Displayed in mib */
2190         tcp->tcp_rack_cnt = 0;
2191         tcp->tcp_rack_cur_max = 0;
2192         tcp->tcp_rack_abs_max = 0;
2193 
2194         tcp->tcp_max_swnd = 0;
2195 
2196         ASSERT(tcp->tcp_listener == NULL);
2197 
2198         DONTCARE(tcp->tcp_irs);                      /* tcp_valid_bits cleared */
2199         DONTCARE(tcp->tcp_iss);                      /* tcp_valid_bits cleared */
2200         DONTCARE(tcp->tcp_fss);                      /* tcp_valid_bits cleared */
2201         DONTCARE(tcp->tcp_urg);                      /* tcp_valid_bits cleared */
2202 
2203         ASSERT(tcp->tcp_conn_req_cnt_q == 0);
2204         ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
2205         PRESERVE(tcp->tcp_conn_req_max);
2206         PRESERVE(tcp->tcp_conn_req_seqnum);
2207 
2208         DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
2209         DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
2210         DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
2211         DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
2212 
2213         DONTCARE(tcp->tcp_urp_last); /* tcp_urp_last_valid is cleared */
2214         ASSERT(tcp->tcp_urp_mp == NULL);
2215         ASSERT(tcp->tcp_urp_mark_mp == NULL);
2216         ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
2217 
2218         ASSERT(tcp->tcp_eager_next_q == NULL);
2219         ASSERT(tcp->tcp_eager_last_q == NULL);
2220         ASSERT((tcp->tcp_eager_next_q0 == NULL &&
2221             tcp->tcp_eager_prev_q0 == NULL) ||
2222             tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
2223         ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
2224 
2225         ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
2226             tcp->tcp_eager_prev_drop_q0 == NULL) ||
2227             tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
2228 
2229         tcp->tcp_client_errno = 0;
2230 
2231         DONTCARE(connp->conn_sum);           /* Init in tcp_init_values */
2232 
2233         connp->conn_faddr_v6 = ipv6_all_zeros;       /* Displayed in MIB */
2234 
2235         PRESERVE(connp->conn_bound_addr_v6);
2236         tcp->tcp_last_sent_len = 0;
2237         tcp->tcp_dupack_cnt = 0;
2238 
2239         connp->conn_fport = 0;                       /* Displayed in MIB */
2240         PRESERVE(connp->conn_lport);
2241 
2242         PRESERVE(tcp->tcp_acceptor_lockp);
2243 
2244         ASSERT(tcp->tcp_ordrel_mp == NULL);
2245         PRESERVE(tcp->tcp_acceptor_id);
2246         DONTCARE(tcp->tcp_ipsec_overhead);
2247 
2248         PRESERVE(connp->conn_family);
2249         /* Remove any remnants of mapped address binding */
2250         if (connp->conn_family == AF_INET6) {
2251                 connp->conn_ipversion = IPV6_VERSION;
2252                 tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
2253         } else {
2254                 connp->conn_ipversion = IPV4_VERSION;
2255                 tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
2256         }
2257 
2258         connp->conn_bound_if = 0;
2259         connp->conn_recv_ancillary.crb_all = 0;
2260         tcp->tcp_recvifindex = 0;
2261         tcp->tcp_recvhops = 0;
2262         tcp->tcp_closed = 0;
2263         if (tcp->tcp_hopopts != NULL) {
2264                 mi_free(tcp->tcp_hopopts);
2265                 tcp->tcp_hopopts = NULL;
2266                 tcp->tcp_hopoptslen = 0;
2267         }
2268         ASSERT(tcp->tcp_hopoptslen == 0);
2269         if (tcp->tcp_dstopts != NULL) {
2270                 mi_free(tcp->tcp_dstopts);
2271                 tcp->tcp_dstopts = NULL;
2272                 tcp->tcp_dstoptslen = 0;
2273         }
2274         ASSERT(tcp->tcp_dstoptslen == 0);
2275         if (tcp->tcp_rthdrdstopts != NULL) {
2276                 mi_free(tcp->tcp_rthdrdstopts);
2277                 tcp->tcp_rthdrdstopts = NULL;
2278                 tcp->tcp_rthdrdstoptslen = 0;
2279         }
2280         ASSERT(tcp->tcp_rthdrdstoptslen == 0);
2281         if (tcp->tcp_rthdr != NULL) {
2282                 mi_free(tcp->tcp_rthdr);
2283                 tcp->tcp_rthdr = NULL;
2284                 tcp->tcp_rthdrlen = 0;
2285         }
2286         ASSERT(tcp->tcp_rthdrlen == 0);
2287 
2288         /* Reset fusion-related fields */
2289         tcp->tcp_fused = B_FALSE;
2290         tcp->tcp_unfusable = B_FALSE;
2291         tcp->tcp_fused_sigurg = B_FALSE;
2292         tcp->tcp_loopback_peer = NULL;
2293 
2294         tcp->tcp_lso = B_FALSE;
2295 
2296         tcp->tcp_in_ack_unsent = 0;
2297         tcp->tcp_cork = B_FALSE;
2298         tcp->tcp_tconnind_started = B_FALSE;
2299 
2300         PRESERVE(tcp->tcp_squeue_bytes);
2301 
2302         tcp->tcp_closemp_used = B_FALSE;
2303 
2304         PRESERVE(tcp->tcp_rsrv_mp);
2305         PRESERVE(tcp->tcp_rsrv_mp_lock);
2306 
2307 #ifdef DEBUG
2308         DONTCARE(tcp->tcmp_stk[0]);
2309 #endif
2310 
2311         PRESERVE(tcp->tcp_connid);
2312 
2313         ASSERT(tcp->tcp_listen_cnt == NULL);
2314         ASSERT(tcp->tcp_reass_tid == 0);
2315 
2316 #undef  DONTCARE
2317 #undef  PRESERVE
2318 }
2319 
2320 /*
2321  * Initialize the various fields in tcp_t.  If parent (the listener) is non
2322  * NULL, certain values will be inheritted from it.
2323  */
2324 void
2325 tcp_init_values(tcp_t *tcp, tcp_t *parent)
2326 {
2327         tcp_stack_t     *tcps = tcp->tcp_tcps;
2328         conn_t          *connp = tcp->tcp_connp;
2329         clock_t         rto;
2330 
2331         ASSERT((connp->conn_family == AF_INET &&
2332             connp->conn_ipversion == IPV4_VERSION) ||
2333             (connp->conn_family == AF_INET6 &&
2334             (connp->conn_ipversion == IPV4_VERSION ||
2335             connp->conn_ipversion == IPV6_VERSION)));
2336 
2337         if (parent == NULL) {
2338                 tcp->tcp_naglim = tcps->tcps_naglim_def;
2339 
2340                 tcp->tcp_rto_initial = tcps->tcps_rexmit_interval_initial;
2341                 tcp->tcp_rto_min = tcps->tcps_rexmit_interval_min;
2342                 tcp->tcp_rto_max = tcps->tcps_rexmit_interval_max;
2343 
2344                 tcp->tcp_first_ctimer_threshold =
2345                     tcps->tcps_ip_notify_cinterval;
2346                 tcp->tcp_second_ctimer_threshold =
2347                     tcps->tcps_ip_abort_cinterval;
2348                 tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
2349                 tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
2350 
2351                 tcp->tcp_fin_wait_2_flush_interval =
2352                     tcps->tcps_fin_wait_2_flush_interval;
2353 
2354                 tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
2355                 tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
2356 
2357                 /*
2358                  * Default value of tcp_init_cwnd is 0, so no need to set here
2359                  * if parent is NULL.  But we need to inherit it from parent.
2360                  */
2361         } else {
2362                 /* Inherit various TCP parameters from the parent. */
2363                 tcp->tcp_naglim = parent->tcp_naglim;
2364 
2365                 tcp->tcp_rto_initial = parent->tcp_rto_initial;
2366                 tcp->tcp_rto_min = parent->tcp_rto_min;
2367                 tcp->tcp_rto_max = parent->tcp_rto_max;
2368 
2369                 tcp->tcp_first_ctimer_threshold =
2370                     parent->tcp_first_ctimer_threshold;
2371                 tcp->tcp_second_ctimer_threshold =
2372                     parent->tcp_second_ctimer_threshold;
2373                 tcp->tcp_first_timer_threshold =
2374                     parent->tcp_first_timer_threshold;
2375                 tcp->tcp_second_timer_threshold =
2376                     parent->tcp_second_timer_threshold;
2377 
2378                 tcp->tcp_fin_wait_2_flush_interval =
2379                     parent->tcp_fin_wait_2_flush_interval;
2380 
2381                 tcp->tcp_ka_interval = parent->tcp_ka_interval;
2382                 tcp->tcp_ka_abort_thres = parent->tcp_ka_abort_thres;
2383 
2384                 tcp->tcp_init_cwnd = parent->tcp_init_cwnd;
2385         }
2386 
2387         /*
2388          * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
2389          * will be close to tcp_rexmit_interval_initial.  By doing this, we
2390          * allow the algorithm to adjust slowly to large fluctuations of RTT
2391          * during first few transmissions of a connection as seen in slow
2392          * links.
2393          */
2394         tcp->tcp_rtt_sa = tcp->tcp_rto_initial << 2;
2395         tcp->tcp_rtt_sd = tcp->tcp_rto_initial >> 1;
2396         rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2397             tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
2398             tcps->tcps_conn_grace_period;
2399         TCP_SET_RTO(tcp, rto);
2400 
2401         tcp->tcp_timer_backoff = 0;
2402         tcp->tcp_ms_we_have_waited = 0;
2403         tcp->tcp_last_recv_time = ddi_get_lbolt();
2404         tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
2405         tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2406         tcp->tcp_snd_burst = TCP_CWND_INFINITE;
2407 
2408         tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
2409 
2410         /* NOTE:  ISS is now set in tcp_set_destination(). */
2411 
2412         /* Reset fusion-related fields */
2413         tcp->tcp_fused = B_FALSE;
2414         tcp->tcp_unfusable = B_FALSE;
2415         tcp->tcp_fused_sigurg = B_FALSE;
2416         tcp->tcp_loopback_peer = NULL;
2417 
2418         /* We rebuild the header template on the next connect/conn_request */
2419 
2420         connp->conn_mlp_type = mlptSingle;
2421 
2422         /*
2423          * Init the window scale to the max so tcp_rwnd_set() won't pare
2424          * down tcp_rwnd. tcp_set_destination() will set the right value later.
2425          */
2426         tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
2427         tcp->tcp_rwnd = connp->conn_rcvbuf;
2428 
2429         tcp->tcp_cork = B_FALSE;
2430         /*
2431          * Init the tcp_debug option if it wasn't already set.  This value
2432          * determines whether TCP
2433          * calls strlog() to print out debug messages.  Doing this
2434          * initialization here means that this value is not inherited thru
2435          * tcp_reinit().
2436          */
2437         if (!connp->conn_debug)
2438                 connp->conn_debug = tcps->tcps_dbg;
2439 }
2440 
2441 /*
2442  * Update the TCP connection according to change of PMTU.
2443  *
2444  * Path MTU might have changed by either increase or decrease, so need to
2445  * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
2446  * or negative MSS, since tcp_mss_set() will do it.
2447  */
2448 void
2449 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
2450 {
2451         uint32_t        pmtu;
2452         int32_t         mss;
2453         conn_t          *connp = tcp->tcp_connp;
2454         ip_xmit_attr_t  *ixa = connp->conn_ixa;
2455         iaflags_t       ixaflags;
2456 
2457         if (tcp->tcp_tcps->tcps_ignore_path_mtu)
2458                 return;
2459 
2460         if (tcp->tcp_state < TCPS_ESTABLISHED)
2461                 return;
2462 
2463         /*
2464          * Always call ip_get_pmtu() to make sure that IP has updated
2465          * ixa_flags properly.
2466          */
2467         pmtu = ip_get_pmtu(ixa);
2468         ixaflags = ixa->ixa_flags;
2469 
2470         /*
2471          * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
2472          * IPsec overhead if applied. Make sure to use the most recent
2473          * IPsec information.
2474          */
2475         mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
2476 
2477         /*
2478          * Nothing to change, so just return.
2479          */
2480         if (mss == tcp->tcp_mss)
2481                 return;
2482 
2483         /*
2484          * Currently, for ICMP errors, only PMTU decrease is handled.
2485          */
2486         if (mss > tcp->tcp_mss && decrease_only)
2487                 return;
2488 
2489         DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
2490 
2491         /*
2492          * Update ixa_fragsize and ixa_pmtu.
2493          */
2494         ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
2495 
2496         /*
2497          * Adjust MSS and all relevant variables.
2498          */
2499         tcp_mss_set(tcp, mss);
2500 
2501         /*
2502          * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
2503          * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
2504          * has a (potentially different) min size we do the same. Make sure to
2505          * clear IXAF_DONTFRAG, which is used by IP to decide whether to
2506          * fragment the packet.
2507          *
2508          * LSO over IPv6 can not be fragmented. So need to disable LSO
2509          * when IPv6 fragmentation is needed.
2510          */
2511         if (mss < tcp->tcp_tcps->tcps_mss_min)
2512                 ixaflags |= IXAF_PMTU_TOO_SMALL;
2513 
2514         if (ixaflags & IXAF_PMTU_TOO_SMALL)
2515                 ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
2516 
2517         if ((connp->conn_ipversion == IPV4_VERSION) &&
2518             !(ixaflags & IXAF_PMTU_IPV4_DF)) {
2519                 tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
2520         }
2521         ixa->ixa_flags = ixaflags;
2522 }
2523 
2524 int
2525 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
2526 {
2527         conn_t  *connp = tcp->tcp_connp;
2528         queue_t *q = connp->conn_rq;
2529         int32_t mss = tcp->tcp_mss;
2530         int     maxpsz;
2531 
2532         if (TCP_IS_DETACHED(tcp))
2533                 return (mss);
2534         if (tcp->tcp_fused) {
2535                 maxpsz = tcp_fuse_maxpsz(tcp);
2536                 mss = INFPSZ;
2537         } else if (tcp->tcp_maxpsz_multiplier == 0) {
2538                 /*
2539                  * Set the sd_qn_maxpsz according to the socket send buffer
2540                  * size, and sd_maxblk to INFPSZ (-1).  This will essentially
2541                  * instruct the stream head to copyin user data into contiguous
2542                  * kernel-allocated buffers without breaking it up into smaller
2543                  * chunks.  We round up the buffer size to the nearest SMSS.
2544                  */
2545                 maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
2546                 mss = INFPSZ;
2547         } else {
2548                 /*
2549                  * Set sd_qn_maxpsz to approx half the (receivers) buffer
2550                  * (and a multiple of the mss).  This instructs the stream
2551                  * head to break down larger than SMSS writes into SMSS-
2552                  * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
2553                  */
2554                 maxpsz = tcp->tcp_maxpsz_multiplier * mss;
2555                 if (maxpsz > connp->conn_sndbuf / 2) {
2556                         maxpsz = connp->conn_sndbuf / 2;
2557                         /* Round up to nearest mss */
2558                         maxpsz = MSS_ROUNDUP(maxpsz, mss);
2559                 }
2560         }
2561 
2562         (void) proto_set_maxpsz(q, connp, maxpsz);
2563         if (!(IPCL_IS_NONSTR(connp)))
2564                 connp->conn_wq->q_maxpsz = maxpsz;
2565         if (set_maxblk)
2566                 (void) proto_set_tx_maxblk(q, connp, mss);
2567         return (mss);
2568 }
2569 
2570 /* For /dev/tcp aka AF_INET open */
2571 static int
2572 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
2573 {
2574         return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
2575 }
2576 
2577 /* For /dev/tcp6 aka AF_INET6 open */
2578 static int
2579 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
2580 {
2581         return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
2582 }
2583 
2584 conn_t *
2585 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
2586     int *errorp)
2587 {
2588         tcp_t           *tcp = NULL;
2589         conn_t          *connp;
2590         zoneid_t        zoneid;
2591         tcp_stack_t     *tcps;
2592         squeue_t        *sqp;
2593 
2594         ASSERT(errorp != NULL);
2595         /*
2596          * Find the proper zoneid and netstack.
2597          */
2598         /*
2599          * Special case for install: miniroot needs to be able to
2600          * access files via NFS as though it were always in the
2601          * global zone.
2602          */
2603         if (credp == kcred && nfs_global_client_only != 0) {
2604                 zoneid = GLOBAL_ZONEID;
2605                 tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
2606                     netstack_tcp;
2607                 ASSERT(tcps != NULL);
2608         } else {
2609                 netstack_t *ns;
2610                 int err;
2611 
2612                 if ((err = secpolicy_basic_net_access(credp)) != 0) {
2613                         *errorp = err;
2614                         return (NULL);
2615                 }
2616 
2617                 ns = netstack_find_by_cred(credp);
2618                 ASSERT(ns != NULL);
2619                 tcps = ns->netstack_tcp;
2620                 ASSERT(tcps != NULL);
2621 
2622                 /*
2623                  * For exclusive stacks we set the zoneid to zero
2624                  * to make TCP operate as if in the global zone.
2625                  */
2626                 if (tcps->tcps_netstack->netstack_stackid !=
2627                     GLOBAL_NETSTACKID)
2628                         zoneid = GLOBAL_ZONEID;
2629                 else
2630                         zoneid = crgetzoneid(credp);
2631         }
2632 
2633         sqp = IP_SQUEUE_GET((uint_t)gethrtime());
2634         connp = (conn_t *)tcp_get_conn(sqp, tcps);
2635         /*
2636          * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
2637          * so we drop it by one.
2638          */
2639         netstack_rele(tcps->tcps_netstack);
2640         if (connp == NULL) {
2641                 *errorp = ENOSR;
2642                 return (NULL);
2643         }
2644         ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
2645 
2646         connp->conn_sqp = sqp;
2647         connp->conn_initial_sqp = connp->conn_sqp;
2648         connp->conn_ixa->ixa_sqp = connp->conn_sqp;
2649         tcp = connp->conn_tcp;
2650 
2651         /*
2652          * Besides asking IP to set the checksum for us, have conn_ip_output
2653          * to do the following checks when necessary:
2654          *
2655          * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
2656          * IXAF_VERIFY_PMTU: verify PMTU changes
2657          * IXAF_VERIFY_LSO: verify LSO capability changes
2658          */
2659         connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
2660             IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
2661 
2662         if (!tcps->tcps_dev_flow_ctl)
2663                 connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
2664 
2665         if (isv6) {
2666                 connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
2667                 connp->conn_ipversion = IPV6_VERSION;
2668                 connp->conn_family = AF_INET6;
2669                 tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
2670                 connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
2671         } else {
2672                 connp->conn_ipversion = IPV4_VERSION;
2673                 connp->conn_family = AF_INET;
2674                 tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
2675                 connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
2676         }
2677         connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
2678 
2679         crhold(credp);
2680         connp->conn_cred = credp;
2681         connp->conn_cpid = curproc->p_pid;
2682         connp->conn_open_time = ddi_get_lbolt64();
2683 
2684         /* Cache things in the ixa without any refhold */
2685         ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
2686         connp->conn_ixa->ixa_cred = credp;
2687         connp->conn_ixa->ixa_cpid = connp->conn_cpid;
2688 
2689         connp->conn_zoneid = zoneid;
2690         /* conn_allzones can not be set this early, hence no IPCL_ZONEID */
2691         connp->conn_ixa->ixa_zoneid = zoneid;
2692         connp->conn_mlp_type = mlptSingle;
2693         ASSERT(connp->conn_netstack == tcps->tcps_netstack);
2694         ASSERT(tcp->tcp_tcps == tcps);
2695 
2696         /*
2697          * If the caller has the process-wide flag set, then default to MAC
2698          * exempt mode.  This allows read-down to unlabeled hosts.
2699          */
2700         if (getpflags(NET_MAC_AWARE, credp) != 0)
2701                 connp->conn_mac_mode = CONN_MAC_AWARE;
2702 
2703         connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
2704 
2705         if (issocket) {
2706                 tcp->tcp_issocket = 1;
2707         }
2708 
2709         connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
2710         connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
2711         connp->conn_sndlowat = tcps->tcps_xmit_lowat;
2712         connp->conn_so_type = SOCK_STREAM;
2713         connp->conn_wroff = connp->conn_ht_iphc_allocated +
2714             tcps->tcps_wroff_xtra;
2715 
2716         SOCK_CONNID_INIT(tcp->tcp_connid);
2717         /* DTrace ignores this - it isn't a tcp:::state-change */
2718         tcp->tcp_state = TCPS_IDLE;
2719         tcp_init_values(tcp, NULL);
2720         return (connp);
2721 }
2722 
2723 static int
2724 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
2725     boolean_t isv6)
2726 {
2727         tcp_t           *tcp = NULL;
2728         conn_t          *connp = NULL;
2729         int             err;
2730         vmem_t          *minor_arena = NULL;
2731         dev_t           conn_dev;
2732         boolean_t       issocket;
2733 
2734         if (q->q_ptr != NULL)
2735                 return (0);
2736 
2737         if (sflag == MODOPEN)
2738                 return (EINVAL);
2739 
2740         if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
2741             ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
2742                 minor_arena = ip_minor_arena_la;
2743         } else {
2744                 /*
2745                  * Either minor numbers in the large arena were exhausted
2746                  * or a non socket application is doing the open.
2747                  * Try to allocate from the small arena.
2748                  */
2749                 if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
2750                         return (EBUSY);
2751                 }
2752                 minor_arena = ip_minor_arena_sa;
2753         }
2754 
2755         ASSERT(minor_arena != NULL);
2756 
2757         *devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
2758 
2759         if (flag & SO_FALLBACK) {
2760                 /*
2761                  * Non streams socket needs a stream to fallback to
2762                  */
2763                 RD(q)->q_ptr = (void *)conn_dev;
2764                 WR(q)->q_qinfo = &tcp_fallback_sock_winit;
2765                 WR(q)->q_ptr = (void *)minor_arena;
2766                 qprocson(q);
2767                 return (0);
2768         } else if (flag & SO_ACCEPTOR) {
2769                 q->q_qinfo = &tcp_acceptor_rinit;
2770                 /*
2771                  * the conn_dev and minor_arena will be subsequently used by
2772                  * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
2773                  * the minor device number for this connection from the q_ptr.
2774                  */
2775                 RD(q)->q_ptr = (void *)conn_dev;
2776                 WR(q)->q_qinfo = &tcp_acceptor_winit;
2777                 WR(q)->q_ptr = (void *)minor_arena;
2778                 qprocson(q);
2779                 return (0);
2780         }
2781 
2782         issocket = flag & SO_SOCKSTR;
2783         connp = tcp_create_common(credp, isv6, issocket, &err);
2784 
2785         if (connp == NULL) {
2786                 inet_minor_free(minor_arena, conn_dev);
2787                 q->q_ptr = WR(q)->q_ptr = NULL;
2788                 return (err);
2789         }
2790 
2791         connp->conn_rq = q;
2792         connp->conn_wq = WR(q);
2793         q->q_ptr = WR(q)->q_ptr = connp;
2794 
2795         connp->conn_dev = conn_dev;
2796         connp->conn_minor_arena = minor_arena;
2797 
2798         ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
2799         ASSERT(WR(q)->q_qinfo == &tcp_winit);
2800 
2801         tcp = connp->conn_tcp;
2802 
2803         if (issocket) {
2804                 WR(q)->q_qinfo = &tcp_sock_winit;
2805         } else {
2806 #ifdef  _ILP32
2807                 tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
2808 #else
2809                 tcp->tcp_acceptor_id = conn_dev;
2810 #endif  /* _ILP32 */
2811                 tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
2812         }
2813 
2814         /*
2815          * Put the ref for TCP. Ref for IP was already put
2816          * by ipcl_conn_create. Also Make the conn_t globally
2817          * visible to walkers
2818          */
2819         mutex_enter(&connp->conn_lock);
2820         CONN_INC_REF_LOCKED(connp);
2821         ASSERT(connp->conn_ref == 2);
2822         connp->conn_state_flags &= ~CONN_INCIPIENT;
2823         mutex_exit(&connp->conn_lock);
2824 
2825         qprocson(q);
2826         return (0);
2827 }
2828 
2829 /*
2830  * Build/update the tcp header template (in conn_ht_iphc) based on
2831  * conn_xmit_ipp. The headers include ip6_t, any extension
2832  * headers, and the maximum size tcp header (to avoid reallocation
2833  * on the fly for additional tcp options).
2834  *
2835  * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
2836  * Returns failure if can't allocate memory.
2837  */
2838 int
2839 tcp_build_hdrs(tcp_t *tcp)
2840 {
2841         tcp_stack_t     *tcps = tcp->tcp_tcps;
2842         conn_t          *connp = tcp->tcp_connp;
2843         char            buf[TCP_MAX_HDR_LENGTH];
2844         uint_t          buflen;
2845         uint_t          ulplen = TCP_MIN_HEADER_LENGTH;
2846         uint_t          extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
2847         tcpha_t         *tcpha;
2848         uint32_t        cksum;
2849         int             error;
2850 
2851         /*
2852          * We might be called after the connection is set up, and we might
2853          * have TS options already in the TCP header. Thus we  save any
2854          * existing tcp header.
2855          */
2856         buflen = connp->conn_ht_ulp_len;
2857         if (buflen != 0) {
2858                 bcopy(connp->conn_ht_ulp, buf, buflen);
2859                 extralen -= buflen - ulplen;
2860                 ulplen = buflen;
2861         }
2862 
2863         /* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
2864         mutex_enter(&connp->conn_lock);
2865         error = conn_build_hdr_template(connp, ulplen, extralen,
2866             &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
2867         mutex_exit(&connp->conn_lock);
2868         if (error != 0)
2869                 return (error);
2870 
2871         /*
2872          * Any routing header/option has been massaged. The checksum difference
2873          * is stored in conn_sum for later use.
2874          */
2875         tcpha = (tcpha_t *)connp->conn_ht_ulp;
2876         tcp->tcp_tcpha = tcpha;
2877 
2878         /* restore any old tcp header */
2879         if (buflen != 0) {
2880                 bcopy(buf, connp->conn_ht_ulp, buflen);
2881         } else {
2882                 tcpha->tha_sum = 0;
2883                 tcpha->tha_urp = 0;
2884                 tcpha->tha_ack = 0;
2885                 tcpha->tha_offset_and_reserved = (5 << 4);
2886                 tcpha->tha_lport = connp->conn_lport;
2887                 tcpha->tha_fport = connp->conn_fport;
2888         }
2889 
2890         /*
2891          * IP wants our header length in the checksum field to
2892          * allow it to perform a single pseudo-header+checksum
2893          * calculation on behalf of TCP.
2894          * Include the adjustment for a source route once IP_OPTIONS is set.
2895          */
2896         cksum = sizeof (tcpha_t) + connp->conn_sum;
2897         cksum = (cksum >> 16) + (cksum & 0xFFFF);
2898         ASSERT(cksum < 0x10000);
2899         tcpha->tha_sum = htons(cksum);
2900 
2901         if (connp->conn_ipversion == IPV4_VERSION)
2902                 tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
2903         else
2904                 tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
2905 
2906         if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
2907             connp->conn_wroff) {
2908                 connp->conn_wroff = connp->conn_ht_iphc_allocated +
2909                     tcps->tcps_wroff_xtra;
2910                 (void) proto_set_tx_wroff(connp->conn_rq, connp,
2911                     connp->conn_wroff);
2912         }
2913         return (0);
2914 }
2915 
2916 /*
2917  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
2918  * We do not allow the receive window to shrink.  After setting rwnd,
2919  * set the flow control hiwat of the stream.
2920  *
2921  * This function is called in 2 cases:
2922  *
2923  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
2924  *    connection (passive open) and in tcp_input_data() for active connect.
2925  *    This is called after tcp_mss_set() when the desired MSS value is known.
2926  *    This makes sure that our window size is a mutiple of the other side's
2927  *    MSS.
2928  * 2) Handling SO_RCVBUF option.
2929  *
2930  * It is ASSUMED that the requested size is a multiple of the current MSS.
2931  *
2932  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
2933  * user requests so.
2934  */
2935 int
2936 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
2937 {
2938         uint32_t        mss = tcp->tcp_mss;
2939         uint32_t        old_max_rwnd;
2940         uint32_t        max_transmittable_rwnd;
2941         boolean_t       tcp_detached = TCP_IS_DETACHED(tcp);
2942         tcp_stack_t     *tcps = tcp->tcp_tcps;
2943         conn_t          *connp = tcp->tcp_connp;
2944 
2945         /*
2946          * Insist on a receive window that is at least
2947          * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
2948          * funny TCP interactions of Nagle algorithm, SWS avoidance
2949          * and delayed acknowledgement.
2950          */
2951         rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
2952 
2953         if (tcp->tcp_fused) {
2954                 size_t sth_hiwat;
2955                 tcp_t *peer_tcp = tcp->tcp_loopback_peer;
2956 
2957                 ASSERT(peer_tcp != NULL);
2958                 sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
2959                 if (!tcp_detached) {
2960                         (void) proto_set_rx_hiwat(connp->conn_rq, connp,
2961                             sth_hiwat);
2962                         tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
2963                 }
2964 
2965                 /* Caller could have changed tcp_rwnd; update tha_win */
2966                 if (tcp->tcp_tcpha != NULL) {
2967                         tcp->tcp_tcpha->tha_win =
2968                             htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
2969                 }
2970                 if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
2971                         tcp->tcp_cwnd_max = rwnd;
2972 
2973                 /*
2974                  * In the fusion case, the maxpsz stream head value of
2975                  * our peer is set according to its send buffer size
2976                  * and our receive buffer size; since the latter may
2977                  * have changed we need to update the peer's maxpsz.
2978                  */
2979                 (void) tcp_maxpsz_set(peer_tcp, B_TRUE);
2980                 return (sth_hiwat);
2981         }
2982 
2983         if (tcp_detached)
2984                 old_max_rwnd = tcp->tcp_rwnd;
2985         else
2986                 old_max_rwnd = connp->conn_rcvbuf;
2987 
2988 
2989         /*
2990          * If window size info has already been exchanged, TCP should not
2991          * shrink the window.  Shrinking window is doable if done carefully.
2992          * We may add that support later.  But so far there is not a real
2993          * need to do that.
2994          */
2995         if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
2996                 /* MSS may have changed, do a round up again. */
2997                 rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
2998         }
2999 
3000         /*
3001          * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
3002          * can be applied even before the window scale option is decided.
3003          */
3004         max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
3005         if (rwnd > max_transmittable_rwnd) {
3006                 rwnd = max_transmittable_rwnd -
3007                     (max_transmittable_rwnd % mss);
3008                 if (rwnd < mss)
3009                         rwnd = max_transmittable_rwnd;
3010                 /*
3011                  * If we're over the limit we may have to back down tcp_rwnd.
3012                  * The increment below won't work for us. So we set all three
3013                  * here and the increment below will have no effect.
3014                  */
3015                 tcp->tcp_rwnd = old_max_rwnd = rwnd;
3016         }
3017         if (tcp->tcp_localnet) {
3018                 tcp->tcp_rack_abs_max =
3019                     MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
3020         } else {
3021                 /*
3022                  * For a remote host on a different subnet (through a router),
3023                  * we ack every other packet to be conforming to RFC1122.
3024                  * tcp_deferred_acks_max is default to 2.
3025                  */
3026                 tcp->tcp_rack_abs_max =
3027                     MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
3028         }
3029         if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
3030                 tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
3031         else
3032                 tcp->tcp_rack_cur_max = 0;
3033         /*
3034          * Increment the current rwnd by the amount the maximum grew (we
3035          * can not overwrite it since we might be in the middle of a
3036          * connection.)
3037          */
3038         tcp->tcp_rwnd += rwnd - old_max_rwnd;
3039         connp->conn_rcvbuf = rwnd;
3040 
3041         /* Are we already connected? */
3042         if (tcp->tcp_tcpha != NULL) {
3043                 tcp->tcp_tcpha->tha_win =
3044                     htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
3045         }
3046 
3047         if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
3048                 tcp->tcp_cwnd_max = rwnd;
3049 
3050         if (tcp_detached)
3051                 return (rwnd);
3052 
3053         tcp_set_recv_threshold(tcp, rwnd >> 3);
3054 
3055         (void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
3056         return (rwnd);
3057 }
3058 
3059 int
3060 tcp_do_unbind(conn_t *connp)
3061 {
3062         tcp_t *tcp = connp->conn_tcp;
3063         int32_t oldstate;
3064 
3065         switch (tcp->tcp_state) {
3066         case TCPS_BOUND:
3067         case TCPS_LISTEN:
3068                 break;
3069         default:
3070                 return (-TOUTSTATE);
3071         }
3072 
3073         /*
3074          * Need to clean up all the eagers since after the unbind, segments
3075          * will no longer be delivered to this listener stream.
3076          */
3077         mutex_enter(&tcp->tcp_eager_lock);
3078         if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3079                 tcp_eager_cleanup(tcp, 0);
3080         }
3081         mutex_exit(&tcp->tcp_eager_lock);
3082 
3083         /* Clean up the listener connection counter if necessary. */
3084         if (tcp->tcp_listen_cnt != NULL)
3085                 TCP_DECR_LISTEN_CNT(tcp);
3086         connp->conn_laddr_v6 = ipv6_all_zeros;
3087         connp->conn_saddr_v6 = ipv6_all_zeros;
3088         tcp_bind_hash_remove(tcp);
3089         oldstate = tcp->tcp_state;
3090         tcp->tcp_state = TCPS_IDLE;
3091         DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
3092             connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
3093             int32_t, oldstate);
3094 
3095         ip_unbind(connp);
3096         bzero(&connp->conn_ports, sizeof (connp->conn_ports));
3097 
3098         return (0);
3099 }
3100 
3101 /*
3102  * Collect protocol properties to send to the upper handle.
3103  */
3104 void
3105 tcp_get_proto_props(tcp_t *tcp, struct sock_proto_props *sopp)
3106 {
3107         conn_t *connp = tcp->tcp_connp;
3108 
3109         sopp->sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
3110         sopp->sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
3111 
3112         sopp->sopp_rxhiwat = tcp->tcp_fused ?
3113             tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
3114             connp->conn_rcvbuf;
3115         /*
3116          * Determine what write offset value to use depending on SACK and
3117          * whether the endpoint is fused or not.
3118          */
3119         if (tcp->tcp_fused) {
3120                 ASSERT(tcp->tcp_loopback);
3121                 ASSERT(tcp->tcp_loopback_peer != NULL);
3122                 /*
3123                  * For fused tcp loopback, set the stream head's write
3124                  * offset value to zero since we won't be needing any room
3125                  * for TCP/IP headers.  This would also improve performance
3126                  * since it would reduce the amount of work done by kmem.
3127                  * Non-fused tcp loopback case is handled separately below.
3128                  */
3129                 sopp->sopp_wroff = 0;
3130                 /*
3131                  * Update the peer's transmit parameters according to
3132                  * our recently calculated high water mark value.
3133                  */
3134                 (void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
3135         } else if (tcp->tcp_snd_sack_ok) {
3136                 sopp->sopp_wroff = connp->conn_ht_iphc_allocated +
3137                     (tcp->tcp_loopback ? 0 : tcp->tcp_tcps->tcps_wroff_xtra);
3138         } else {
3139                 sopp->sopp_wroff = connp->conn_ht_iphc_len +
3140                     (tcp->tcp_loopback ? 0 : tcp->tcp_tcps->tcps_wroff_xtra);
3141         }
3142 
3143         if (tcp->tcp_loopback) {
3144                 sopp->sopp_flags |= SOCKOPT_LOOPBACK;
3145                 sopp->sopp_loopback = B_TRUE;
3146         }
3147 }
3148 
3149 /*
3150  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
3151  */
3152 boolean_t
3153 tcp_zcopy_check(tcp_t *tcp)
3154 {
3155         conn_t          *connp = tcp->tcp_connp;
3156         ip_xmit_attr_t  *ixa = connp->conn_ixa;
3157         boolean_t       zc_enabled = B_FALSE;
3158         tcp_stack_t     *tcps = tcp->tcp_tcps;
3159 
3160         if (do_tcpzcopy == 2)
3161                 zc_enabled = B_TRUE;
3162         else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
3163                 zc_enabled = B_TRUE;
3164 
3165         tcp->tcp_snd_zcopy_on = zc_enabled;
3166         if (!TCP_IS_DETACHED(tcp)) {
3167                 if (zc_enabled) {
3168                         ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
3169                         (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3170                             ZCVMSAFE);
3171                         TCP_STAT(tcps, tcp_zcopy_on);
3172                 } else {
3173                         ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
3174                         (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3175                             ZCVMUNSAFE);
3176                         TCP_STAT(tcps, tcp_zcopy_off);
3177                 }
3178         }
3179         return (zc_enabled);
3180 }
3181 
3182 /*
3183  * Backoff from a zero-copy message by copying data to a new allocated
3184  * message and freeing the original desballoca'ed segmapped message.
3185  *
3186  * This function is called by following two callers:
3187  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
3188  *    the origial desballoca'ed message and notify sockfs. This is in re-
3189  *    transmit state.
3190  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
3191  *    to be copied to new message.
3192  */
3193 mblk_t *
3194 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
3195 {
3196         mblk_t          *nbp;
3197         mblk_t          *head = NULL;
3198         mblk_t          *tail = NULL;
3199         tcp_stack_t     *tcps = tcp->tcp_tcps;
3200 
3201         ASSERT(bp != NULL);
3202         while (bp != NULL) {
3203                 if (IS_VMLOANED_MBLK(bp)) {
3204                         TCP_STAT(tcps, tcp_zcopy_backoff);
3205                         if ((nbp = copyb(bp)) == NULL) {
3206                                 tcp->tcp_xmit_zc_clean = B_FALSE;
3207                                 if (tail != NULL)
3208                                         tail->b_cont = bp;
3209                                 return ((head == NULL) ? bp : head);
3210                         }
3211 
3212                         if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
3213                                 if (fix_xmitlist)
3214                                         tcp_zcopy_notify(tcp);
3215                                 else
3216                                         nbp->b_datap->db_struioflag |=
3217                                             STRUIO_ZCNOTIFY;
3218                         }
3219                         nbp->b_cont = bp->b_cont;
3220 
3221                         /*
3222                          * Copy saved information and adjust tcp_xmit_tail
3223                          * if needed.
3224                          */
3225                         if (fix_xmitlist) {
3226                                 nbp->b_prev = bp->b_prev;
3227                                 nbp->b_next = bp->b_next;
3228 
3229                                 if (tcp->tcp_xmit_tail == bp)
3230                                         tcp->tcp_xmit_tail = nbp;
3231                         }
3232 
3233                         /* Free the original message. */
3234                         bp->b_prev = NULL;
3235                         bp->b_next = NULL;
3236                         freeb(bp);
3237 
3238                         bp = nbp;
3239                 }
3240 
3241                 if (head == NULL) {
3242                         head = bp;
3243                 }
3244                 if (tail == NULL) {
3245                         tail = bp;
3246                 } else {
3247                         tail->b_cont = bp;
3248                         tail = bp;
3249                 }
3250 
3251                 /* Move forward. */
3252                 bp = bp->b_cont;
3253         }
3254 
3255         if (fix_xmitlist) {
3256                 tcp->tcp_xmit_last = tail;
3257                 tcp->tcp_xmit_zc_clean = B_TRUE;
3258         }
3259 
3260         return (head);
3261 }
3262 
3263 void
3264 tcp_zcopy_notify(tcp_t *tcp)
3265 {
3266         struct stdata   *stp;
3267         conn_t          *connp;
3268 
3269         if (tcp->tcp_detached)
3270                 return;
3271         connp = tcp->tcp_connp;
3272         if (IPCL_IS_NONSTR(connp)) {
3273                 (*connp->conn_upcalls->su_zcopy_notify)
3274                     (connp->conn_upper_handle);
3275                 return;
3276         }
3277         stp = STREAM(connp->conn_rq);
3278         mutex_enter(&stp->sd_lock);
3279         stp->sd_flag |= STZCNOTIFY;
3280         cv_broadcast(&stp->sd_zcopy_wait);
3281         mutex_exit(&stp->sd_lock);
3282 }
3283 
3284 /*
3285  * Update the TCP connection according to change of LSO capability.
3286  */
3287 static void
3288 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
3289 {
3290         /*
3291          * We check against IPv4 header length to preserve the old behavior
3292          * of only enabling LSO when there are no IP options.
3293          * But this restriction might not be necessary at all. Before removing
3294          * it, need to verify how LSO is handled for source routing case, with
3295          * which IP does software checksum.
3296          *
3297          * For IPv6, whenever any extension header is needed, LSO is supressed.
3298          */
3299         if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
3300             IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
3301                 return;
3302 
3303         /*
3304          * Either the LSO capability newly became usable, or it has changed.
3305          */
3306         if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
3307                 ill_lso_capab_t *lsoc = &ixa->ixa_lso_capab;
3308 
3309                 ASSERT(lsoc->ill_lso_max > 0);
3310                 tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
3311 
3312                 DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
3313                     boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
3314 
3315                 /*
3316                  * If LSO to be enabled, notify the STREAM header with larger
3317                  * data block.
3318                  */
3319                 if (!tcp->tcp_lso)
3320                         tcp->tcp_maxpsz_multiplier = 0;
3321 
3322                 tcp->tcp_lso = B_TRUE;
3323                 TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
3324         } else { /* LSO capability is not usable any more. */
3325                 DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
3326                     boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
3327 
3328                 /*
3329                  * If LSO to be disabled, notify the STREAM header with smaller
3330                  * data block. And need to restore fragsize to PMTU.
3331                  */
3332                 if (tcp->tcp_lso) {
3333                         tcp->tcp_maxpsz_multiplier =
3334                             tcp->tcp_tcps->tcps_maxpsz_multiplier;
3335                         ixa->ixa_fragsize = ixa->ixa_pmtu;
3336                         tcp->tcp_lso = B_FALSE;
3337                         TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
3338                 }
3339         }
3340 
3341         (void) tcp_maxpsz_set(tcp, B_TRUE);
3342 }
3343 
3344 /*
3345  * Update the TCP connection according to change of ZEROCOPY capability.
3346  */
3347 static void
3348 tcp_update_zcopy(tcp_t *tcp)
3349 {
3350         conn_t          *connp = tcp->tcp_connp;
3351         tcp_stack_t     *tcps = tcp->tcp_tcps;
3352 
3353         if (tcp->tcp_snd_zcopy_on) {
3354                 tcp->tcp_snd_zcopy_on = B_FALSE;
3355                 if (!TCP_IS_DETACHED(tcp)) {
3356                         (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3357                             ZCVMUNSAFE);
3358                         TCP_STAT(tcps, tcp_zcopy_off);
3359                 }
3360         } else {
3361                 tcp->tcp_snd_zcopy_on = B_TRUE;
3362                 if (!TCP_IS_DETACHED(tcp)) {
3363                         (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3364                             ZCVMSAFE);
3365                         TCP_STAT(tcps, tcp_zcopy_on);
3366                 }
3367         }
3368 }
3369 
3370 /*
3371  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
3372  * so it's safe to update the TCP connection.
3373  */
3374 /* ARGSUSED1 */
3375 static void
3376 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
3377     ixa_notify_arg_t narg)
3378 {
3379         tcp_t           *tcp = (tcp_t *)arg;
3380         conn_t          *connp = tcp->tcp_connp;
3381 
3382         switch (ntype) {
3383         case IXAN_LSO:
3384                 tcp_update_lso(tcp, connp->conn_ixa);
3385                 break;
3386         case IXAN_PMTU:
3387                 tcp_update_pmtu(tcp, B_FALSE);
3388                 break;
3389         case IXAN_ZCOPY:
3390                 tcp_update_zcopy(tcp);
3391                 break;
3392         default:
3393                 break;
3394         }
3395 }
3396 
3397 /*
3398  * The TCP write service routine should never be called...
3399  */
3400 /* ARGSUSED */
3401 static void
3402 tcp_wsrv(queue_t *q)
3403 {
3404         tcp_stack_t     *tcps = Q_TO_TCP(q)->tcp_tcps;
3405 
3406         TCP_STAT(tcps, tcp_wsrv_called);
3407 }
3408 
3409 /*
3410  * Hash list lookup routine for tcp_t structures.
3411  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
3412  */
3413 tcp_t *
3414 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
3415 {
3416         tf_t    *tf;
3417         tcp_t   *tcp;
3418 
3419         tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
3420         mutex_enter(&tf->tf_lock);
3421         for (tcp = tf->tf_tcp; tcp != NULL;
3422             tcp = tcp->tcp_acceptor_hash) {
3423                 if (tcp->tcp_acceptor_id == id) {
3424                         CONN_INC_REF(tcp->tcp_connp);
3425                         mutex_exit(&tf->tf_lock);
3426                         return (tcp);
3427                 }
3428         }
3429         mutex_exit(&tf->tf_lock);
3430         return (NULL);
3431 }
3432 
3433 /*
3434  * Hash list insertion routine for tcp_t structures.
3435  */
3436 void
3437 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
3438 {
3439         tf_t    *tf;
3440         tcp_t   **tcpp;
3441         tcp_t   *tcpnext;
3442         tcp_stack_t     *tcps = tcp->tcp_tcps;
3443 
3444         tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
3445 
3446         if (tcp->tcp_ptpahn != NULL)
3447                 tcp_acceptor_hash_remove(tcp);
3448         tcpp = &tf->tf_tcp;
3449         mutex_enter(&tf->tf_lock);
3450         tcpnext = tcpp[0];
3451         if (tcpnext)
3452                 tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
3453         tcp->tcp_acceptor_hash = tcpnext;
3454         tcp->tcp_ptpahn = tcpp;
3455         tcpp[0] = tcp;
3456         tcp->tcp_acceptor_lockp = &tf->tf_lock;       /* For tcp_*_hash_remove */
3457         mutex_exit(&tf->tf_lock);
3458 }
3459 
3460 /*
3461  * Hash list removal routine for tcp_t structures.
3462  */
3463 void
3464 tcp_acceptor_hash_remove(tcp_t *tcp)
3465 {
3466         tcp_t   *tcpnext;
3467         kmutex_t *lockp;
3468 
3469         /*
3470          * Extract the lock pointer in case there are concurrent
3471          * hash_remove's for this instance.
3472          */
3473         lockp = tcp->tcp_acceptor_lockp;
3474 
3475         if (tcp->tcp_ptpahn == NULL)
3476                 return;
3477 
3478         ASSERT(lockp != NULL);
3479         mutex_enter(lockp);
3480         if (tcp->tcp_ptpahn) {
3481                 tcpnext = tcp->tcp_acceptor_hash;
3482                 if (tcpnext) {
3483                         tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
3484                         tcp->tcp_acceptor_hash = NULL;
3485                 }
3486                 *tcp->tcp_ptpahn = tcpnext;
3487                 tcp->tcp_ptpahn = NULL;
3488         }
3489         mutex_exit(lockp);
3490         tcp->tcp_acceptor_lockp = NULL;
3491 }
3492 
3493 /*
3494  * Type three generator adapted from the random() function in 4.4 BSD:
3495  */
3496 
3497 /*
3498  * Copyright (c) 1983, 1993
3499  *      The Regents of the University of California.  All rights reserved.
3500  *
3501  * Redistribution and use in source and binary forms, with or without
3502  * modification, are permitted provided that the following conditions
3503  * are met:
3504  * 1. Redistributions of source code must retain the above copyright
3505  *    notice, this list of conditions and the following disclaimer.
3506  * 2. Redistributions in binary form must reproduce the above copyright
3507  *    notice, this list of conditions and the following disclaimer in the
3508  *    documentation and/or other materials provided with the distribution.
3509  * 3. All advertising materials mentioning features or use of this software
3510  *    must display the following acknowledgement:
3511  *      This product includes software developed by the University of
3512  *      California, Berkeley and its contributors.
3513  * 4. Neither the name of the University nor the names of its contributors
3514  *    may be used to endorse or promote products derived from this software
3515  *    without specific prior written permission.
3516  *
3517  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3518  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3519  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3520  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3521  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3522  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3523  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3524  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3525  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3526  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3527  * SUCH DAMAGE.
3528  */
3529 
3530 /* Type 3 -- x**31 + x**3 + 1 */
3531 #define DEG_3           31
3532 #define SEP_3           3
3533 
3534 
3535 /* Protected by tcp_random_lock */
3536 static int tcp_randtbl[DEG_3 + 1];
3537 
3538 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
3539 static int *tcp_random_rptr = &tcp_randtbl[1];
3540 
3541 static int *tcp_random_state = &tcp_randtbl[1];
3542 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
3543 
3544 kmutex_t tcp_random_lock;
3545 
3546 void
3547 tcp_random_init(void)
3548 {
3549         int i;
3550         hrtime_t hrt;
3551         time_t wallclock;
3552         uint64_t result;
3553 
3554         /*
3555          * Use high-res timer and current time for seed.  Gethrtime() returns
3556          * a longlong, which may contain resolution down to nanoseconds.
3557          * The current time will either be a 32-bit or a 64-bit quantity.
3558          * XOR the two together in a 64-bit result variable.
3559          * Convert the result to a 32-bit value by multiplying the high-order
3560          * 32-bits by the low-order 32-bits.
3561          */
3562 
3563         hrt = gethrtime();
3564         (void) drv_getparm(TIME, &wallclock);
3565         result = (uint64_t)wallclock ^ (uint64_t)hrt;
3566         mutex_enter(&tcp_random_lock);
3567         tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
3568             (result & 0xffffffff);
3569 
3570         for (i = 1; i < DEG_3; i++)
3571                 tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
3572                     + 12345;
3573         tcp_random_fptr = &tcp_random_state[SEP_3];
3574         tcp_random_rptr = &tcp_random_state[0];
3575         mutex_exit(&tcp_random_lock);
3576         for (i = 0; i < 10 * DEG_3; i++)
3577                 (void) tcp_random();
3578 }
3579 
3580 /*
3581  * tcp_random: Return a random number in the range [1 - (128K + 1)].
3582  * This range is selected to be approximately centered on TCP_ISS / 2,
3583  * and easy to compute. We get this value by generating a 32-bit random
3584  * number, selecting out the high-order 17 bits, and then adding one so
3585  * that we never return zero.
3586  */
3587 int
3588 tcp_random(void)
3589 {
3590         int i;
3591 
3592         mutex_enter(&tcp_random_lock);
3593         *tcp_random_fptr += *tcp_random_rptr;
3594 
3595         /*
3596          * The high-order bits are more random than the low-order bits,
3597          * so we select out the high-order 17 bits and add one so that
3598          * we never return zero.
3599          */
3600         i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
3601         if (++tcp_random_fptr >= tcp_random_end_ptr) {
3602                 tcp_random_fptr = tcp_random_state;
3603                 ++tcp_random_rptr;
3604         } else if (++tcp_random_rptr >= tcp_random_end_ptr)
3605                 tcp_random_rptr = tcp_random_state;
3606 
3607         mutex_exit(&tcp_random_lock);
3608         return (i);
3609 }
3610 
3611 /*
3612  * Split this function out so that if the secret changes, I'm okay.
3613  *
3614  * Initialize the tcp_iss_cookie and tcp_iss_key.
3615  */
3616 
3617 #define PASSWD_SIZE 16  /* MUST be multiple of 4 */
3618 
3619 void
3620 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
3621 {
3622         struct {
3623                 int32_t current_time;
3624                 uint32_t randnum;
3625                 uint16_t pad;
3626                 uint8_t ether[6];
3627                 uint8_t passwd[PASSWD_SIZE];
3628         } tcp_iss_cookie;
3629         time_t t;
3630 
3631         /*
3632          * Start with the current absolute time.
3633          */
3634         (void) drv_getparm(TIME, &t);
3635         tcp_iss_cookie.current_time = t;
3636 
3637         /*
3638          * XXX - Need a more random number per RFC 1750, not this crap.
3639          * OTOH, if what follows is pretty random, then I'm in better shape.
3640          */
3641         tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
3642         tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
3643 
3644         /*
3645          * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
3646          * as a good template.
3647          */
3648         bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
3649             min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
3650 
3651         /*
3652          * The pass-phrase.  Normally this is supplied by user-called NDD.
3653          */
3654         bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
3655 
3656         /*
3657          * See 4010593 if this section becomes a problem again,
3658          * but the local ethernet address is useful here.
3659          */
3660         (void) localetheraddr(NULL,
3661             (struct ether_addr *)&tcp_iss_cookie.ether);
3662 
3663         /*
3664          * Hash 'em all together.  The MD5Final is called per-connection.
3665          */
3666         mutex_enter(&tcps->tcps_iss_key_lock);
3667         MD5Init(&tcps->tcps_iss_key);
3668         MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
3669             sizeof (tcp_iss_cookie));
3670         mutex_exit(&tcps->tcps_iss_key_lock);
3671 }
3672 
3673 /*
3674  * Called by IP when IP is loaded into the kernel
3675  */
3676 void
3677 tcp_ddi_g_init(void)
3678 {
3679         tcp_timercache = kmem_cache_create("tcp_timercache",
3680             sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
3681             NULL, NULL, NULL, NULL, NULL, 0);
3682 
3683         tcp_notsack_blk_cache = kmem_cache_create("tcp_notsack_blk_cache",
3684             sizeof (notsack_blk_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
3685 
3686         mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
3687 
3688         /* Initialize the random number generator */
3689         tcp_random_init();
3690 
3691         /* A single callback independently of how many netstacks we have */
3692         ip_squeue_init(tcp_squeue_add);
3693 
3694         tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
3695 
3696         tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
3697 
3698         /*
3699          * We want to be informed each time a stack is created or
3700          * destroyed in the kernel, so we can maintain the
3701          * set of tcp_stack_t's.
3702          */
3703         netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
3704 }
3705 
3706 
3707 #define INET_NAME       "ip"
3708 
3709 /*
3710  * Initialize the TCP stack instance.
3711  */
3712 static void *
3713 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
3714 {
3715         tcp_stack_t     *tcps;
3716         int             i;
3717         int             error = 0;
3718         major_t         major;
3719         size_t          arrsz;
3720 
3721         tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
3722         tcps->tcps_netstack = ns;
3723 
3724         /* Initialize locks */
3725         mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
3726         mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
3727 
3728         tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
3729         tcps->tcps_g_epriv_ports[0] = ULP_DEF_EPRIV_PORT1;
3730         tcps->tcps_g_epriv_ports[1] = ULP_DEF_EPRIV_PORT2;
3731         tcps->tcps_min_anonpriv_port = 512;
3732 
3733         tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
3734             TCP_BIND_FANOUT_SIZE, KM_SLEEP);
3735         tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
3736             TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
3737 
3738         for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
3739                 mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
3740                     MUTEX_DEFAULT, NULL);
3741         }
3742 
3743         for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
3744                 mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
3745                     MUTEX_DEFAULT, NULL);
3746         }
3747 
3748         /* TCP's IPsec code calls the packet dropper. */
3749         ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
3750 
3751         arrsz = tcp_propinfo_count * sizeof (mod_prop_info_t);
3752         tcps->tcps_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz,
3753             KM_SLEEP);
3754         bcopy(tcp_propinfo_tbl, tcps->tcps_propinfo_tbl, arrsz);
3755 
3756         /*
3757          * Note: To really walk the device tree you need the devinfo
3758          * pointer to your device which is only available after probe/attach.
3759          * The following is safe only because it uses ddi_root_node()
3760          */
3761         tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
3762             tcp_opt_obj.odb_opt_arr_cnt);
3763 
3764         /*
3765          * Initialize RFC 1948 secret values.  This will probably be reset once
3766          * by the boot scripts.
3767          *
3768          * Use NULL name, as the name is caught by the new lockstats.
3769          *
3770          * Initialize with some random, non-guessable string, like the global
3771          * T_INFO_ACK.
3772          */
3773 
3774         tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
3775             sizeof (tcp_g_t_info_ack), tcps);
3776 
3777         tcps->tcps_kstat = tcp_kstat2_init(stackid);
3778         tcps->tcps_mibkp = tcp_kstat_init(stackid);
3779 
3780         major = mod_name_to_major(INET_NAME);
3781         error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
3782         ASSERT(error == 0);
3783         tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
3784         ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
3785         cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
3786         mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
3787 
3788         mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
3789         tcps->tcps_reclaim = B_FALSE;
3790         tcps->tcps_reclaim_tid = 0;
3791         tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max;
3792 
3793         /*
3794          * ncpus is the current number of CPUs, which can be bigger than
3795          * boot_ncpus.  But we don't want to use ncpus to allocate all the
3796          * tcp_stats_cpu_t at system boot up time since it will be 1.  While
3797          * we handle adding CPU in tcp_cpu_update(), it will be slow if
3798          * there are many CPUs as we will be adding them 1 by 1.
3799          *
3800          * Note that tcps_sc_cnt never decreases and the tcps_sc[x] pointers
3801          * are not freed until the stack is going away.  So there is no need
3802          * to grab a lock to access the per CPU tcps_sc[x] pointer.
3803          */
3804         mutex_enter(&cpu_lock);
3805         tcps->tcps_sc_cnt = MAX(ncpus, boot_ncpus);
3806         mutex_exit(&cpu_lock);
3807         tcps->tcps_sc = kmem_zalloc(max_ncpus  * sizeof (tcp_stats_cpu_t *),
3808             KM_SLEEP);
3809         for (i = 0; i < tcps->tcps_sc_cnt; i++) {
3810                 tcps->tcps_sc[i] = kmem_zalloc(sizeof (tcp_stats_cpu_t),
3811                     KM_SLEEP);
3812         }
3813 
3814         mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
3815         list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
3816             offsetof(tcp_listener_t, tl_link));
3817 
3818         return (tcps);
3819 }
3820 
3821 /*
3822  * Called when the IP module is about to be unloaded.
3823  */
3824 void
3825 tcp_ddi_g_destroy(void)
3826 {
3827         tcp_g_kstat_fini(tcp_g_kstat);
3828         tcp_g_kstat = NULL;
3829         bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
3830 
3831         mutex_destroy(&tcp_random_lock);
3832 
3833         kmem_cache_destroy(tcp_timercache);
3834         kmem_cache_destroy(tcp_notsack_blk_cache);
3835 
3836         netstack_unregister(NS_TCP);
3837 }
3838 
3839 /*
3840  * Free the TCP stack instance.
3841  */
3842 static void
3843 tcp_stack_fini(netstackid_t stackid, void *arg)
3844 {
3845         tcp_stack_t *tcps = (tcp_stack_t *)arg;
3846         int i;
3847 
3848         freeb(tcps->tcps_ixa_cleanup_mp);
3849         tcps->tcps_ixa_cleanup_mp = NULL;
3850         cv_destroy(&tcps->tcps_ixa_cleanup_cv);
3851         mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
3852 
3853         /*
3854          * Set tcps_reclaim to false tells tcp_reclaim_timer() not to restart
3855          * the timer.
3856          */
3857         mutex_enter(&tcps->tcps_reclaim_lock);
3858         tcps->tcps_reclaim = B_FALSE;
3859         mutex_exit(&tcps->tcps_reclaim_lock);
3860         if (tcps->tcps_reclaim_tid != 0)
3861                 (void) untimeout(tcps->tcps_reclaim_tid);
3862         mutex_destroy(&tcps->tcps_reclaim_lock);
3863 
3864         tcp_listener_conf_cleanup(tcps);
3865 
3866         for (i = 0; i < tcps->tcps_sc_cnt; i++)
3867                 kmem_free(tcps->tcps_sc[i], sizeof (tcp_stats_cpu_t));
3868         kmem_free(tcps->tcps_sc, max_ncpus * sizeof (tcp_stats_cpu_t *));
3869 
3870         kmem_free(tcps->tcps_propinfo_tbl,
3871             tcp_propinfo_count * sizeof (mod_prop_info_t));
3872         tcps->tcps_propinfo_tbl = NULL;
3873 
3874         for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
3875                 ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
3876                 mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
3877         }
3878 
3879         for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
3880                 ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
3881                 mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
3882         }
3883 
3884         kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
3885         tcps->tcps_bind_fanout = NULL;
3886 
3887         kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
3888             TCP_ACCEPTOR_FANOUT_SIZE);
3889         tcps->tcps_acceptor_fanout = NULL;
3890 
3891         mutex_destroy(&tcps->tcps_iss_key_lock);
3892         mutex_destroy(&tcps->tcps_epriv_port_lock);
3893 
3894         ip_drop_unregister(&tcps->tcps_dropper);
3895 
3896         tcp_kstat2_fini(stackid, tcps->tcps_kstat);
3897         tcps->tcps_kstat = NULL;
3898 
3899         tcp_kstat_fini(stackid, tcps->tcps_mibkp);
3900         tcps->tcps_mibkp = NULL;
3901 
3902         ldi_ident_release(tcps->tcps_ldi_ident);
3903         kmem_free(tcps, sizeof (*tcps));
3904 }
3905 
3906 /*
3907  * Generate ISS, taking into account NDD changes may happen halfway through.
3908  * (If the iss is not zero, set it.)
3909  */
3910 
3911 static void
3912 tcp_iss_init(tcp_t *tcp)
3913 {
3914         MD5_CTX context;
3915         struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
3916         uint32_t answer[4];
3917         tcp_stack_t     *tcps = tcp->tcp_tcps;
3918         conn_t          *connp = tcp->tcp_connp;
3919 
3920         tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
3921         tcp->tcp_iss = tcps->tcps_iss_incr_extra;
3922         switch (tcps->tcps_strong_iss) {
3923         case 2:
3924                 mutex_enter(&tcps->tcps_iss_key_lock);
3925                 context = tcps->tcps_iss_key;
3926                 mutex_exit(&tcps->tcps_iss_key_lock);
3927                 arg.ports = connp->conn_ports;
3928                 arg.src = connp->conn_laddr_v6;
3929                 arg.dst = connp->conn_faddr_v6;
3930                 MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
3931                 MD5Final((uchar_t *)answer, &context);
3932                 tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
3933                 /*
3934                  * Now that we've hashed into a unique per-connection sequence
3935                  * space, add a random increment per strong_iss == 1.  So I
3936                  * guess we'll have to...
3937                  */
3938                 /* FALLTHRU */
3939         case 1:
3940                 tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
3941                 break;
3942         default:
3943                 tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
3944                 break;
3945         }
3946         tcp->tcp_valid_bits = TCP_ISS_VALID;
3947         tcp->tcp_fss = tcp->tcp_iss - 1;
3948         tcp->tcp_suna = tcp->tcp_iss;
3949         tcp->tcp_snxt = tcp->tcp_iss + 1;
3950         tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
3951         tcp->tcp_csuna = tcp->tcp_snxt;
3952 }
3953 
3954 /*
3955  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
3956  * on the specified backing STREAMS q. Note, the caller may make the
3957  * decision to call based on the tcp_t.tcp_flow_stopped value which
3958  * when check outside the q's lock is only an advisory check ...
3959  */
3960 void
3961 tcp_setqfull(tcp_t *tcp)
3962 {
3963         tcp_stack_t     *tcps = tcp->tcp_tcps;
3964         conn_t  *connp = tcp->tcp_connp;
3965 
3966         if (tcp->tcp_closed)
3967                 return;
3968 
3969         conn_setqfull(connp, &tcp->tcp_flow_stopped);
3970         if (tcp->tcp_flow_stopped)
3971                 TCP_STAT(tcps, tcp_flwctl_on);
3972 }
3973 
3974 void
3975 tcp_clrqfull(tcp_t *tcp)
3976 {
3977         conn_t  *connp = tcp->tcp_connp;
3978 
3979         if (tcp->tcp_closed)
3980                 return;
3981         conn_clrqfull(connp, &tcp->tcp_flow_stopped);
3982 }
3983 
3984 static int
3985 tcp_squeue_switch(int val)
3986 {
3987         int rval = SQ_FILL;
3988 
3989         switch (val) {
3990         case 1:
3991                 rval = SQ_NODRAIN;
3992                 break;
3993         case 2:
3994                 rval = SQ_PROCESS;
3995                 break;
3996         default:
3997                 break;
3998         }
3999         return (rval);
4000 }
4001 
4002 /*
4003  * This is called once for each squeue - globally for all stack
4004  * instances.
4005  */
4006 static void
4007 tcp_squeue_add(squeue_t *sqp)
4008 {
4009         tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
4010             sizeof (tcp_squeue_priv_t), KM_SLEEP);
4011 
4012         *squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
4013         if (tcp_free_list_max_cnt == 0) {
4014                 int tcp_ncpus = ((boot_max_ncpus == -1) ?
4015                     max_ncpus : boot_max_ncpus);
4016 
4017                 /*
4018                  * Limit number of entries to 1% of availble memory / tcp_ncpus
4019                  */
4020                 tcp_free_list_max_cnt = (freemem * PAGESIZE) /
4021                     (tcp_ncpus * sizeof (tcp_t) * 100);
4022         }
4023         tcp_time_wait->tcp_free_list_cnt = 0;
4024 }
4025 /*
4026  * Return unix error is tli error is TSYSERR, otherwise return a negative
4027  * tli error.
4028  */
4029 int
4030 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
4031     boolean_t bind_to_req_port_only)
4032 {
4033         int error;
4034         tcp_t *tcp = connp->conn_tcp;
4035 
4036         if (tcp->tcp_state >= TCPS_BOUND) {
4037                 if (connp->conn_debug) {
4038                         (void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
4039                             "tcp_bind: bad state, %d", tcp->tcp_state);
4040                 }
4041                 return (-TOUTSTATE);
4042         }
4043 
4044         error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
4045         if (error != 0)
4046                 return (error);
4047 
4048         ASSERT(tcp->tcp_state == TCPS_BOUND);
4049         tcp->tcp_conn_req_max = 0;
4050         return (0);
4051 }
4052 
4053 /*
4054  * If the return value from this function is positive, it's a UNIX error.
4055  * Otherwise, if it's negative, then the absolute value is a TLI error.
4056  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
4057  */
4058 int
4059 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
4060     cred_t *cr, pid_t pid)
4061 {
4062         tcp_t           *tcp = connp->conn_tcp;
4063         sin_t           *sin = (sin_t *)sa;
4064         sin6_t          *sin6 = (sin6_t *)sa;
4065         ipaddr_t        *dstaddrp;
4066         in_port_t       dstport;
4067         uint_t          srcid;
4068         int             error;
4069         uint32_t        mss;
4070         mblk_t          *syn_mp;
4071         tcp_stack_t     *tcps = tcp->tcp_tcps;
4072         int32_t         oldstate;
4073         ip_xmit_attr_t  *ixa = connp->conn_ixa;
4074 
4075         oldstate = tcp->tcp_state;
4076 
4077         switch (len) {
4078         default:
4079                 /*
4080                  * Should never happen
4081                  */
4082                 return (EINVAL);
4083 
4084         case sizeof (sin_t):
4085                 sin = (sin_t *)sa;
4086                 if (sin->sin_port == 0) {
4087                         return (-TBADADDR);
4088                 }
4089                 if (connp->conn_ipv6_v6only) {
4090                         return (EAFNOSUPPORT);
4091                 }
4092                 break;
4093 
4094         case sizeof (sin6_t):
4095                 sin6 = (sin6_t *)sa;
4096                 if (sin6->sin6_port == 0) {
4097                         return (-TBADADDR);
4098                 }
4099                 break;
4100         }
4101         /*
4102          * If we're connecting to an IPv4-mapped IPv6 address, we need to
4103          * make sure that the conn_ipversion is IPV4_VERSION.  We
4104          * need to this before we call tcp_bindi() so that the port lookup
4105          * code will look for ports in the correct port space (IPv4 and
4106          * IPv6 have separate port spaces).
4107          */
4108         if (connp->conn_family == AF_INET6 &&
4109             connp->conn_ipversion == IPV6_VERSION &&
4110             IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
4111                 if (connp->conn_ipv6_v6only)
4112                         return (EADDRNOTAVAIL);
4113 
4114                 connp->conn_ipversion = IPV4_VERSION;
4115         }
4116 
4117         switch (tcp->tcp_state) {
4118         case TCPS_LISTEN:
4119                 /*
4120                  * Listening sockets are not allowed to issue connect().
4121                  */
4122                 if (IPCL_IS_NONSTR(connp))
4123                         return (EOPNOTSUPP);
4124                 /* FALLTHRU */
4125         case TCPS_IDLE:
4126                 /*
4127                  * We support quick connect, refer to comments in
4128                  * tcp_connect_*()
4129                  */
4130                 /* FALLTHRU */
4131         case TCPS_BOUND:
4132                 break;
4133         default:
4134                 return (-TOUTSTATE);
4135         }
4136 
4137         /*
4138          * We update our cred/cpid based on the caller of connect
4139          */
4140         if (connp->conn_cred != cr) {
4141                 crhold(cr);
4142                 crfree(connp->conn_cred);
4143                 connp->conn_cred = cr;
4144         }
4145         connp->conn_cpid = pid;
4146 
4147         /* Cache things in the ixa without any refhold */
4148         ASSERT(!(ixa->ixa_free_flags & IXA_FREE_CRED));
4149         ixa->ixa_cred = cr;
4150         ixa->ixa_cpid = pid;
4151         if (is_system_labeled()) {
4152                 /* We need to restart with a label based on the cred */
4153                 ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
4154         }
4155 
4156         if (connp->conn_family == AF_INET6) {
4157                 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
4158                         error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
4159                             sin6->sin6_port, sin6->sin6_flowinfo,
4160                             sin6->__sin6_src_id, sin6->sin6_scope_id);
4161                 } else {
4162                         /*
4163                          * Destination adress is mapped IPv6 address.
4164                          * Source bound address should be unspecified or
4165                          * IPv6 mapped address as well.
4166                          */
4167                         if (!IN6_IS_ADDR_UNSPECIFIED(
4168                             &connp->conn_bound_addr_v6) &&
4169                             !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
4170                                 return (EADDRNOTAVAIL);
4171                         }
4172                         dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
4173                         dstport = sin6->sin6_port;
4174                         srcid = sin6->__sin6_src_id;
4175                         error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
4176                             srcid);
4177                 }
4178         } else {
4179                 dstaddrp = &sin->sin_addr.s_addr;
4180                 dstport = sin->sin_port;
4181                 srcid = 0;
4182                 error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
4183         }
4184 
4185         if (error != 0)
4186                 goto connect_failed;
4187 
4188         CL_INET_CONNECT(connp, B_TRUE, error);
4189         if (error != 0)
4190                 goto connect_failed;
4191 
4192         /* connect succeeded */
4193         TCPS_BUMP_MIB(tcps, tcpActiveOpens);
4194         tcp->tcp_active_open = 1;
4195 
4196         /*
4197          * tcp_set_destination() does not adjust for TCP/IP header length.
4198          */
4199         mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
4200 
4201         /*
4202          * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
4203          * to the nearest MSS.
4204          *
4205          * We do the round up here because we need to get the interface MTU
4206          * first before we can do the round up.
4207          */
4208         tcp->tcp_rwnd = connp->conn_rcvbuf;
4209         tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
4210             tcps->tcps_recv_hiwat_minmss * mss);
4211         connp->conn_rcvbuf = tcp->tcp_rwnd;
4212         tcp_set_ws_value(tcp);
4213         tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
4214         if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
4215                 tcp->tcp_snd_ws_ok = B_TRUE;
4216 
4217         /*
4218          * Set tcp_snd_ts_ok to true
4219          * so that tcp_xmit_mp will
4220          * include the timestamp
4221          * option in the SYN segment.
4222          */
4223         if (tcps->tcps_tstamp_always ||
4224             (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
4225                 tcp->tcp_snd_ts_ok = B_TRUE;
4226         }
4227 
4228         /*
4229          * Note that tcp_snd_sack_ok can be set in tcp_set_destination() if
4230          * the SACK metric is set.  So here we just check the per stack SACK
4231          * permitted param.
4232          */
4233         if (tcps->tcps_sack_permitted == 2) {
4234                 ASSERT(tcp->tcp_num_sack_blk == 0);
4235                 ASSERT(tcp->tcp_notsack_list == NULL);
4236                 tcp->tcp_snd_sack_ok = B_TRUE;
4237         }
4238 
4239         /*
4240          * Should we use ECN?  Note that the current
4241          * default value (SunOS 5.9) of tcp_ecn_permitted
4242          * is 1.  The reason for doing this is that there
4243          * are equipments out there that will drop ECN
4244          * enabled IP packets.  Setting it to 1 avoids
4245          * compatibility problems.
4246          */
4247         if (tcps->tcps_ecn_permitted == 2)
4248                 tcp->tcp_ecn_ok = B_TRUE;
4249 
4250         /* Trace change from BOUND -> SYN_SENT here */
4251         DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
4252             connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
4253             int32_t, TCPS_BOUND);
4254 
4255         TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
4256         syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
4257             tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
4258         if (syn_mp != NULL) {
4259                 /*
4260                  * We must bump the generation before sending the syn
4261                  * to ensure that we use the right generation in case
4262                  * this thread issues a "connected" up call.
4263                  */
4264                 SOCK_CONNID_BUMP(tcp->tcp_connid);
4265                 /*
4266                  * DTrace sending the first SYN as a
4267                  * tcp:::connect-request event.
4268                  */
4269                 DTRACE_TCP5(connect__request, mblk_t *, NULL,
4270                     ip_xmit_attr_t *, connp->conn_ixa,
4271                     void_ip_t *, syn_mp->b_rptr, tcp_t *, tcp,
4272                     tcph_t *,
4273                     &syn_mp->b_rptr[connp->conn_ixa->ixa_ip_hdr_length]);
4274                 tcp_send_data(tcp, syn_mp);
4275         }
4276 
4277         if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4278                 tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4279         return (0);
4280 
4281 connect_failed:
4282         connp->conn_faddr_v6 = ipv6_all_zeros;
4283         connp->conn_fport = 0;
4284         tcp->tcp_state = oldstate;
4285         if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4286                 tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4287         return (error);
4288 }
4289 
4290 int
4291 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
4292     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
4293 {
4294         tcp_t           *tcp = connp->conn_tcp;
4295         int             error = 0;
4296         tcp_stack_t     *tcps = tcp->tcp_tcps;
4297         int32_t         oldstate;
4298 
4299         /* All Solaris components should pass a cred for this operation. */
4300         ASSERT(cr != NULL);
4301 
4302         if (tcp->tcp_state >= TCPS_BOUND) {
4303                 if ((tcp->tcp_state == TCPS_BOUND ||
4304                     tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
4305                         /*
4306                          * Handle listen() increasing backlog.
4307                          * This is more "liberal" then what the TPI spec
4308                          * requires but is needed to avoid a t_unbind
4309                          * when handling listen() since the port number
4310                          * might be "stolen" between the unbind and bind.
4311                          */
4312                         goto do_listen;
4313                 }
4314                 if (connp->conn_debug) {
4315                         (void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
4316                             "tcp_listen: bad state, %d", tcp->tcp_state);
4317                 }
4318                 return (-TOUTSTATE);
4319         } else {
4320                 if (sa == NULL) {
4321                         sin6_t  addr;
4322                         sin_t *sin;
4323                         sin6_t *sin6;
4324 
4325                         ASSERT(IPCL_IS_NONSTR(connp));
4326                         /* Do an implicit bind: Request for a generic port. */
4327                         if (connp->conn_family == AF_INET) {
4328                                 len = sizeof (sin_t);
4329                                 sin = (sin_t *)&addr;
4330                                 *sin = sin_null;
4331                                 sin->sin_family = AF_INET;
4332                         } else {
4333                                 ASSERT(connp->conn_family == AF_INET6);
4334                                 len = sizeof (sin6_t);
4335                                 sin6 = (sin6_t *)&addr;
4336                                 *sin6 = sin6_null;
4337                                 sin6->sin6_family = AF_INET6;
4338                         }
4339                         sa = (struct sockaddr *)&addr;
4340                 }
4341 
4342                 error = tcp_bind_check(connp, sa, len, cr,
4343                     bind_to_req_port_only);
4344                 if (error)
4345                         return (error);
4346                 /* Fall through and do the fanout insertion */
4347         }
4348 
4349 do_listen:
4350         ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
4351         tcp->tcp_conn_req_max = backlog;
4352         if (tcp->tcp_conn_req_max) {
4353                 if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
4354                         tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
4355                 if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
4356                         tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
4357                 /*
4358                  * If this is a listener, do not reset the eager list
4359                  * and other stuffs.  Note that we don't check if the
4360                  * existing eager list meets the new tcp_conn_req_max
4361                  * requirement.
4362                  */
4363                 if (tcp->tcp_state != TCPS_LISTEN) {
4364                         tcp->tcp_state = TCPS_LISTEN;
4365                         DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
4366                             connp->conn_ixa, void, NULL, tcp_t *, tcp,
4367                             void, NULL, int32_t, TCPS_BOUND);
4368                         /* Initialize the chain. Don't need the eager_lock */
4369                         tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
4370                         tcp->tcp_eager_next_drop_q0 = tcp;
4371                         tcp->tcp_eager_prev_drop_q0 = tcp;
4372                         tcp->tcp_second_ctimer_threshold =
4373                             tcps->tcps_ip_abort_linterval;
4374                 }
4375         }
4376 
4377         /*
4378          * We need to make sure that the conn_recv is set to a non-null
4379          * value before we insert the conn into the classifier table.
4380          * This is to avoid a race with an incoming packet which does an
4381          * ipcl_classify().
4382          * We initially set it to tcp_input_listener_unbound to try to
4383          * pick a good squeue for the listener when the first SYN arrives.
4384          * tcp_input_listener_unbound sets it to tcp_input_listener on that
4385          * first SYN.
4386          */
4387         connp->conn_recv = tcp_input_listener_unbound;
4388 
4389         /* Insert the listener in the classifier table */
4390         error = ip_laddr_fanout_insert(connp);
4391         if (error != 0) {
4392                 /* Undo the bind - release the port number */
4393                 oldstate = tcp->tcp_state;
4394                 tcp->tcp_state = TCPS_IDLE;
4395                 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
4396                     connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
4397                     int32_t, oldstate);
4398                 connp->conn_bound_addr_v6 = ipv6_all_zeros;
4399 
4400                 connp->conn_laddr_v6 = ipv6_all_zeros;
4401                 connp->conn_saddr_v6 = ipv6_all_zeros;
4402                 connp->conn_ports = 0;
4403 
4404                 if (connp->conn_anon_port) {
4405                         zone_t          *zone;
4406 
4407                         zone = crgetzone(cr);
4408                         connp->conn_anon_port = B_FALSE;
4409                         (void) tsol_mlp_anon(zone, connp->conn_mlp_type,
4410                             connp->conn_proto, connp->conn_lport, B_FALSE);
4411                 }
4412                 connp->conn_mlp_type = mlptSingle;
4413 
4414                 tcp_bind_hash_remove(tcp);
4415                 return (error);
4416         } else {
4417                 /*
4418                  * If there is a connection limit, allocate and initialize
4419                  * the counter struct.  Note that since listen can be called
4420                  * multiple times, the struct may have been allready allocated.
4421                  */
4422                 if (!list_is_empty(&tcps->tcps_listener_conf) &&
4423                     tcp->tcp_listen_cnt == NULL) {
4424                         tcp_listen_cnt_t *tlc;
4425                         uint32_t ratio;
4426 
4427                         ratio = tcp_find_listener_conf(tcps,
4428                             ntohs(connp->conn_lport));
4429                         if (ratio != 0) {
4430                                 uint32_t mem_ratio, tot_buf;
4431 
4432                                 tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
4433                                     KM_SLEEP);
4434                                 /*
4435                                  * Calculate the connection limit based on
4436                                  * the configured ratio and maxusers.  Maxusers
4437                                  * are calculated based on memory size,
4438                                  * ~ 1 user per MB.  Note that the conn_rcvbuf
4439                                  * and conn_sndbuf may change after a
4440                                  * connection is accepted.  So what we have
4441                                  * is only an approximation.
4442                                  */
4443                                 if ((tot_buf = connp->conn_rcvbuf +
4444                                     connp->conn_sndbuf) < MB) {
4445                                         mem_ratio = MB / tot_buf;
4446                                         tlc->tlc_max = maxusers / ratio *
4447                                             mem_ratio;
4448                                 } else {
4449                                         mem_ratio = tot_buf / MB;
4450                                         tlc->tlc_max = maxusers / ratio /
4451                                             mem_ratio;
4452                                 }
4453                                 /* At least we should allow two connections! */
4454                                 if (tlc->tlc_max <= tcp_min_conn_listener)
4455                                         tlc->tlc_max = tcp_min_conn_listener;
4456                                 tlc->tlc_cnt = 1;
4457                                 tlc->tlc_drop = 0;
4458                                 tcp->tcp_listen_cnt = tlc;
4459                         }
4460                 }
4461         }
4462         return (error);
4463 }