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