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