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