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