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