xref: /titanic_44/usr/src/uts/common/inet/tcp/tcp_input.c (revision accf27a5824ae84dfac7b089c4325917231a7d15)
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) 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 /* This file contains all TCP input processing functions. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/suntpi.h>
37 #include <sys/xti_inet.h>
38 #include <sys/squeue_impl.h>
39 #include <sys/squeue.h>
40 #include <sys/tsol/tnet.h>
41 
42 #include <inet/common.h>
43 #include <inet/ip.h>
44 #include <inet/tcp.h>
45 #include <inet/tcp_impl.h>
46 #include <inet/tcp_cluster.h>
47 #include <inet/proto_set.h>
48 #include <inet/ipsec_impl.h>
49 
50 /*
51  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
52  */
53 
54 #ifdef _BIG_ENDIAN
55 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
56 	(TCPOPT_TSTAMP << 8) | 10)
57 #else
58 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
59 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
60 #endif
61 
62 /*
63  * Flags returned from tcp_parse_options.
64  */
65 #define	TCP_OPT_MSS_PRESENT	1
66 #define	TCP_OPT_WSCALE_PRESENT	2
67 #define	TCP_OPT_TSTAMP_PRESENT	4
68 #define	TCP_OPT_SACK_OK_PRESENT	8
69 #define	TCP_OPT_SACK_PRESENT	16
70 
71 /*
72  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
73  */
74 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
75 
76 /*
77  * Since tcp_listener is not cleared atomically with tcp_detached
78  * being cleared we need this extra bit to tell a detached connection
79  * apart from one that is in the process of being accepted.
80  */
81 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
82 	(TCP_IS_DETACHED(tcp) &&	\
83 	    (!(tcp)->tcp_hard_binding))
84 
85 /*
86  * Steps to do when a tcp_t moves to TIME-WAIT state.
87  *
88  * This connection is done, we don't need to account for it.  Decrement
89  * the listener connection counter if needed.
90  *
91  * Decrement the connection counter of the stack.  Note that this counter
92  * is per CPU.  So the total number of connections in a stack is the sum of all
93  * of them.  Since there is no lock for handling all of them exclusively, the
94  * resulting sum is only an approximation.
95  *
96  * Unconditionally clear the exclusive binding bit so this TIME-WAIT
97  * connection won't interfere with new ones.
98  *
99  * Start the TIME-WAIT timer.  If upper layer has not closed the connection,
100  * the timer is handled within the context of this tcp_t.  When the timer
101  * fires, tcp_clean_death() is called.  If upper layer closes the connection
102  * during this period, tcp_time_wait_append() will be called to add this
103  * tcp_t to the global TIME-WAIT list.  Note that this means that the
104  * actual wait time in TIME-WAIT state will be longer than the
105  * tcps_time_wait_interval since the period before upper layer closes the
106  * connection is not accounted for when tcp_time_wait_append() is called.
107  *
108  * If uppser layer has closed the connection, call tcp_time_wait_append()
109  * directly.
110  *
111  */
112 #define	SET_TIME_WAIT(tcps, tcp, connp)				\
113 {								\
114 	(tcp)->tcp_state = TCPS_TIME_WAIT;			\
115 	if ((tcp)->tcp_listen_cnt != NULL)			\
116 		TCP_DECR_LISTEN_CNT(tcp);			\
117 	atomic_dec_64(						\
118 	    (uint64_t *)&(tcps)->tcps_sc[CPU->cpu_seqid]->tcp_sc_conn_cnt); \
119 	(connp)->conn_exclbind = 0;				\
120 	if (!TCP_IS_DETACHED(tcp)) {				\
121 		TCP_TIMER_RESTART(tcp, (tcps)->tcps_time_wait_interval); \
122 	} else {						\
123 		tcp_time_wait_append(tcp);			\
124 		TCP_DBGSTAT(tcps, tcp_rput_time_wait);		\
125 	}							\
126 }
127 
128 /*
129  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
130  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
131  * data, TCP will not respond with an ACK.  RFC 793 requires that
132  * TCP responds with an ACK for such a bogus ACK.  By not following
133  * the RFC, we prevent TCP from getting into an ACK storm if somehow
134  * an attacker successfully spoofs an acceptable segment to our
135  * peer; or when our peer is "confused."
136  */
137 static uint32_t tcp_drop_ack_unsent_cnt = 10;
138 
139 /*
140  * The shift factor applied to tcp_mss to decide if the peer sends us a
141  * valid initial receive window.  By default, if the peer receive window
142  * is smaller than 1 MSS (shift factor is 0), it is considered as invalid.
143  */
144 static uint32_t tcp_init_wnd_shft = 0;
145 
146 /* Process ICMP source quench message or not. */
147 static boolean_t tcp_icmp_source_quench = B_FALSE;
148 
149 static boolean_t tcp_outbound_squeue_switch = B_FALSE;
150 
151 static mblk_t	*tcp_conn_create_v4(conn_t *, conn_t *, mblk_t *,
152 		    ip_recv_attr_t *);
153 static mblk_t	*tcp_conn_create_v6(conn_t *, conn_t *, mblk_t *,
154 		    ip_recv_attr_t *);
155 static boolean_t	tcp_drop_q0(tcp_t *);
156 static void	tcp_icmp_error_ipv6(tcp_t *, mblk_t *, ip_recv_attr_t *);
157 static mblk_t	*tcp_input_add_ancillary(tcp_t *, mblk_t *, ip_pkt_t *,
158 		    ip_recv_attr_t *);
159 static void	tcp_input_listener(void *, mblk_t *, void *, ip_recv_attr_t *);
160 static int	tcp_parse_options(tcpha_t *, tcp_opt_t *);
161 static void	tcp_process_options(tcp_t *, tcpha_t *);
162 static mblk_t	*tcp_reass(tcp_t *, mblk_t *, uint32_t);
163 static void	tcp_reass_elim_overlap(tcp_t *, mblk_t *);
164 static void	tcp_rsrv_input(void *, mblk_t *, void *, ip_recv_attr_t *);
165 static void	tcp_set_rto(tcp_t *, time_t);
166 static void	tcp_setcred_data(mblk_t *, ip_recv_attr_t *);
167 
168 extern void	tcp_kssl_input(tcp_t *, mblk_t *, cred_t *);
169 
170 /*
171  * Set the MSS associated with a particular tcp based on its current value,
172  * and a new one passed in. Observe minimums and maximums, and reset other
173  * state variables that we want to view as multiples of MSS.
174  *
175  * The value of MSS could be either increased or descreased.
176  */
177 void
178 tcp_mss_set(tcp_t *tcp, uint32_t mss)
179 {
180 	uint32_t	mss_max;
181 	tcp_stack_t	*tcps = tcp->tcp_tcps;
182 	conn_t		*connp = tcp->tcp_connp;
183 
184 	if (connp->conn_ipversion == IPV4_VERSION)
185 		mss_max = tcps->tcps_mss_max_ipv4;
186 	else
187 		mss_max = tcps->tcps_mss_max_ipv6;
188 
189 	if (mss < tcps->tcps_mss_min)
190 		mss = tcps->tcps_mss_min;
191 	if (mss > mss_max)
192 		mss = mss_max;
193 	/*
194 	 * Unless naglim has been set by our client to
195 	 * a non-mss value, force naglim to track mss.
196 	 * This can help to aggregate small writes.
197 	 */
198 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
199 		tcp->tcp_naglim = mss;
200 	/*
201 	 * TCP should be able to buffer at least 4 MSS data for obvious
202 	 * performance reason.
203 	 */
204 	if ((mss << 2) > connp->conn_sndbuf)
205 		connp->conn_sndbuf = mss << 2;
206 
207 	/*
208 	 * Set the send lowater to at least twice of MSS.
209 	 */
210 	if ((mss << 1) > connp->conn_sndlowat)
211 		connp->conn_sndlowat = mss << 1;
212 
213 	/*
214 	 * Update tcp_cwnd according to the new value of MSS. Keep the
215 	 * previous ratio to preserve the transmit rate.
216 	 */
217 	tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
218 	tcp->tcp_cwnd_cnt = 0;
219 
220 	tcp->tcp_mss = mss;
221 	(void) tcp_maxpsz_set(tcp, B_TRUE);
222 }
223 
224 /*
225  * Extract option values from a tcp header.  We put any found values into the
226  * tcpopt struct and return a bitmask saying which options were found.
227  */
228 static int
229 tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt)
230 {
231 	uchar_t		*endp;
232 	int		len;
233 	uint32_t	mss;
234 	uchar_t		*up = (uchar_t *)tcpha;
235 	int		found = 0;
236 	int32_t		sack_len;
237 	tcp_seq		sack_begin, sack_end;
238 	tcp_t		*tcp;
239 
240 	endp = up + TCP_HDR_LENGTH(tcpha);
241 	up += TCP_MIN_HEADER_LENGTH;
242 	while (up < endp) {
243 		len = endp - up;
244 		switch (*up) {
245 		case TCPOPT_EOL:
246 			break;
247 
248 		case TCPOPT_NOP:
249 			up++;
250 			continue;
251 
252 		case TCPOPT_MAXSEG:
253 			if (len < TCPOPT_MAXSEG_LEN ||
254 			    up[1] != TCPOPT_MAXSEG_LEN)
255 				break;
256 
257 			mss = BE16_TO_U16(up+2);
258 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
259 			tcpopt->tcp_opt_mss = mss;
260 			found |= TCP_OPT_MSS_PRESENT;
261 
262 			up += TCPOPT_MAXSEG_LEN;
263 			continue;
264 
265 		case TCPOPT_WSCALE:
266 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
267 				break;
268 
269 			if (up[2] > TCP_MAX_WINSHIFT)
270 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
271 			else
272 				tcpopt->tcp_opt_wscale = up[2];
273 			found |= TCP_OPT_WSCALE_PRESENT;
274 
275 			up += TCPOPT_WS_LEN;
276 			continue;
277 
278 		case TCPOPT_SACK_PERMITTED:
279 			if (len < TCPOPT_SACK_OK_LEN ||
280 			    up[1] != TCPOPT_SACK_OK_LEN)
281 				break;
282 			found |= TCP_OPT_SACK_OK_PRESENT;
283 			up += TCPOPT_SACK_OK_LEN;
284 			continue;
285 
286 		case TCPOPT_SACK:
287 			if (len <= 2 || up[1] <= 2 || len < up[1])
288 				break;
289 
290 			/* If TCP is not interested in SACK blks... */
291 			if ((tcp = tcpopt->tcp) == NULL) {
292 				up += up[1];
293 				continue;
294 			}
295 			sack_len = up[1] - TCPOPT_HEADER_LEN;
296 			up += TCPOPT_HEADER_LEN;
297 
298 			/*
299 			 * If the list is empty, allocate one and assume
300 			 * nothing is sack'ed.
301 			 */
302 			if (tcp->tcp_notsack_list == NULL) {
303 				tcp_notsack_update(&(tcp->tcp_notsack_list),
304 				    tcp->tcp_suna, tcp->tcp_snxt,
305 				    &(tcp->tcp_num_notsack_blk),
306 				    &(tcp->tcp_cnt_notsack_list));
307 
308 				/*
309 				 * Make sure tcp_notsack_list is not NULL.
310 				 * This happens when kmem_alloc(KM_NOSLEEP)
311 				 * returns NULL.
312 				 */
313 				if (tcp->tcp_notsack_list == NULL) {
314 					up += sack_len;
315 					continue;
316 				}
317 				tcp->tcp_fack = tcp->tcp_suna;
318 			}
319 
320 			while (sack_len > 0) {
321 				if (up + 8 > endp) {
322 					up = endp;
323 					break;
324 				}
325 				sack_begin = BE32_TO_U32(up);
326 				up += 4;
327 				sack_end = BE32_TO_U32(up);
328 				up += 4;
329 				sack_len -= 8;
330 				/*
331 				 * Bounds checking.  Make sure the SACK
332 				 * info is within tcp_suna and tcp_snxt.
333 				 * If this SACK blk is out of bound, ignore
334 				 * it but continue to parse the following
335 				 * blks.
336 				 */
337 				if (SEQ_LEQ(sack_end, sack_begin) ||
338 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
339 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
340 					continue;
341 				}
342 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
343 				    sack_begin, sack_end,
344 				    &(tcp->tcp_num_notsack_blk),
345 				    &(tcp->tcp_cnt_notsack_list));
346 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
347 					tcp->tcp_fack = sack_end;
348 				}
349 			}
350 			found |= TCP_OPT_SACK_PRESENT;
351 			continue;
352 
353 		case TCPOPT_TSTAMP:
354 			if (len < TCPOPT_TSTAMP_LEN ||
355 			    up[1] != TCPOPT_TSTAMP_LEN)
356 				break;
357 
358 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
359 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
360 
361 			found |= TCP_OPT_TSTAMP_PRESENT;
362 
363 			up += TCPOPT_TSTAMP_LEN;
364 			continue;
365 
366 		default:
367 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
368 				break;
369 			up += up[1];
370 			continue;
371 		}
372 		break;
373 	}
374 	return (found);
375 }
376 
377 /*
378  * Process all TCP option in SYN segment.  Note that this function should
379  * be called after tcp_set_destination() is called so that the necessary info
380  * from IRE is already set in the tcp structure.
381  *
382  * This function sets up the correct tcp_mss value according to the
383  * MSS option value and our header size.  It also sets up the window scale
384  * and timestamp values, and initialize SACK info blocks.  But it does not
385  * change receive window size after setting the tcp_mss value.  The caller
386  * should do the appropriate change.
387  */
388 static void
389 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
390 {
391 	int options;
392 	tcp_opt_t tcpopt;
393 	uint32_t mss_max;
394 	char *tmp_tcph;
395 	tcp_stack_t	*tcps = tcp->tcp_tcps;
396 	conn_t		*connp = tcp->tcp_connp;
397 
398 	tcpopt.tcp = NULL;
399 	options = tcp_parse_options(tcpha, &tcpopt);
400 
401 	/*
402 	 * Process MSS option.  Note that MSS option value does not account
403 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
404 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
405 	 * IPv6.
406 	 */
407 	if (!(options & TCP_OPT_MSS_PRESENT)) {
408 		if (connp->conn_ipversion == IPV4_VERSION)
409 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
410 		else
411 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
412 	} else {
413 		if (connp->conn_ipversion == IPV4_VERSION)
414 			mss_max = tcps->tcps_mss_max_ipv4;
415 		else
416 			mss_max = tcps->tcps_mss_max_ipv6;
417 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
418 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
419 		else if (tcpopt.tcp_opt_mss > mss_max)
420 			tcpopt.tcp_opt_mss = mss_max;
421 	}
422 
423 	/* Process Window Scale option. */
424 	if (options & TCP_OPT_WSCALE_PRESENT) {
425 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
426 		tcp->tcp_snd_ws_ok = B_TRUE;
427 	} else {
428 		tcp->tcp_snd_ws = B_FALSE;
429 		tcp->tcp_snd_ws_ok = B_FALSE;
430 		tcp->tcp_rcv_ws = B_FALSE;
431 	}
432 
433 	/* Process Timestamp option. */
434 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
435 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
436 		tmp_tcph = (char *)tcp->tcp_tcpha;
437 
438 		tcp->tcp_snd_ts_ok = B_TRUE;
439 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
440 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
441 		ASSERT(OK_32PTR(tmp_tcph));
442 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
443 
444 		/* Fill in our template header with basic timestamp option. */
445 		tmp_tcph += connp->conn_ht_ulp_len;
446 		tmp_tcph[0] = TCPOPT_NOP;
447 		tmp_tcph[1] = TCPOPT_NOP;
448 		tmp_tcph[2] = TCPOPT_TSTAMP;
449 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
450 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
451 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
452 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
453 	} else {
454 		tcp->tcp_snd_ts_ok = B_FALSE;
455 	}
456 
457 	/*
458 	 * Process SACK options.  If SACK is enabled for this connection,
459 	 * then allocate the SACK info structure.  Note the following ways
460 	 * when tcp_snd_sack_ok is set to true.
461 	 *
462 	 * For active connection: in tcp_set_destination() called in
463 	 * tcp_connect().
464 	 *
465 	 * For passive connection: in tcp_set_destination() called in
466 	 * tcp_input_listener().
467 	 *
468 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
469 	 * That check makes sure that if we did not send a SACK OK option,
470 	 * we will not enable SACK for this connection even though the other
471 	 * side sends us SACK OK option.  For active connection, the SACK
472 	 * info structure has already been allocated.  So we need to free
473 	 * it if SACK is disabled.
474 	 */
475 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
476 	    (tcp->tcp_snd_sack_ok ||
477 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
478 		ASSERT(tcp->tcp_num_sack_blk == 0);
479 		ASSERT(tcp->tcp_notsack_list == NULL);
480 
481 		tcp->tcp_snd_sack_ok = B_TRUE;
482 		if (tcp->tcp_snd_ts_ok) {
483 			tcp->tcp_max_sack_blk = 3;
484 		} else {
485 			tcp->tcp_max_sack_blk = 4;
486 		}
487 	} else if (tcp->tcp_snd_sack_ok) {
488 		/*
489 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
490 		 * no SACK info will be used for this
491 		 * connection.  This assumes that SACK usage
492 		 * permission is negotiated.  This may need
493 		 * to be changed once this is clarified.
494 		 */
495 		ASSERT(tcp->tcp_num_sack_blk == 0);
496 		ASSERT(tcp->tcp_notsack_list == NULL);
497 		tcp->tcp_snd_sack_ok = B_FALSE;
498 	}
499 
500 	/*
501 	 * Now we know the exact TCP/IP header length, subtract
502 	 * that from tcp_mss to get our side's MSS.
503 	 */
504 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
505 
506 	/*
507 	 * Here we assume that the other side's header size will be equal to
508 	 * our header size.  We calculate the real MSS accordingly.  Need to
509 	 * take into additional stuffs IPsec puts in.
510 	 *
511 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
512 	 */
513 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
514 	    tcp->tcp_ipsec_overhead -
515 	    ((connp->conn_ipversion == IPV4_VERSION ?
516 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
517 
518 	/*
519 	 * Set MSS to the smaller one of both ends of the connection.
520 	 * We should not have called tcp_mss_set() before, but our
521 	 * side of the MSS should have been set to a proper value
522 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
523 	 * STREAM head parameters properly.
524 	 *
525 	 * If we have a larger-than-16-bit window but the other side
526 	 * didn't want to do window scale, tcp_rwnd_set() will take
527 	 * care of that.
528 	 */
529 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
530 
531 	/*
532 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
533 	 * updated properly.
534 	 */
535 	TCP_SET_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
536 }
537 
538 /*
539  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
540  * is filled, return as much as we can.  The message passed in may be
541  * multi-part, chained using b_cont.  "start" is the starting sequence
542  * number for this piece.
543  */
544 static mblk_t *
545 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
546 {
547 	uint32_t	end;
548 	mblk_t		*mp1;
549 	mblk_t		*mp2;
550 	mblk_t		*next_mp;
551 	uint32_t	u1;
552 	tcp_stack_t	*tcps = tcp->tcp_tcps;
553 
554 
555 	/* Walk through all the new pieces. */
556 	do {
557 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
558 		    (uintptr_t)INT_MAX);
559 		end = start + (int)(mp->b_wptr - mp->b_rptr);
560 		next_mp = mp->b_cont;
561 		if (start == end) {
562 			/* Empty.  Blast it. */
563 			freeb(mp);
564 			continue;
565 		}
566 		mp->b_cont = NULL;
567 		TCP_REASS_SET_SEQ(mp, start);
568 		TCP_REASS_SET_END(mp, end);
569 		mp1 = tcp->tcp_reass_tail;
570 		if (!mp1) {
571 			tcp->tcp_reass_tail = mp;
572 			tcp->tcp_reass_head = mp;
573 			TCPS_BUMP_MIB(tcps, tcpInDataUnorderSegs);
574 			TCPS_UPDATE_MIB(tcps, tcpInDataUnorderBytes,
575 			    end - start);
576 			continue;
577 		}
578 		/* New stuff completely beyond tail? */
579 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
580 			/* Link it on end. */
581 			mp1->b_cont = mp;
582 			tcp->tcp_reass_tail = mp;
583 			TCPS_BUMP_MIB(tcps, tcpInDataUnorderSegs);
584 			TCPS_UPDATE_MIB(tcps, tcpInDataUnorderBytes,
585 			    end - start);
586 			continue;
587 		}
588 		mp1 = tcp->tcp_reass_head;
589 		u1 = TCP_REASS_SEQ(mp1);
590 		/* New stuff at the front? */
591 		if (SEQ_LT(start, u1)) {
592 			/* Yes... Check for overlap. */
593 			mp->b_cont = mp1;
594 			tcp->tcp_reass_head = mp;
595 			tcp_reass_elim_overlap(tcp, mp);
596 			continue;
597 		}
598 		/*
599 		 * The new piece fits somewhere between the head and tail.
600 		 * We find our slot, where mp1 precedes us and mp2 trails.
601 		 */
602 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
603 			u1 = TCP_REASS_SEQ(mp2);
604 			if (SEQ_LEQ(start, u1))
605 				break;
606 		}
607 		/* Link ourselves in */
608 		mp->b_cont = mp2;
609 		mp1->b_cont = mp;
610 
611 		/* Trim overlap with following mblk(s) first */
612 		tcp_reass_elim_overlap(tcp, mp);
613 
614 		/* Trim overlap with preceding mblk */
615 		tcp_reass_elim_overlap(tcp, mp1);
616 
617 	} while (start = end, mp = next_mp);
618 	mp1 = tcp->tcp_reass_head;
619 	/* Anything ready to go? */
620 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
621 		return (NULL);
622 	/* Eat what we can off the queue */
623 	for (;;) {
624 		mp = mp1->b_cont;
625 		end = TCP_REASS_END(mp1);
626 		TCP_REASS_SET_SEQ(mp1, 0);
627 		TCP_REASS_SET_END(mp1, 0);
628 		if (!mp) {
629 			tcp->tcp_reass_tail = NULL;
630 			break;
631 		}
632 		if (end != TCP_REASS_SEQ(mp)) {
633 			mp1->b_cont = NULL;
634 			break;
635 		}
636 		mp1 = mp;
637 	}
638 	mp1 = tcp->tcp_reass_head;
639 	tcp->tcp_reass_head = mp;
640 	return (mp1);
641 }
642 
643 /* Eliminate any overlap that mp may have over later mblks */
644 static void
645 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
646 {
647 	uint32_t	end;
648 	mblk_t		*mp1;
649 	uint32_t	u1;
650 	tcp_stack_t	*tcps = tcp->tcp_tcps;
651 
652 	end = TCP_REASS_END(mp);
653 	while ((mp1 = mp->b_cont) != NULL) {
654 		u1 = TCP_REASS_SEQ(mp1);
655 		if (!SEQ_GT(end, u1))
656 			break;
657 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
658 			mp->b_wptr -= end - u1;
659 			TCP_REASS_SET_END(mp, u1);
660 			TCPS_BUMP_MIB(tcps, tcpInDataPartDupSegs);
661 			TCPS_UPDATE_MIB(tcps, tcpInDataPartDupBytes,
662 			    end - u1);
663 			break;
664 		}
665 		mp->b_cont = mp1->b_cont;
666 		TCP_REASS_SET_SEQ(mp1, 0);
667 		TCP_REASS_SET_END(mp1, 0);
668 		freeb(mp1);
669 		TCPS_BUMP_MIB(tcps, tcpInDataDupSegs);
670 		TCPS_UPDATE_MIB(tcps, tcpInDataDupBytes, end - u1);
671 	}
672 	if (!mp1)
673 		tcp->tcp_reass_tail = mp;
674 }
675 
676 /*
677  * This function does PAWS protection check. Returns B_TRUE if the
678  * segment passes the PAWS test, else returns B_FALSE.
679  */
680 boolean_t
681 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
682 {
683 	uint8_t	flags;
684 	int	options;
685 	uint8_t *up;
686 	conn_t	*connp = tcp->tcp_connp;
687 
688 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
689 	/*
690 	 * If timestamp option is aligned nicely, get values inline,
691 	 * otherwise call general routine to parse.  Only do that
692 	 * if timestamp is the only option.
693 	 */
694 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
695 	    TCPOPT_REAL_TS_LEN &&
696 	    OK_32PTR((up = ((uint8_t *)tcpha) +
697 	    TCP_MIN_HEADER_LENGTH)) &&
698 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
699 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
700 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
701 
702 		options = TCP_OPT_TSTAMP_PRESENT;
703 	} else {
704 		if (tcp->tcp_snd_sack_ok) {
705 			tcpoptp->tcp = tcp;
706 		} else {
707 			tcpoptp->tcp = NULL;
708 		}
709 		options = tcp_parse_options(tcpha, tcpoptp);
710 	}
711 
712 	if (options & TCP_OPT_TSTAMP_PRESENT) {
713 		/*
714 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
715 		 * regardless of the timestamp, page 18 RFC 1323.bis.
716 		 */
717 		if ((flags & TH_RST) == 0 &&
718 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
719 		    tcp->tcp_ts_recent)) {
720 			if (TSTMP_LT(LBOLT_FASTPATH64,
721 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
722 				/* This segment is not acceptable. */
723 				return (B_FALSE);
724 			} else {
725 				/*
726 				 * Connection has been idle for
727 				 * too long.  Reset the timestamp
728 				 * and assume the segment is valid.
729 				 */
730 				tcp->tcp_ts_recent =
731 				    tcpoptp->tcp_opt_ts_val;
732 			}
733 		}
734 	} else {
735 		/*
736 		 * If we don't get a timestamp on every packet, we
737 		 * figure we can't really trust 'em, so we stop sending
738 		 * and parsing them.
739 		 */
740 		tcp->tcp_snd_ts_ok = B_FALSE;
741 
742 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
743 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
744 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
745 		/*
746 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
747 		 * doing a slow start here so as to not to lose on the
748 		 * transfer rate built up so far.
749 		 */
750 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
751 		if (tcp->tcp_snd_sack_ok)
752 			tcp->tcp_max_sack_blk = 4;
753 	}
754 	return (B_TRUE);
755 }
756 
757 /*
758  * Defense for the SYN attack -
759  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
760  *    one from the list of droppable eagers. This list is a subset of q0.
761  *    see comments before the definition of MAKE_DROPPABLE().
762  * 2. Don't drop a SYN request before its first timeout. This gives every
763  *    request at least til the first timeout to complete its 3-way handshake.
764  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
765  *    requests currently on the queue that has timed out. This will be used
766  *    as an indicator of whether an attack is under way, so that appropriate
767  *    actions can be taken. (It's incremented in tcp_timer() and decremented
768  *    either when eager goes into ESTABLISHED, or gets freed up.)
769  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
770  *    # of timeout drops back to <= q0len/32 => SYN alert off
771  */
772 static boolean_t
773 tcp_drop_q0(tcp_t *tcp)
774 {
775 	tcp_t	*eager;
776 	mblk_t	*mp;
777 	tcp_stack_t	*tcps = tcp->tcp_tcps;
778 
779 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
780 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
781 
782 	/* Pick oldest eager from the list of droppable eagers */
783 	eager = tcp->tcp_eager_prev_drop_q0;
784 
785 	/* If list is empty. return B_FALSE */
786 	if (eager == tcp) {
787 		return (B_FALSE);
788 	}
789 
790 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
791 	if ((mp = allocb(0, BPRI_HI)) == NULL)
792 		return (B_FALSE);
793 
794 	/*
795 	 * Take this eager out from the list of droppable eagers since we are
796 	 * going to drop it.
797 	 */
798 	MAKE_UNDROPPABLE(eager);
799 
800 	if (tcp->tcp_connp->conn_debug) {
801 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
802 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
803 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
804 		    tcp->tcp_conn_req_cnt_q0,
805 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
806 	}
807 
808 	TCPS_BUMP_MIB(tcps, tcpHalfOpenDrop);
809 
810 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
811 	CONN_INC_REF(eager->tcp_connp);
812 
813 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
814 	    tcp_clean_death_wrapper, eager->tcp_connp, NULL,
815 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
816 
817 	return (B_TRUE);
818 }
819 
820 /*
821  * Handle a SYN on an AF_INET6 socket; can be either IPv4 or IPv6
822  */
823 static mblk_t *
824 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
825     ip_recv_attr_t *ira)
826 {
827 	tcp_t 		*ltcp = lconnp->conn_tcp;
828 	tcp_t		*tcp = connp->conn_tcp;
829 	mblk_t		*tpi_mp;
830 	ipha_t		*ipha;
831 	ip6_t		*ip6h;
832 	sin6_t 		sin6;
833 	uint_t		ifindex = ira->ira_ruifindex;
834 	tcp_stack_t	*tcps = tcp->tcp_tcps;
835 
836 	if (ira->ira_flags & IRAF_IS_IPV4) {
837 		ipha = (ipha_t *)mp->b_rptr;
838 
839 		connp->conn_ipversion = IPV4_VERSION;
840 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
841 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
842 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
843 
844 		sin6 = sin6_null;
845 		sin6.sin6_addr = connp->conn_faddr_v6;
846 		sin6.sin6_port = connp->conn_fport;
847 		sin6.sin6_family = AF_INET6;
848 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
849 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
850 
851 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
852 			sin6_t	sin6d;
853 
854 			sin6d = sin6_null;
855 			sin6d.sin6_addr = connp->conn_laddr_v6;
856 			sin6d.sin6_port = connp->conn_lport;
857 			sin6d.sin6_family = AF_INET;
858 			tpi_mp = mi_tpi_extconn_ind(NULL,
859 			    (char *)&sin6d, sizeof (sin6_t),
860 			    (char *)&tcp,
861 			    (t_scalar_t)sizeof (intptr_t),
862 			    (char *)&sin6d, sizeof (sin6_t),
863 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
864 		} else {
865 			tpi_mp = mi_tpi_conn_ind(NULL,
866 			    (char *)&sin6, sizeof (sin6_t),
867 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
868 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
869 		}
870 	} else {
871 		ip6h = (ip6_t *)mp->b_rptr;
872 
873 		connp->conn_ipversion = IPV6_VERSION;
874 		connp->conn_laddr_v6 = ip6h->ip6_dst;
875 		connp->conn_faddr_v6 = ip6h->ip6_src;
876 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
877 
878 		sin6 = sin6_null;
879 		sin6.sin6_addr = connp->conn_faddr_v6;
880 		sin6.sin6_port = connp->conn_fport;
881 		sin6.sin6_family = AF_INET6;
882 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
883 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
884 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
885 
886 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
887 			/* Pass up the scope_id of remote addr */
888 			sin6.sin6_scope_id = ifindex;
889 		} else {
890 			sin6.sin6_scope_id = 0;
891 		}
892 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
893 			sin6_t	sin6d;
894 
895 			sin6d = sin6_null;
896 			sin6.sin6_addr = connp->conn_laddr_v6;
897 			sin6d.sin6_port = connp->conn_lport;
898 			sin6d.sin6_family = AF_INET6;
899 			if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_laddr_v6))
900 				sin6d.sin6_scope_id = ifindex;
901 
902 			tpi_mp = mi_tpi_extconn_ind(NULL,
903 			    (char *)&sin6d, sizeof (sin6_t),
904 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
905 			    (char *)&sin6d, sizeof (sin6_t),
906 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
907 		} else {
908 			tpi_mp = mi_tpi_conn_ind(NULL,
909 			    (char *)&sin6, sizeof (sin6_t),
910 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
911 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
912 		}
913 	}
914 
915 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
916 	return (tpi_mp);
917 }
918 
919 /* Handle a SYN on an AF_INET socket */
920 static mblk_t *
921 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
922     ip_recv_attr_t *ira)
923 {
924 	tcp_t 		*ltcp = lconnp->conn_tcp;
925 	tcp_t		*tcp = connp->conn_tcp;
926 	sin_t		sin;
927 	mblk_t		*tpi_mp = NULL;
928 	tcp_stack_t	*tcps = tcp->tcp_tcps;
929 	ipha_t		*ipha;
930 
931 	ASSERT(ira->ira_flags & IRAF_IS_IPV4);
932 	ipha = (ipha_t *)mp->b_rptr;
933 
934 	connp->conn_ipversion = IPV4_VERSION;
935 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
936 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
937 	connp->conn_saddr_v6 = connp->conn_laddr_v6;
938 
939 	sin = sin_null;
940 	sin.sin_addr.s_addr = connp->conn_faddr_v4;
941 	sin.sin_port = connp->conn_fport;
942 	sin.sin_family = AF_INET;
943 	if (lconnp->conn_recv_ancillary.crb_recvdstaddr) {
944 		sin_t	sind;
945 
946 		sind = sin_null;
947 		sind.sin_addr.s_addr = connp->conn_laddr_v4;
948 		sind.sin_port = connp->conn_lport;
949 		sind.sin_family = AF_INET;
950 		tpi_mp = mi_tpi_extconn_ind(NULL,
951 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
952 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
953 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
954 	} else {
955 		tpi_mp = mi_tpi_conn_ind(NULL,
956 		    (char *)&sin, sizeof (sin_t),
957 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
958 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
959 	}
960 
961 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
962 	return (tpi_mp);
963 }
964 
965 /*
966  * Called via squeue to get on to eager's perimeter. It sends a
967  * TH_RST if eager is in the fanout table. The listener wants the
968  * eager to disappear either by means of tcp_eager_blowoff() or
969  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
970  * called (via squeue) if the eager cannot be inserted in the
971  * fanout table in tcp_input_listener().
972  */
973 /* ARGSUSED */
974 void
975 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
976 {
977 	conn_t	*econnp = (conn_t *)arg;
978 	tcp_t	*eager = econnp->conn_tcp;
979 	tcp_t	*listener = eager->tcp_listener;
980 
981 	/*
982 	 * We could be called because listener is closing. Since
983 	 * the eager was using listener's queue's, we avoid
984 	 * using the listeners queues from now on.
985 	 */
986 	ASSERT(eager->tcp_detached);
987 	econnp->conn_rq = NULL;
988 	econnp->conn_wq = NULL;
989 
990 	/*
991 	 * An eager's conn_fanout will be NULL if it's a duplicate
992 	 * for an existing 4-tuples in the conn fanout table.
993 	 * We don't want to send an RST out in such case.
994 	 */
995 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
996 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
997 		    eager, eager->tcp_snxt, 0, TH_RST);
998 	}
999 
1000 	/* We are here because listener wants this eager gone */
1001 	if (listener != NULL) {
1002 		mutex_enter(&listener->tcp_eager_lock);
1003 		tcp_eager_unlink(eager);
1004 		if (eager->tcp_tconnind_started) {
1005 			/*
1006 			 * The eager has sent a conn_ind up to the
1007 			 * listener but listener decides to close
1008 			 * instead. We need to drop the extra ref
1009 			 * placed on eager in tcp_input_data() before
1010 			 * sending the conn_ind to listener.
1011 			 */
1012 			CONN_DEC_REF(econnp);
1013 		}
1014 		mutex_exit(&listener->tcp_eager_lock);
1015 		CONN_DEC_REF(listener->tcp_connp);
1016 	}
1017 
1018 	if (eager->tcp_state != TCPS_CLOSED)
1019 		tcp_close_detached(eager);
1020 }
1021 
1022 /*
1023  * Reset any eager connection hanging off this listener marked
1024  * with 'seqnum' and then reclaim it's resources.
1025  */
1026 boolean_t
1027 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
1028 {
1029 	tcp_t	*eager;
1030 	mblk_t 	*mp;
1031 
1032 	eager = listener;
1033 	mutex_enter(&listener->tcp_eager_lock);
1034 	do {
1035 		eager = eager->tcp_eager_next_q;
1036 		if (eager == NULL) {
1037 			mutex_exit(&listener->tcp_eager_lock);
1038 			return (B_FALSE);
1039 		}
1040 	} while (eager->tcp_conn_req_seqnum != seqnum);
1041 
1042 	if (eager->tcp_closemp_used) {
1043 		mutex_exit(&listener->tcp_eager_lock);
1044 		return (B_TRUE);
1045 	}
1046 	eager->tcp_closemp_used = B_TRUE;
1047 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
1048 	CONN_INC_REF(eager->tcp_connp);
1049 	mutex_exit(&listener->tcp_eager_lock);
1050 	mp = &eager->tcp_closemp;
1051 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
1052 	    eager->tcp_connp, NULL, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
1053 	return (B_TRUE);
1054 }
1055 
1056 /*
1057  * Reset any eager connection hanging off this listener
1058  * and then reclaim it's resources.
1059  */
1060 void
1061 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
1062 {
1063 	tcp_t	*eager;
1064 	mblk_t	*mp;
1065 	tcp_stack_t	*tcps = listener->tcp_tcps;
1066 
1067 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
1068 
1069 	if (!q0_only) {
1070 		/* First cleanup q */
1071 		TCP_STAT(tcps, tcp_eager_blowoff_q);
1072 		eager = listener->tcp_eager_next_q;
1073 		while (eager != NULL) {
1074 			if (!eager->tcp_closemp_used) {
1075 				eager->tcp_closemp_used = B_TRUE;
1076 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
1077 				CONN_INC_REF(eager->tcp_connp);
1078 				mp = &eager->tcp_closemp;
1079 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
1080 				    tcp_eager_kill, eager->tcp_connp, NULL,
1081 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
1082 			}
1083 			eager = eager->tcp_eager_next_q;
1084 		}
1085 	}
1086 	/* Then cleanup q0 */
1087 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
1088 	eager = listener->tcp_eager_next_q0;
1089 	while (eager != listener) {
1090 		if (!eager->tcp_closemp_used) {
1091 			eager->tcp_closemp_used = B_TRUE;
1092 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
1093 			CONN_INC_REF(eager->tcp_connp);
1094 			mp = &eager->tcp_closemp;
1095 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
1096 			    tcp_eager_kill, eager->tcp_connp, NULL, SQ_FILL,
1097 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
1098 		}
1099 		eager = eager->tcp_eager_next_q0;
1100 	}
1101 }
1102 
1103 /*
1104  * If we are an eager connection hanging off a listener that hasn't
1105  * formally accepted the connection yet, get off his list and blow off
1106  * any data that we have accumulated.
1107  */
1108 void
1109 tcp_eager_unlink(tcp_t *tcp)
1110 {
1111 	tcp_t	*listener = tcp->tcp_listener;
1112 
1113 	ASSERT(listener != NULL);
1114 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
1115 	if (tcp->tcp_eager_next_q0 != NULL) {
1116 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
1117 
1118 		/* Remove the eager tcp from q0 */
1119 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
1120 		    tcp->tcp_eager_prev_q0;
1121 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
1122 		    tcp->tcp_eager_next_q0;
1123 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
1124 		listener->tcp_conn_req_cnt_q0--;
1125 
1126 		tcp->tcp_eager_next_q0 = NULL;
1127 		tcp->tcp_eager_prev_q0 = NULL;
1128 
1129 		/*
1130 		 * Take the eager out, if it is in the list of droppable
1131 		 * eagers.
1132 		 */
1133 		MAKE_UNDROPPABLE(tcp);
1134 
1135 		if (tcp->tcp_syn_rcvd_timeout != 0) {
1136 			/* we have timed out before */
1137 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
1138 			listener->tcp_syn_rcvd_timeout--;
1139 		}
1140 	} else {
1141 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
1142 		tcp_t	*prev = NULL;
1143 
1144 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
1145 			if (tcpp[0] == tcp) {
1146 				if (listener->tcp_eager_last_q == tcp) {
1147 					/*
1148 					 * If we are unlinking the last
1149 					 * element on the list, adjust
1150 					 * tail pointer. Set tail pointer
1151 					 * to nil when list is empty.
1152 					 */
1153 					ASSERT(tcp->tcp_eager_next_q == NULL);
1154 					if (listener->tcp_eager_last_q ==
1155 					    listener->tcp_eager_next_q) {
1156 						listener->tcp_eager_last_q =
1157 						    NULL;
1158 					} else {
1159 						/*
1160 						 * We won't get here if there
1161 						 * is only one eager in the
1162 						 * list.
1163 						 */
1164 						ASSERT(prev != NULL);
1165 						listener->tcp_eager_last_q =
1166 						    prev;
1167 					}
1168 				}
1169 				tcpp[0] = tcp->tcp_eager_next_q;
1170 				tcp->tcp_eager_next_q = NULL;
1171 				tcp->tcp_eager_last_q = NULL;
1172 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
1173 				listener->tcp_conn_req_cnt_q--;
1174 				break;
1175 			}
1176 			prev = tcpp[0];
1177 		}
1178 	}
1179 	tcp->tcp_listener = NULL;
1180 }
1181 
1182 /* BEGIN CSTYLED */
1183 /*
1184  *
1185  * The sockfs ACCEPT path:
1186  * =======================
1187  *
1188  * The eager is now established in its own perimeter as soon as SYN is
1189  * received in tcp_input_listener(). When sockfs receives conn_ind, it
1190  * completes the accept processing on the acceptor STREAM. The sending
1191  * of conn_ind part is common for both sockfs listener and a TLI/XTI
1192  * listener but a TLI/XTI listener completes the accept processing
1193  * on the listener perimeter.
1194  *
1195  * Common control flow for 3 way handshake:
1196  * ----------------------------------------
1197  *
1198  * incoming SYN (listener perimeter)	-> tcp_input_listener()
1199  *
1200  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_input_data()
1201  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
1202  *
1203  * Sockfs ACCEPT Path:
1204  * -------------------
1205  *
1206  * open acceptor stream (tcp_open allocates tcp_tli_accept()
1207  * as STREAM entry point)
1208  *
1209  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_tli_accept()
1210  *
1211  * tcp_tli_accept() extracts the eager and makes the q->q_ptr <-> eager
1212  * association (we are not behind eager's squeue but sockfs is protecting us
1213  * and no one knows about this stream yet. The STREAMS entry point q->q_info
1214  * is changed to point at tcp_wput().
1215  *
1216  * tcp_accept_common() sends any deferred eagers via tcp_send_pending() to
1217  * listener (done on listener's perimeter).
1218  *
1219  * tcp_tli_accept() calls tcp_accept_finish() on eagers perimeter to finish
1220  * accept.
1221  *
1222  * TLI/XTI client ACCEPT path:
1223  * ---------------------------
1224  *
1225  * soaccept() sends T_CONN_RES on the listener STREAM.
1226  *
1227  * tcp_tli_accept() -> tcp_accept_swap() complete the processing and send
1228  * a M_SETOPS mblk to eager perimeter to finish accept (tcp_accept_finish()).
1229  *
1230  * Locks:
1231  * ======
1232  *
1233  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
1234  * and listeners->tcp_eager_next_q.
1235  *
1236  * Referencing:
1237  * ============
1238  *
1239  * 1) We start out in tcp_input_listener by eager placing a ref on
1240  * listener and listener adding eager to listeners->tcp_eager_next_q0.
1241  *
1242  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
1243  * doing so we place a ref on the eager. This ref is finally dropped at the
1244  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
1245  * reference is dropped by the squeue framework.
1246  *
1247  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
1248  *
1249  * The reference must be released by the same entity that added the reference
1250  * In the above scheme, the eager is the entity that adds and releases the
1251  * references. Note that tcp_accept_finish executes in the squeue of the eager
1252  * (albeit after it is attached to the acceptor stream). Though 1. executes
1253  * in the listener's squeue, the eager is nascent at this point and the
1254  * reference can be considered to have been added on behalf of the eager.
1255  *
1256  * Eager getting a Reset or listener closing:
1257  * ==========================================
1258  *
1259  * Once the listener and eager are linked, the listener never does the unlink.
1260  * If the listener needs to close, tcp_eager_cleanup() is called which queues
1261  * a message on all eager perimeter. The eager then does the unlink, clears
1262  * any pointers to the listener's queue and drops the reference to the
1263  * listener. The listener waits in tcp_close outside the squeue until its
1264  * refcount has dropped to 1. This ensures that the listener has waited for
1265  * all eagers to clear their association with the listener.
1266  *
1267  * Similarly, if eager decides to go away, it can unlink itself and close.
1268  * When the T_CONN_RES comes down, we check if eager has closed. Note that
1269  * the reference to eager is still valid because of the extra ref we put
1270  * in tcp_send_conn_ind.
1271  *
1272  * Listener can always locate the eager under the protection
1273  * of the listener->tcp_eager_lock, and then do a refhold
1274  * on the eager during the accept processing.
1275  *
1276  * The acceptor stream accesses the eager in the accept processing
1277  * based on the ref placed on eager before sending T_conn_ind.
1278  * The only entity that can negate this refhold is a listener close
1279  * which is mutually exclusive with an active acceptor stream.
1280  *
1281  * Eager's reference on the listener
1282  * ===================================
1283  *
1284  * If the accept happens (even on a closed eager) the eager drops its
1285  * reference on the listener at the start of tcp_accept_finish. If the
1286  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
1287  * the reference is dropped in tcp_closei_local. If the listener closes,
1288  * the reference is dropped in tcp_eager_kill. In all cases the reference
1289  * is dropped while executing in the eager's context (squeue).
1290  */
1291 /* END CSTYLED */
1292 
1293 /* Process the SYN packet, mp, directed at the listener 'tcp' */
1294 
1295 /*
1296  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
1297  * tcp_input_data will not see any packets for listeners since the listener
1298  * has conn_recv set to tcp_input_listener.
1299  */
1300 /* ARGSUSED */
1301 static void
1302 tcp_input_listener(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
1303 {
1304 	tcpha_t		*tcpha;
1305 	uint32_t	seg_seq;
1306 	tcp_t		*eager;
1307 	int		err;
1308 	conn_t		*econnp = NULL;
1309 	squeue_t	*new_sqp;
1310 	mblk_t		*mp1;
1311 	uint_t 		ip_hdr_len;
1312 	conn_t		*lconnp = (conn_t *)arg;
1313 	tcp_t		*listener = lconnp->conn_tcp;
1314 	tcp_stack_t	*tcps = listener->tcp_tcps;
1315 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
1316 	uint_t		flags;
1317 	mblk_t		*tpi_mp;
1318 	uint_t		ifindex = ira->ira_ruifindex;
1319 	boolean_t	tlc_set = B_FALSE;
1320 
1321 	ip_hdr_len = ira->ira_ip_hdr_length;
1322 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
1323 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
1324 
1325 	if (!(flags & TH_SYN)) {
1326 		if ((flags & TH_RST) || (flags & TH_URG)) {
1327 			freemsg(mp);
1328 			return;
1329 		}
1330 		if (flags & TH_ACK) {
1331 			/* Note this executes in listener's squeue */
1332 			tcp_xmit_listeners_reset(mp, ira, ipst, lconnp);
1333 			return;
1334 		}
1335 
1336 		freemsg(mp);
1337 		return;
1338 	}
1339 
1340 	if (listener->tcp_state != TCPS_LISTEN)
1341 		goto error2;
1342 
1343 	ASSERT(IPCL_IS_BOUND(lconnp));
1344 
1345 	mutex_enter(&listener->tcp_eager_lock);
1346 
1347 	/*
1348 	 * The system is under memory pressure, so we need to do our part
1349 	 * to relieve the pressure.  So we only accept new request if there
1350 	 * is nothing waiting to be accepted or waiting to complete the 3-way
1351 	 * handshake.  This means that busy listener will not get too many
1352 	 * new requests which they cannot handle in time while non-busy
1353 	 * listener is still functioning properly.
1354 	 */
1355 	if (tcps->tcps_reclaim && (listener->tcp_conn_req_cnt_q > 0 ||
1356 	    listener->tcp_conn_req_cnt_q0 > 0)) {
1357 		mutex_exit(&listener->tcp_eager_lock);
1358 		TCP_STAT(tcps, tcp_listen_mem_drop);
1359 		goto error2;
1360 	}
1361 
1362 	if (listener->tcp_conn_req_cnt_q >= listener->tcp_conn_req_max) {
1363 		mutex_exit(&listener->tcp_eager_lock);
1364 		TCP_STAT(tcps, tcp_listendrop);
1365 		TCPS_BUMP_MIB(tcps, tcpListenDrop);
1366 		if (lconnp->conn_debug) {
1367 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
1368 			    "tcp_input_listener: listen backlog (max=%d) "
1369 			    "overflow (%d pending) on %s",
1370 			    listener->tcp_conn_req_max,
1371 			    listener->tcp_conn_req_cnt_q,
1372 			    tcp_display(listener, NULL, DISP_PORT_ONLY));
1373 		}
1374 		goto error2;
1375 	}
1376 
1377 	if (listener->tcp_conn_req_cnt_q0 >=
1378 	    listener->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
1379 		/*
1380 		 * Q0 is full. Drop a pending half-open req from the queue
1381 		 * to make room for the new SYN req. Also mark the time we
1382 		 * drop a SYN.
1383 		 *
1384 		 * A more aggressive defense against SYN attack will
1385 		 * be to set the "tcp_syn_defense" flag now.
1386 		 */
1387 		TCP_STAT(tcps, tcp_listendropq0);
1388 		listener->tcp_last_rcv_lbolt = ddi_get_lbolt64();
1389 		if (!tcp_drop_q0(listener)) {
1390 			mutex_exit(&listener->tcp_eager_lock);
1391 			TCPS_BUMP_MIB(tcps, tcpListenDropQ0);
1392 			if (lconnp->conn_debug) {
1393 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
1394 				    "tcp_input_listener: listen half-open "
1395 				    "queue (max=%d) full (%d pending) on %s",
1396 				    tcps->tcps_conn_req_max_q0,
1397 				    listener->tcp_conn_req_cnt_q0,
1398 				    tcp_display(listener, NULL,
1399 				    DISP_PORT_ONLY));
1400 			}
1401 			goto error2;
1402 		}
1403 	}
1404 
1405 	/*
1406 	 * Enforce the limit set on the number of connections per listener.
1407 	 * Note that tlc_cnt starts with 1.  So need to add 1 to tlc_max
1408 	 * for comparison.
1409 	 */
1410 	if (listener->tcp_listen_cnt != NULL) {
1411 		tcp_listen_cnt_t *tlc = listener->tcp_listen_cnt;
1412 		int64_t now;
1413 
1414 		if (atomic_add_32_nv(&tlc->tlc_cnt, 1) > tlc->tlc_max + 1) {
1415 			mutex_exit(&listener->tcp_eager_lock);
1416 			now = ddi_get_lbolt64();
1417 			atomic_add_32(&tlc->tlc_cnt, -1);
1418 			TCP_STAT(tcps, tcp_listen_cnt_drop);
1419 			tlc->tlc_drop++;
1420 			if (now - tlc->tlc_report_time >
1421 			    MSEC_TO_TICK(TCP_TLC_REPORT_INTERVAL)) {
1422 				zcmn_err(lconnp->conn_zoneid, CE_WARN,
1423 				    "Listener (port %d) connection max (%u) "
1424 				    "reached: %u attempts dropped total\n",
1425 				    ntohs(listener->tcp_connp->conn_lport),
1426 				    tlc->tlc_max, tlc->tlc_drop);
1427 				tlc->tlc_report_time = now;
1428 			}
1429 			goto error2;
1430 		}
1431 		tlc_set = B_TRUE;
1432 	}
1433 
1434 	mutex_exit(&listener->tcp_eager_lock);
1435 
1436 	/*
1437 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
1438 	 * or based on the ring (for packets from GLD). Otherwise it is
1439 	 * set based on lbolt i.e., a somewhat random number.
1440 	 */
1441 	ASSERT(ira->ira_sqp != NULL);
1442 	new_sqp = ira->ira_sqp;
1443 
1444 	econnp = (conn_t *)tcp_get_conn(arg2, tcps);
1445 	if (econnp == NULL)
1446 		goto error2;
1447 
1448 	ASSERT(econnp->conn_netstack == lconnp->conn_netstack);
1449 	econnp->conn_sqp = new_sqp;
1450 	econnp->conn_initial_sqp = new_sqp;
1451 	econnp->conn_ixa->ixa_sqp = new_sqp;
1452 
1453 	econnp->conn_fport = tcpha->tha_lport;
1454 	econnp->conn_lport = tcpha->tha_fport;
1455 
1456 	err = conn_inherit_parent(lconnp, econnp);
1457 	if (err != 0)
1458 		goto error3;
1459 
1460 	/* We already know the laddr of the new connection is ours */
1461 	econnp->conn_ixa->ixa_src_generation = ipst->ips_src_generation;
1462 
1463 	ASSERT(OK_32PTR(mp->b_rptr));
1464 	ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION ||
1465 	    IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
1466 
1467 	if (lconnp->conn_family == AF_INET) {
1468 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
1469 		tpi_mp = tcp_conn_create_v4(lconnp, econnp, mp, ira);
1470 	} else {
1471 		tpi_mp = tcp_conn_create_v6(lconnp, econnp, mp, ira);
1472 	}
1473 
1474 	if (tpi_mp == NULL)
1475 		goto error3;
1476 
1477 	eager = econnp->conn_tcp;
1478 	eager->tcp_detached = B_TRUE;
1479 	SOCK_CONNID_INIT(eager->tcp_connid);
1480 
1481 	tcp_init_values(eager);
1482 
1483 	ASSERT((econnp->conn_ixa->ixa_flags &
1484 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
1485 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO)) ==
1486 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
1487 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO));
1488 
1489 	if (!tcps->tcps_dev_flow_ctl)
1490 		econnp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
1491 
1492 	/* Prepare for diffing against previous packets */
1493 	eager->tcp_recvifindex = 0;
1494 	eager->tcp_recvhops = 0xffffffffU;
1495 
1496 	if (!(ira->ira_flags & IRAF_IS_IPV4) && econnp->conn_bound_if == 0) {
1497 		if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_faddr_v6) ||
1498 		    IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6)) {
1499 			econnp->conn_incoming_ifindex = ifindex;
1500 			econnp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
1501 			econnp->conn_ixa->ixa_scopeid = ifindex;
1502 		}
1503 	}
1504 
1505 	if ((ira->ira_flags & (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS)) ==
1506 	    (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS) &&
1507 	    tcps->tcps_rev_src_routes) {
1508 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
1509 		ip_pkt_t *ipp = &econnp->conn_xmit_ipp;
1510 
1511 		/* Source routing option copyover (reverse it) */
1512 		err = ip_find_hdr_v4(ipha, ipp, B_TRUE);
1513 		if (err != 0) {
1514 			freemsg(tpi_mp);
1515 			goto error3;
1516 		}
1517 		ip_pkt_source_route_reverse_v4(ipp);
1518 	}
1519 
1520 	ASSERT(eager->tcp_conn.tcp_eager_conn_ind == NULL);
1521 	ASSERT(!eager->tcp_tconnind_started);
1522 	/*
1523 	 * If the SYN came with a credential, it's a loopback packet or a
1524 	 * labeled packet; attach the credential to the TPI message.
1525 	 */
1526 	if (ira->ira_cred != NULL)
1527 		mblk_setcred(tpi_mp, ira->ira_cred, ira->ira_cpid);
1528 
1529 	eager->tcp_conn.tcp_eager_conn_ind = tpi_mp;
1530 
1531 	/* Inherit the listener's SSL protection state */
1532 	if ((eager->tcp_kssl_ent = listener->tcp_kssl_ent) != NULL) {
1533 		kssl_hold_ent(eager->tcp_kssl_ent);
1534 		eager->tcp_kssl_pending = B_TRUE;
1535 	}
1536 
1537 	/* Inherit the listener's non-STREAMS flag */
1538 	if (IPCL_IS_NONSTR(lconnp)) {
1539 		econnp->conn_flags |= IPCL_NONSTR;
1540 	}
1541 
1542 	ASSERT(eager->tcp_ordrel_mp == NULL);
1543 
1544 	if (!IPCL_IS_NONSTR(econnp)) {
1545 		/*
1546 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
1547 		 * at close time, we will always have that to send up.
1548 		 * Otherwise, we need to do special handling in case the
1549 		 * allocation fails at that time.
1550 		 */
1551 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
1552 			goto error3;
1553 	}
1554 	/*
1555 	 * Now that the IP addresses and ports are setup in econnp we
1556 	 * can do the IPsec policy work.
1557 	 */
1558 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
1559 		if (lconnp->conn_policy != NULL) {
1560 			/*
1561 			 * Inherit the policy from the listener; use
1562 			 * actions from ira
1563 			 */
1564 			if (!ip_ipsec_policy_inherit(econnp, lconnp, ira)) {
1565 				CONN_DEC_REF(econnp);
1566 				freemsg(mp);
1567 				goto error3;
1568 			}
1569 		}
1570 	}
1571 
1572 	/* Inherit various TCP parameters from the listener */
1573 	eager->tcp_naglim = listener->tcp_naglim;
1574 	eager->tcp_first_timer_threshold = listener->tcp_first_timer_threshold;
1575 	eager->tcp_second_timer_threshold =
1576 	    listener->tcp_second_timer_threshold;
1577 	eager->tcp_first_ctimer_threshold =
1578 	    listener->tcp_first_ctimer_threshold;
1579 	eager->tcp_second_ctimer_threshold =
1580 	    listener->tcp_second_ctimer_threshold;
1581 
1582 	/*
1583 	 * tcp_set_destination() may set tcp_rwnd according to the route
1584 	 * metrics. If it does not, the eager's receive window will be set
1585 	 * to the listener's receive window later in this function.
1586 	 */
1587 	eager->tcp_rwnd = 0;
1588 
1589 	/*
1590 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
1591 	 * calling tcp_process_options() which set the initial cwnd.
1592 	 */
1593 	eager->tcp_init_cwnd = listener->tcp_init_cwnd;
1594 
1595 	if (is_system_labeled()) {
1596 		ip_xmit_attr_t *ixa = econnp->conn_ixa;
1597 
1598 		ASSERT(ira->ira_tsl != NULL);
1599 		/* Discard any old label */
1600 		if (ixa->ixa_free_flags & IXA_FREE_TSL) {
1601 			ASSERT(ixa->ixa_tsl != NULL);
1602 			label_rele(ixa->ixa_tsl);
1603 			ixa->ixa_free_flags &= ~IXA_FREE_TSL;
1604 			ixa->ixa_tsl = NULL;
1605 		}
1606 		if ((lconnp->conn_mlp_type != mlptSingle ||
1607 		    lconnp->conn_mac_mode != CONN_MAC_DEFAULT) &&
1608 		    ira->ira_tsl != NULL) {
1609 			/*
1610 			 * If this is an MLP connection or a MAC-Exempt
1611 			 * connection with an unlabeled node, packets are to be
1612 			 * exchanged using the security label of the received
1613 			 * SYN packet instead of the server application's label.
1614 			 * tsol_check_dest called from ip_set_destination
1615 			 * might later update TSF_UNLABELED by replacing
1616 			 * ixa_tsl with a new label.
1617 			 */
1618 			label_hold(ira->ira_tsl);
1619 			ip_xmit_attr_replace_tsl(ixa, ira->ira_tsl);
1620 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
1621 			    econnp, ts_label_t *, ixa->ixa_tsl)
1622 		} else {
1623 			ixa->ixa_tsl = crgetlabel(econnp->conn_cred);
1624 			DTRACE_PROBE2(syn_accept, conn_t *,
1625 			    econnp, ts_label_t *, ixa->ixa_tsl)
1626 		}
1627 		/*
1628 		 * conn_connect() called from tcp_set_destination will verify
1629 		 * the destination is allowed to receive packets at the
1630 		 * security label of the SYN-ACK we are generating. As part of
1631 		 * that, tsol_check_dest() may create a new effective label for
1632 		 * this connection.
1633 		 * Finally conn_connect() will call conn_update_label.
1634 		 * All that remains for TCP to do is to call
1635 		 * conn_build_hdr_template which is done as part of
1636 		 * tcp_set_destination.
1637 		 */
1638 	}
1639 
1640 	/*
1641 	 * Since we will clear tcp_listener before we clear tcp_detached
1642 	 * in the accept code we need tcp_hard_binding aka tcp_accept_inprogress
1643 	 * so we can tell a TCP_DETACHED_NONEAGER apart.
1644 	 */
1645 	eager->tcp_hard_binding = B_TRUE;
1646 
1647 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
1648 	    TCP_BIND_HASH(econnp->conn_lport)], eager, 0);
1649 
1650 	CL_INET_CONNECT(econnp, B_FALSE, err);
1651 	if (err != 0) {
1652 		tcp_bind_hash_remove(eager);
1653 		goto error3;
1654 	}
1655 
1656 	/*
1657 	 * No need to check for multicast destination since ip will only pass
1658 	 * up multicasts to those that have expressed interest
1659 	 * TODO: what about rejecting broadcasts?
1660 	 * Also check that source is not a multicast or broadcast address.
1661 	 */
1662 	eager->tcp_state = TCPS_SYN_RCVD;
1663 	SOCK_CONNID_BUMP(eager->tcp_connid);
1664 
1665 	/*
1666 	 * Adapt our mss, ttl, ... based on the remote address.
1667 	 */
1668 
1669 	if (tcp_set_destination(eager) != 0) {
1670 		TCPS_BUMP_MIB(tcps, tcpAttemptFails);
1671 		/* Undo the bind_hash_insert */
1672 		tcp_bind_hash_remove(eager);
1673 		goto error3;
1674 	}
1675 
1676 	/* Process all TCP options. */
1677 	tcp_process_options(eager, tcpha);
1678 
1679 	/* Is the other end ECN capable? */
1680 	if (tcps->tcps_ecn_permitted >= 1 &&
1681 	    (tcpha->tha_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
1682 		eager->tcp_ecn_ok = B_TRUE;
1683 	}
1684 
1685 	/*
1686 	 * The listener's conn_rcvbuf should be the default window size or a
1687 	 * window size changed via SO_RCVBUF option. First round up the
1688 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
1689 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
1690 	 * setting.
1691 	 *
1692 	 * Note if there is a rpipe metric associated with the remote host,
1693 	 * we should not inherit receive window size from listener.
1694 	 */
1695 	eager->tcp_rwnd = MSS_ROUNDUP(
1696 	    (eager->tcp_rwnd == 0 ? econnp->conn_rcvbuf :
1697 	    eager->tcp_rwnd), eager->tcp_mss);
1698 	if (eager->tcp_snd_ws_ok)
1699 		tcp_set_ws_value(eager);
1700 	/*
1701 	 * Note that this is the only place tcp_rwnd_set() is called for
1702 	 * accepting a connection.  We need to call it here instead of
1703 	 * after the 3-way handshake because we need to tell the other
1704 	 * side our rwnd in the SYN-ACK segment.
1705 	 */
1706 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
1707 
1708 	ASSERT(eager->tcp_connp->conn_rcvbuf != 0 &&
1709 	    eager->tcp_connp->conn_rcvbuf == eager->tcp_rwnd);
1710 
1711 	ASSERT(econnp->conn_rcvbuf != 0 &&
1712 	    econnp->conn_rcvbuf == eager->tcp_rwnd);
1713 
1714 	/* Put a ref on the listener for the eager. */
1715 	CONN_INC_REF(lconnp);
1716 	mutex_enter(&listener->tcp_eager_lock);
1717 	listener->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
1718 	eager->tcp_eager_next_q0 = listener->tcp_eager_next_q0;
1719 	listener->tcp_eager_next_q0 = eager;
1720 	eager->tcp_eager_prev_q0 = listener;
1721 
1722 	/* Set tcp_listener before adding it to tcp_conn_fanout */
1723 	eager->tcp_listener = listener;
1724 	eager->tcp_saved_listener = listener;
1725 
1726 	/*
1727 	 * Set tcp_listen_cnt so that when the connection is done, the counter
1728 	 * is decremented.
1729 	 */
1730 	eager->tcp_listen_cnt = listener->tcp_listen_cnt;
1731 
1732 	/*
1733 	 * Tag this detached tcp vector for later retrieval
1734 	 * by our listener client in tcp_accept().
1735 	 */
1736 	eager->tcp_conn_req_seqnum = listener->tcp_conn_req_seqnum;
1737 	listener->tcp_conn_req_cnt_q0++;
1738 	if (++listener->tcp_conn_req_seqnum == -1) {
1739 		/*
1740 		 * -1 is "special" and defined in TPI as something
1741 		 * that should never be used in T_CONN_IND
1742 		 */
1743 		++listener->tcp_conn_req_seqnum;
1744 	}
1745 	mutex_exit(&listener->tcp_eager_lock);
1746 
1747 	if (listener->tcp_syn_defense) {
1748 		/* Don't drop the SYN that comes from a good IP source */
1749 		ipaddr_t *addr_cache;
1750 
1751 		addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
1752 		if (addr_cache != NULL && econnp->conn_faddr_v4 ==
1753 		    addr_cache[IP_ADDR_CACHE_HASH(econnp->conn_faddr_v4)]) {
1754 			eager->tcp_dontdrop = B_TRUE;
1755 		}
1756 	}
1757 
1758 	/*
1759 	 * We need to insert the eager in its own perimeter but as soon
1760 	 * as we do that, we expose the eager to the classifier and
1761 	 * should not touch any field outside the eager's perimeter.
1762 	 * So do all the work necessary before inserting the eager
1763 	 * in its own perimeter. Be optimistic that conn_connect()
1764 	 * will succeed but undo everything if it fails.
1765 	 */
1766 	seg_seq = ntohl(tcpha->tha_seq);
1767 	eager->tcp_irs = seg_seq;
1768 	eager->tcp_rack = seg_seq;
1769 	eager->tcp_rnxt = seg_seq + 1;
1770 	eager->tcp_tcpha->tha_ack = htonl(eager->tcp_rnxt);
1771 	TCPS_BUMP_MIB(tcps, tcpPassiveOpens);
1772 	eager->tcp_state = TCPS_SYN_RCVD;
1773 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
1774 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
1775 	if (mp1 == NULL) {
1776 		/*
1777 		 * Increment the ref count as we are going to
1778 		 * enqueueing an mp in squeue
1779 		 */
1780 		CONN_INC_REF(econnp);
1781 		goto error;
1782 	}
1783 
1784 	/*
1785 	 * We need to start the rto timer. In normal case, we start
1786 	 * the timer after sending the packet on the wire (or at
1787 	 * least believing that packet was sent by waiting for
1788 	 * conn_ip_output() to return). Since this is the first packet
1789 	 * being sent on the wire for the eager, our initial tcp_rto
1790 	 * is at least tcp_rexmit_interval_min which is a fairly
1791 	 * large value to allow the algorithm to adjust slowly to large
1792 	 * fluctuations of RTT during first few transmissions.
1793 	 *
1794 	 * Starting the timer first and then sending the packet in this
1795 	 * case shouldn't make much difference since tcp_rexmit_interval_min
1796 	 * is of the order of several 100ms and starting the timer
1797 	 * first and then sending the packet will result in difference
1798 	 * of few micro seconds.
1799 	 *
1800 	 * Without this optimization, we are forced to hold the fanout
1801 	 * lock across the ipcl_bind_insert() and sending the packet
1802 	 * so that we don't race against an incoming packet (maybe RST)
1803 	 * for this eager.
1804 	 *
1805 	 * It is necessary to acquire an extra reference on the eager
1806 	 * at this point and hold it until after tcp_send_data() to
1807 	 * ensure against an eager close race.
1808 	 */
1809 
1810 	CONN_INC_REF(econnp);
1811 
1812 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
1813 
1814 	/*
1815 	 * Insert the eager in its own perimeter now. We are ready to deal
1816 	 * with any packets on eager.
1817 	 */
1818 	if (ipcl_conn_insert(econnp) != 0)
1819 		goto error;
1820 
1821 	ASSERT(econnp->conn_ixa->ixa_notify_cookie == econnp->conn_tcp);
1822 	freemsg(mp);
1823 	/*
1824 	 * Send the SYN-ACK. Use the right squeue so that conn_ixa is
1825 	 * only used by one thread at a time.
1826 	 */
1827 	if (econnp->conn_sqp == lconnp->conn_sqp) {
1828 		(void) conn_ip_output(mp1, econnp->conn_ixa);
1829 		CONN_DEC_REF(econnp);
1830 	} else {
1831 		SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_send_synack,
1832 		    econnp, NULL, SQ_PROCESS, SQTAG_TCP_SEND_SYNACK);
1833 	}
1834 	return;
1835 error:
1836 	freemsg(mp1);
1837 	eager->tcp_closemp_used = B_TRUE;
1838 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
1839 	mp1 = &eager->tcp_closemp;
1840 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
1841 	    econnp, NULL, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
1842 
1843 	/*
1844 	 * If a connection already exists, send the mp to that connections so
1845 	 * that it can be appropriately dealt with.
1846 	 */
1847 	ipst = tcps->tcps_netstack->netstack_ip;
1848 
1849 	if ((econnp = ipcl_classify(mp, ira, ipst)) != NULL) {
1850 		if (!IPCL_IS_CONNECTED(econnp)) {
1851 			/*
1852 			 * Something bad happened. ipcl_conn_insert()
1853 			 * failed because a connection already existed
1854 			 * in connected hash but we can't find it
1855 			 * anymore (someone blew it away). Just
1856 			 * free this message and hopefully remote
1857 			 * will retransmit at which time the SYN can be
1858 			 * treated as a new connection or dealth with
1859 			 * a TH_RST if a connection already exists.
1860 			 */
1861 			CONN_DEC_REF(econnp);
1862 			freemsg(mp);
1863 		} else {
1864 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp, tcp_input_data,
1865 			    econnp, ira, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
1866 		}
1867 	} else {
1868 		/* Nobody wants this packet */
1869 		freemsg(mp);
1870 	}
1871 	return;
1872 error3:
1873 	CONN_DEC_REF(econnp);
1874 error2:
1875 	freemsg(mp);
1876 	if (tlc_set)
1877 		atomic_add_32(&listener->tcp_listen_cnt->tlc_cnt, -1);
1878 }
1879 
1880 /*
1881  * In an ideal case of vertical partition in NUMA architecture, its
1882  * beneficial to have the listener and all the incoming connections
1883  * tied to the same squeue. The other constraint is that incoming
1884  * connections should be tied to the squeue attached to interrupted
1885  * CPU for obvious locality reason so this leaves the listener to
1886  * be tied to the same squeue. Our only problem is that when listener
1887  * is binding, the CPU that will get interrupted by the NIC whose
1888  * IP address the listener is binding to is not even known. So
1889  * the code below allows us to change that binding at the time the
1890  * CPU is interrupted by virtue of incoming connection's squeue.
1891  *
1892  * This is usefull only in case of a listener bound to a specific IP
1893  * address. For other kind of listeners, they get bound the
1894  * very first time and there is no attempt to rebind them.
1895  */
1896 void
1897 tcp_input_listener_unbound(void *arg, mblk_t *mp, void *arg2,
1898     ip_recv_attr_t *ira)
1899 {
1900 	conn_t		*connp = (conn_t *)arg;
1901 	squeue_t	*sqp = (squeue_t *)arg2;
1902 	squeue_t	*new_sqp;
1903 	uint32_t	conn_flags;
1904 
1905 	/*
1906 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
1907 	 * or based on the ring (for packets from GLD). Otherwise it is
1908 	 * set based on lbolt i.e., a somewhat random number.
1909 	 */
1910 	ASSERT(ira->ira_sqp != NULL);
1911 	new_sqp = ira->ira_sqp;
1912 
1913 	if (connp->conn_fanout == NULL)
1914 		goto done;
1915 
1916 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
1917 		mutex_enter(&connp->conn_fanout->connf_lock);
1918 		mutex_enter(&connp->conn_lock);
1919 		/*
1920 		 * No one from read or write side can access us now
1921 		 * except for already queued packets on this squeue.
1922 		 * But since we haven't changed the squeue yet, they
1923 		 * can't execute. If they are processed after we have
1924 		 * changed the squeue, they are sent back to the
1925 		 * correct squeue down below.
1926 		 * But a listner close can race with processing of
1927 		 * incoming SYN. If incoming SYN processing changes
1928 		 * the squeue then the listener close which is waiting
1929 		 * to enter the squeue would operate on the wrong
1930 		 * squeue. Hence we don't change the squeue here unless
1931 		 * the refcount is exactly the minimum refcount. The
1932 		 * minimum refcount of 4 is counted as - 1 each for
1933 		 * TCP and IP, 1 for being in the classifier hash, and
1934 		 * 1 for the mblk being processed.
1935 		 */
1936 
1937 		if (connp->conn_ref != 4 ||
1938 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
1939 			mutex_exit(&connp->conn_lock);
1940 			mutex_exit(&connp->conn_fanout->connf_lock);
1941 			goto done;
1942 		}
1943 		if (connp->conn_sqp != new_sqp) {
1944 			while (connp->conn_sqp != new_sqp)
1945 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
1946 			/* No special MT issues for outbound ixa_sqp hint */
1947 			connp->conn_ixa->ixa_sqp = new_sqp;
1948 		}
1949 
1950 		do {
1951 			conn_flags = connp->conn_flags;
1952 			conn_flags |= IPCL_FULLY_BOUND;
1953 			(void) cas32(&connp->conn_flags, connp->conn_flags,
1954 			    conn_flags);
1955 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
1956 
1957 		mutex_exit(&connp->conn_fanout->connf_lock);
1958 		mutex_exit(&connp->conn_lock);
1959 
1960 		/*
1961 		 * Assume we have picked a good squeue for the listener. Make
1962 		 * subsequent SYNs not try to change the squeue.
1963 		 */
1964 		connp->conn_recv = tcp_input_listener;
1965 	}
1966 
1967 done:
1968 	if (connp->conn_sqp != sqp) {
1969 		CONN_INC_REF(connp);
1970 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
1971 		    ira, SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
1972 	} else {
1973 		tcp_input_listener(connp, mp, sqp, ira);
1974 	}
1975 }
1976 
1977 /*
1978  * Send up all messages queued on tcp_rcv_list.
1979  */
1980 uint_t
1981 tcp_rcv_drain(tcp_t *tcp)
1982 {
1983 	mblk_t *mp;
1984 	uint_t ret = 0;
1985 #ifdef DEBUG
1986 	uint_t cnt = 0;
1987 #endif
1988 	queue_t	*q = tcp->tcp_connp->conn_rq;
1989 
1990 	/* Can't drain on an eager connection */
1991 	if (tcp->tcp_listener != NULL)
1992 		return (ret);
1993 
1994 	/* Can't be a non-STREAMS connection */
1995 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1996 
1997 	/* No need for the push timer now. */
1998 	if (tcp->tcp_push_tid != 0) {
1999 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
2000 		tcp->tcp_push_tid = 0;
2001 	}
2002 
2003 	/*
2004 	 * Handle two cases here: we are currently fused or we were
2005 	 * previously fused and have some urgent data to be delivered
2006 	 * upstream.  The latter happens because we either ran out of
2007 	 * memory or were detached and therefore sending the SIGURG was
2008 	 * deferred until this point.  In either case we pass control
2009 	 * over to tcp_fuse_rcv_drain() since it may need to complete
2010 	 * some work.
2011 	 */
2012 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
2013 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
2014 		    tcp->tcp_fused_sigurg_mp != NULL);
2015 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
2016 		    &tcp->tcp_fused_sigurg_mp))
2017 			return (ret);
2018 	}
2019 
2020 	while ((mp = tcp->tcp_rcv_list) != NULL) {
2021 		tcp->tcp_rcv_list = mp->b_next;
2022 		mp->b_next = NULL;
2023 #ifdef DEBUG
2024 		cnt += msgdsize(mp);
2025 #endif
2026 		/* Does this need SSL processing first? */
2027 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
2028 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
2029 			    mblk_t *, mp);
2030 			tcp_kssl_input(tcp, mp, NULL);
2031 			continue;
2032 		}
2033 		putnext(q, mp);
2034 	}
2035 #ifdef DEBUG
2036 	ASSERT(cnt == tcp->tcp_rcv_cnt);
2037 #endif
2038 	tcp->tcp_rcv_last_head = NULL;
2039 	tcp->tcp_rcv_last_tail = NULL;
2040 	tcp->tcp_rcv_cnt = 0;
2041 
2042 	if (canputnext(q))
2043 		return (tcp_rwnd_reopen(tcp));
2044 
2045 	return (ret);
2046 }
2047 
2048 /*
2049  * Queue data on tcp_rcv_list which is a b_next chain.
2050  * tcp_rcv_last_head/tail is the last element of this chain.
2051  * Each element of the chain is a b_cont chain.
2052  *
2053  * M_DATA messages are added to the current element.
2054  * Other messages are added as new (b_next) elements.
2055  */
2056 void
2057 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
2058 {
2059 	ASSERT(seg_len == msgdsize(mp));
2060 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
2061 
2062 	if (is_system_labeled()) {
2063 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
2064 		/*
2065 		 * Provide for protocols above TCP such as RPC. NOPID leaves
2066 		 * db_cpid unchanged.
2067 		 * The cred could have already been set.
2068 		 */
2069 		if (cr != NULL)
2070 			mblk_setcred(mp, cr, NOPID);
2071 	}
2072 
2073 	if (tcp->tcp_rcv_list == NULL) {
2074 		ASSERT(tcp->tcp_rcv_last_head == NULL);
2075 		tcp->tcp_rcv_list = mp;
2076 		tcp->tcp_rcv_last_head = mp;
2077 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
2078 		tcp->tcp_rcv_last_tail->b_cont = mp;
2079 	} else {
2080 		tcp->tcp_rcv_last_head->b_next = mp;
2081 		tcp->tcp_rcv_last_head = mp;
2082 	}
2083 
2084 	while (mp->b_cont)
2085 		mp = mp->b_cont;
2086 
2087 	tcp->tcp_rcv_last_tail = mp;
2088 	tcp->tcp_rcv_cnt += seg_len;
2089 	tcp->tcp_rwnd -= seg_len;
2090 }
2091 
2092 /* Generate an ACK-only (no data) segment for a TCP endpoint */
2093 mblk_t *
2094 tcp_ack_mp(tcp_t *tcp)
2095 {
2096 	uint32_t	seq_no;
2097 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2098 	conn_t		*connp = tcp->tcp_connp;
2099 
2100 	/*
2101 	 * There are a few cases to be considered while setting the sequence no.
2102 	 * Essentially, we can come here while processing an unacceptable pkt
2103 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
2104 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
2105 	 * If we are here for a zero window probe, stick with suna. In all
2106 	 * other cases, we check if suna + swnd encompasses snxt and set
2107 	 * the sequence number to snxt, if so. If snxt falls outside the
2108 	 * window (the receiver probably shrunk its window), we will go with
2109 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
2110 	 * receiver.
2111 	 */
2112 	if (tcp->tcp_zero_win_probe) {
2113 		seq_no = tcp->tcp_suna;
2114 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
2115 		ASSERT(tcp->tcp_swnd == 0);
2116 		seq_no = tcp->tcp_snxt;
2117 	} else {
2118 		seq_no = SEQ_GT(tcp->tcp_snxt,
2119 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
2120 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
2121 	}
2122 
2123 	if (tcp->tcp_valid_bits) {
2124 		/*
2125 		 * For the complex case where we have to send some
2126 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
2127 		 */
2128 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
2129 		    NULL, B_FALSE));
2130 	} else {
2131 		/* Generate a simple ACK */
2132 		int	data_length;
2133 		uchar_t	*rptr;
2134 		tcpha_t	*tcpha;
2135 		mblk_t	*mp1;
2136 		int32_t	total_hdr_len;
2137 		int32_t	tcp_hdr_len;
2138 		int32_t	num_sack_blk = 0;
2139 		int32_t sack_opt_len;
2140 		ip_xmit_attr_t *ixa = connp->conn_ixa;
2141 
2142 		/*
2143 		 * Allocate space for TCP + IP headers
2144 		 * and link-level header
2145 		 */
2146 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
2147 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
2148 			    tcp->tcp_num_sack_blk);
2149 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
2150 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
2151 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
2152 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
2153 		} else {
2154 			total_hdr_len = connp->conn_ht_iphc_len;
2155 			tcp_hdr_len = connp->conn_ht_ulp_len;
2156 		}
2157 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
2158 		if (!mp1)
2159 			return (NULL);
2160 
2161 		/* Update the latest receive window size in TCP header. */
2162 		tcp->tcp_tcpha->tha_win =
2163 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
2164 		/* copy in prototype TCP + IP header */
2165 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
2166 		mp1->b_rptr = rptr;
2167 		mp1->b_wptr = rptr + total_hdr_len;
2168 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
2169 
2170 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
2171 
2172 		/* Set the TCP sequence number. */
2173 		tcpha->tha_seq = htonl(seq_no);
2174 
2175 		/* Set up the TCP flag field. */
2176 		tcpha->tha_flags = (uchar_t)TH_ACK;
2177 		if (tcp->tcp_ecn_echo_on)
2178 			tcpha->tha_flags |= TH_ECE;
2179 
2180 		tcp->tcp_rack = tcp->tcp_rnxt;
2181 		tcp->tcp_rack_cnt = 0;
2182 
2183 		/* fill in timestamp option if in use */
2184 		if (tcp->tcp_snd_ts_ok) {
2185 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
2186 
2187 			U32_TO_BE32(llbolt,
2188 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
2189 			U32_TO_BE32(tcp->tcp_ts_recent,
2190 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
2191 		}
2192 
2193 		/* Fill in SACK options */
2194 		if (num_sack_blk > 0) {
2195 			uchar_t *wptr = (uchar_t *)tcpha +
2196 			    connp->conn_ht_ulp_len;
2197 			sack_blk_t *tmp;
2198 			int32_t	i;
2199 
2200 			wptr[0] = TCPOPT_NOP;
2201 			wptr[1] = TCPOPT_NOP;
2202 			wptr[2] = TCPOPT_SACK;
2203 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
2204 			    sizeof (sack_blk_t);
2205 			wptr += TCPOPT_REAL_SACK_LEN;
2206 
2207 			tmp = tcp->tcp_sack_list;
2208 			for (i = 0; i < num_sack_blk; i++) {
2209 				U32_TO_BE32(tmp[i].begin, wptr);
2210 				wptr += sizeof (tcp_seq);
2211 				U32_TO_BE32(tmp[i].end, wptr);
2212 				wptr += sizeof (tcp_seq);
2213 			}
2214 			tcpha->tha_offset_and_reserved +=
2215 			    ((num_sack_blk * 2 + 1) << 4);
2216 		}
2217 
2218 		ixa->ixa_pktlen = total_hdr_len;
2219 
2220 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
2221 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
2222 		} else {
2223 			ip6_t *ip6 = (ip6_t *)rptr;
2224 
2225 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
2226 		}
2227 
2228 		/*
2229 		 * Prime pump for checksum calculation in IP.  Include the
2230 		 * adjustment for a source route if any.
2231 		 */
2232 		data_length = tcp_hdr_len + connp->conn_sum;
2233 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
2234 		tcpha->tha_sum = htons(data_length);
2235 
2236 		if (tcp->tcp_ip_forward_progress) {
2237 			tcp->tcp_ip_forward_progress = B_FALSE;
2238 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
2239 		} else {
2240 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
2241 		}
2242 		return (mp1);
2243 	}
2244 }
2245 
2246 /*
2247  * Handle M_DATA messages from IP. Its called directly from IP via
2248  * squeue for received IP packets.
2249  *
2250  * The first argument is always the connp/tcp to which the mp belongs.
2251  * There are no exceptions to this rule. The caller has already put
2252  * a reference on this connp/tcp and once tcp_input_data() returns,
2253  * the squeue will do the refrele.
2254  *
2255  * The TH_SYN for the listener directly go to tcp_input_listener via
2256  * squeue. ICMP errors go directly to tcp_icmp_input().
2257  *
2258  * sqp: NULL = recursive, sqp != NULL means called from squeue
2259  */
2260 void
2261 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
2262 {
2263 	int32_t		bytes_acked;
2264 	int32_t		gap;
2265 	mblk_t		*mp1;
2266 	uint_t		flags;
2267 	uint32_t	new_swnd = 0;
2268 	uchar_t		*iphdr;
2269 	uchar_t		*rptr;
2270 	int32_t		rgap;
2271 	uint32_t	seg_ack;
2272 	int		seg_len;
2273 	uint_t		ip_hdr_len;
2274 	uint32_t	seg_seq;
2275 	tcpha_t		*tcpha;
2276 	int		urp;
2277 	tcp_opt_t	tcpopt;
2278 	ip_pkt_t	ipp;
2279 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
2280 	uint32_t	cwnd;
2281 	uint32_t	add;
2282 	int		npkt;
2283 	int		mss;
2284 	conn_t		*connp = (conn_t *)arg;
2285 	squeue_t	*sqp = (squeue_t *)arg2;
2286 	tcp_t		*tcp = connp->conn_tcp;
2287 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2288 
2289 	/*
2290 	 * RST from fused tcp loopback peer should trigger an unfuse.
2291 	 */
2292 	if (tcp->tcp_fused) {
2293 		TCP_STAT(tcps, tcp_fusion_aborted);
2294 		tcp_unfuse(tcp);
2295 	}
2296 
2297 	iphdr = mp->b_rptr;
2298 	rptr = mp->b_rptr;
2299 	ASSERT(OK_32PTR(rptr));
2300 
2301 	ip_hdr_len = ira->ira_ip_hdr_length;
2302 	if (connp->conn_recv_ancillary.crb_all != 0) {
2303 		/*
2304 		 * Record packet information in the ip_pkt_t
2305 		 */
2306 		ipp.ipp_fields = 0;
2307 		if (ira->ira_flags & IRAF_IS_IPV4) {
2308 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
2309 			    B_FALSE);
2310 		} else {
2311 			uint8_t nexthdrp;
2312 
2313 			/*
2314 			 * IPv6 packets can only be received by applications
2315 			 * that are prepared to receive IPv6 addresses.
2316 			 * The IP fanout must ensure this.
2317 			 */
2318 			ASSERT(connp->conn_family == AF_INET6);
2319 
2320 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
2321 			    &nexthdrp);
2322 			ASSERT(nexthdrp == IPPROTO_TCP);
2323 
2324 			/* Could have caused a pullup? */
2325 			iphdr = mp->b_rptr;
2326 			rptr = mp->b_rptr;
2327 		}
2328 	}
2329 	ASSERT(DB_TYPE(mp) == M_DATA);
2330 	ASSERT(mp->b_next == NULL);
2331 
2332 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
2333 	seg_seq = ntohl(tcpha->tha_seq);
2334 	seg_ack = ntohl(tcpha->tha_ack);
2335 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
2336 	seg_len = (int)(mp->b_wptr - rptr) -
2337 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
2338 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
2339 		do {
2340 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
2341 			    (uintptr_t)INT_MAX);
2342 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
2343 		} while ((mp1 = mp1->b_cont) != NULL &&
2344 		    mp1->b_datap->db_type == M_DATA);
2345 	}
2346 
2347 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
2348 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
2349 		    seg_len, tcpha, ira);
2350 		return;
2351 	}
2352 
2353 	if (sqp != NULL) {
2354 		/*
2355 		 * This is the correct place to update tcp_last_recv_time. Note
2356 		 * that it is also updated for tcp structure that belongs to
2357 		 * global and listener queues which do not really need updating.
2358 		 * But that should not cause any harm.  And it is updated for
2359 		 * all kinds of incoming segments, not only for data segments.
2360 		 */
2361 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
2362 	}
2363 
2364 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
2365 
2366 	BUMP_LOCAL(tcp->tcp_ibsegs);
2367 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
2368 
2369 	if ((flags & TH_URG) && sqp != NULL) {
2370 		/*
2371 		 * TCP can't handle urgent pointers that arrive before
2372 		 * the connection has been accept()ed since it can't
2373 		 * buffer OOB data.  Discard segment if this happens.
2374 		 *
2375 		 * We can't just rely on a non-null tcp_listener to indicate
2376 		 * that the accept() has completed since unlinking of the
2377 		 * eager and completion of the accept are not atomic.
2378 		 * tcp_detached, when it is not set (B_FALSE) indicates
2379 		 * that the accept() has completed.
2380 		 *
2381 		 * Nor can it reassemble urgent pointers, so discard
2382 		 * if it's not the next segment expected.
2383 		 *
2384 		 * Otherwise, collapse chain into one mblk (discard if
2385 		 * that fails).  This makes sure the headers, retransmitted
2386 		 * data, and new data all are in the same mblk.
2387 		 */
2388 		ASSERT(mp != NULL);
2389 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
2390 			freemsg(mp);
2391 			return;
2392 		}
2393 		/* Update pointers into message */
2394 		iphdr = rptr = mp->b_rptr;
2395 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
2396 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
2397 			/*
2398 			 * Since we can't handle any data with this urgent
2399 			 * pointer that is out of sequence, we expunge
2400 			 * the data.  This allows us to still register
2401 			 * the urgent mark and generate the M_PCSIG,
2402 			 * which we can do.
2403 			 */
2404 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
2405 			seg_len = 0;
2406 		}
2407 	}
2408 
2409 	switch (tcp->tcp_state) {
2410 	case TCPS_SYN_SENT:
2411 		if (connp->conn_final_sqp == NULL &&
2412 		    tcp_outbound_squeue_switch && sqp != NULL) {
2413 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
2414 			connp->conn_final_sqp = sqp;
2415 			if (connp->conn_final_sqp != connp->conn_sqp) {
2416 				DTRACE_PROBE1(conn__final__sqp__switch,
2417 				    conn_t *, connp);
2418 				CONN_INC_REF(connp);
2419 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
2420 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2421 				    tcp_input_data, connp, ira, ip_squeue_flag,
2422 				    SQTAG_CONNECT_FINISH);
2423 				return;
2424 			}
2425 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
2426 		}
2427 		if (flags & TH_ACK) {
2428 			/*
2429 			 * Note that our stack cannot send data before a
2430 			 * connection is established, therefore the
2431 			 * following check is valid.  Otherwise, it has
2432 			 * to be changed.
2433 			 */
2434 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
2435 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
2436 				freemsg(mp);
2437 				if (flags & TH_RST)
2438 					return;
2439 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
2440 				    tcp, seg_ack, 0, TH_RST);
2441 				return;
2442 			}
2443 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
2444 		}
2445 		if (flags & TH_RST) {
2446 			freemsg(mp);
2447 			if (flags & TH_ACK)
2448 				(void) tcp_clean_death(tcp, ECONNREFUSED);
2449 			return;
2450 		}
2451 		if (!(flags & TH_SYN)) {
2452 			freemsg(mp);
2453 			return;
2454 		}
2455 
2456 		/* Process all TCP options. */
2457 		tcp_process_options(tcp, tcpha);
2458 		/*
2459 		 * The following changes our rwnd to be a multiple of the
2460 		 * MIN(peer MSS, our MSS) for performance reason.
2461 		 */
2462 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
2463 		    tcp->tcp_mss));
2464 
2465 		/* Is the other end ECN capable? */
2466 		if (tcp->tcp_ecn_ok) {
2467 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
2468 				tcp->tcp_ecn_ok = B_FALSE;
2469 			}
2470 		}
2471 		/*
2472 		 * Clear ECN flags because it may interfere with later
2473 		 * processing.
2474 		 */
2475 		flags &= ~(TH_ECE|TH_CWR);
2476 
2477 		tcp->tcp_irs = seg_seq;
2478 		tcp->tcp_rack = seg_seq;
2479 		tcp->tcp_rnxt = seg_seq + 1;
2480 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
2481 		if (!TCP_IS_DETACHED(tcp)) {
2482 			/* Allocate room for SACK options if needed. */
2483 			connp->conn_wroff = connp->conn_ht_iphc_len;
2484 			if (tcp->tcp_snd_sack_ok)
2485 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
2486 			if (!tcp->tcp_loopback)
2487 				connp->conn_wroff += tcps->tcps_wroff_xtra;
2488 
2489 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
2490 			    connp->conn_wroff);
2491 		}
2492 		if (flags & TH_ACK) {
2493 			/*
2494 			 * If we can't get the confirmation upstream, pretend
2495 			 * we didn't even see this one.
2496 			 *
2497 			 * XXX: how can we pretend we didn't see it if we
2498 			 * have updated rnxt et. al.
2499 			 *
2500 			 * For loopback we defer sending up the T_CONN_CON
2501 			 * until after some checks below.
2502 			 */
2503 			mp1 = NULL;
2504 			/*
2505 			 * tcp_sendmsg() checks tcp_state without entering
2506 			 * the squeue so tcp_state should be updated before
2507 			 * sending up connection confirmation
2508 			 */
2509 			tcp->tcp_state = TCPS_ESTABLISHED;
2510 			if (!tcp_conn_con(tcp, iphdr, mp,
2511 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
2512 				tcp->tcp_state = TCPS_SYN_SENT;
2513 				freemsg(mp);
2514 				return;
2515 			}
2516 			TCPS_CONN_INC(tcps);
2517 			/* SYN was acked - making progress */
2518 			tcp->tcp_ip_forward_progress = B_TRUE;
2519 
2520 			/* One for the SYN */
2521 			tcp->tcp_suna = tcp->tcp_iss + 1;
2522 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
2523 
2524 			/*
2525 			 * If SYN was retransmitted, need to reset all
2526 			 * retransmission info.  This is because this
2527 			 * segment will be treated as a dup ACK.
2528 			 */
2529 			if (tcp->tcp_rexmit) {
2530 				tcp->tcp_rexmit = B_FALSE;
2531 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
2532 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
2533 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
2534 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
2535 				tcp->tcp_ms_we_have_waited = 0;
2536 
2537 				/*
2538 				 * Set tcp_cwnd back to 1 MSS, per
2539 				 * recommendation from
2540 				 * draft-floyd-incr-init-win-01.txt,
2541 				 * Increasing TCP's Initial Window.
2542 				 */
2543 				tcp->tcp_cwnd = tcp->tcp_mss;
2544 			}
2545 
2546 			tcp->tcp_swl1 = seg_seq;
2547 			tcp->tcp_swl2 = seg_ack;
2548 
2549 			new_swnd = ntohs(tcpha->tha_win);
2550 			tcp->tcp_swnd = new_swnd;
2551 			if (new_swnd > tcp->tcp_max_swnd)
2552 				tcp->tcp_max_swnd = new_swnd;
2553 
2554 			/*
2555 			 * Always send the three-way handshake ack immediately
2556 			 * in order to make the connection complete as soon as
2557 			 * possible on the accepting host.
2558 			 */
2559 			flags |= TH_ACK_NEEDED;
2560 
2561 			/*
2562 			 * Special case for loopback.  At this point we have
2563 			 * received SYN-ACK from the remote endpoint.  In
2564 			 * order to ensure that both endpoints reach the
2565 			 * fused state prior to any data exchange, the final
2566 			 * ACK needs to be sent before we indicate T_CONN_CON
2567 			 * to the module upstream.
2568 			 */
2569 			if (tcp->tcp_loopback) {
2570 				mblk_t *ack_mp;
2571 
2572 				ASSERT(!tcp->tcp_unfusable);
2573 				ASSERT(mp1 != NULL);
2574 				/*
2575 				 * For loopback, we always get a pure SYN-ACK
2576 				 * and only need to send back the final ACK
2577 				 * with no data (this is because the other
2578 				 * tcp is ours and we don't do T/TCP).  This
2579 				 * final ACK triggers the passive side to
2580 				 * perform fusion in ESTABLISHED state.
2581 				 */
2582 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
2583 					if (tcp->tcp_ack_tid != 0) {
2584 						(void) TCP_TIMER_CANCEL(tcp,
2585 						    tcp->tcp_ack_tid);
2586 						tcp->tcp_ack_tid = 0;
2587 					}
2588 					tcp_send_data(tcp, ack_mp);
2589 					BUMP_LOCAL(tcp->tcp_obsegs);
2590 					TCPS_BUMP_MIB(tcps, tcpOutAck);
2591 
2592 					if (!IPCL_IS_NONSTR(connp)) {
2593 						/* Send up T_CONN_CON */
2594 						if (ira->ira_cred != NULL) {
2595 							mblk_setcred(mp1,
2596 							    ira->ira_cred,
2597 							    ira->ira_cpid);
2598 						}
2599 						putnext(connp->conn_rq, mp1);
2600 					} else {
2601 						(*connp->conn_upcalls->
2602 						    su_connected)
2603 						    (connp->conn_upper_handle,
2604 						    tcp->tcp_connid,
2605 						    ira->ira_cred,
2606 						    ira->ira_cpid);
2607 						freemsg(mp1);
2608 					}
2609 
2610 					freemsg(mp);
2611 					return;
2612 				}
2613 				/*
2614 				 * Forget fusion; we need to handle more
2615 				 * complex cases below.  Send the deferred
2616 				 * T_CONN_CON message upstream and proceed
2617 				 * as usual.  Mark this tcp as not capable
2618 				 * of fusion.
2619 				 */
2620 				TCP_STAT(tcps, tcp_fusion_unfusable);
2621 				tcp->tcp_unfusable = B_TRUE;
2622 				if (!IPCL_IS_NONSTR(connp)) {
2623 					if (ira->ira_cred != NULL) {
2624 						mblk_setcred(mp1, ira->ira_cred,
2625 						    ira->ira_cpid);
2626 					}
2627 					putnext(connp->conn_rq, mp1);
2628 				} else {
2629 					(*connp->conn_upcalls->su_connected)
2630 					    (connp->conn_upper_handle,
2631 					    tcp->tcp_connid, ira->ira_cred,
2632 					    ira->ira_cpid);
2633 					freemsg(mp1);
2634 				}
2635 			}
2636 
2637 			/*
2638 			 * Check to see if there is data to be sent.  If
2639 			 * yes, set the transmit flag.  Then check to see
2640 			 * if received data processing needs to be done.
2641 			 * If not, go straight to xmit_check.  This short
2642 			 * cut is OK as we don't support T/TCP.
2643 			 */
2644 			if (tcp->tcp_unsent)
2645 				flags |= TH_XMIT_NEEDED;
2646 
2647 			if (seg_len == 0 && !(flags & TH_URG)) {
2648 				freemsg(mp);
2649 				goto xmit_check;
2650 			}
2651 
2652 			flags &= ~TH_SYN;
2653 			seg_seq++;
2654 			break;
2655 		}
2656 		tcp->tcp_state = TCPS_SYN_RCVD;
2657 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
2658 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
2659 		if (mp1 != NULL) {
2660 			tcp_send_data(tcp, mp1);
2661 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
2662 		}
2663 		freemsg(mp);
2664 		return;
2665 	case TCPS_SYN_RCVD:
2666 		if (flags & TH_ACK) {
2667 			/*
2668 			 * In this state, a SYN|ACK packet is either bogus
2669 			 * because the other side must be ACKing our SYN which
2670 			 * indicates it has seen the ACK for their SYN and
2671 			 * shouldn't retransmit it or we're crossing SYNs
2672 			 * on active open.
2673 			 */
2674 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
2675 				freemsg(mp);
2676 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
2677 				    tcp, seg_ack, 0, TH_RST);
2678 				return;
2679 			}
2680 			/*
2681 			 * NOTE: RFC 793 pg. 72 says this should be
2682 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
2683 			 * but that would mean we have an ack that ignored
2684 			 * our SYN.
2685 			 */
2686 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
2687 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
2688 				freemsg(mp);
2689 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
2690 				    tcp, seg_ack, 0, TH_RST);
2691 				return;
2692 			}
2693 			/*
2694 			 * No sane TCP stack will send such a small window
2695 			 * without receiving any data.  Just drop this invalid
2696 			 * ACK.  We also shorten the abort timeout in case
2697 			 * this is an attack.
2698 			 */
2699 			if ((ntohs(tcpha->tha_win) << tcp->tcp_snd_ws) <
2700 			    (tcp->tcp_mss >> tcp_init_wnd_shft)) {
2701 				freemsg(mp);
2702 				TCP_STAT(tcps, tcp_zwin_ack_syn);
2703 				tcp->tcp_second_ctimer_threshold =
2704 				    tcp_early_abort * SECONDS;
2705 				return;
2706 			}
2707 		}
2708 		break;
2709 	case TCPS_LISTEN:
2710 		/*
2711 		 * Only a TLI listener can come through this path when a
2712 		 * acceptor is going back to be a listener and a packet
2713 		 * for the acceptor hits the classifier. For a socket
2714 		 * listener, this can never happen because a listener
2715 		 * can never accept connection on itself and hence a
2716 		 * socket acceptor can not go back to being a listener.
2717 		 */
2718 		ASSERT(!TCP_IS_SOCKET(tcp));
2719 		/*FALLTHRU*/
2720 	case TCPS_CLOSED:
2721 	case TCPS_BOUND: {
2722 		conn_t	*new_connp;
2723 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
2724 
2725 		/*
2726 		 * Don't accept any input on a closed tcp as this TCP logically
2727 		 * does not exist on the system. Don't proceed further with
2728 		 * this TCP. For instance, this packet could trigger another
2729 		 * close of this tcp which would be disastrous for tcp_refcnt.
2730 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
2731 		 * be called at most once on a TCP. In this case we need to
2732 		 * refeed the packet into the classifier and figure out where
2733 		 * the packet should go.
2734 		 */
2735 		new_connp = ipcl_classify(mp, ira, ipst);
2736 		if (new_connp != NULL) {
2737 			/* Drops ref on new_connp */
2738 			tcp_reinput(new_connp, mp, ira, ipst);
2739 			return;
2740 		}
2741 		/* We failed to classify. For now just drop the packet */
2742 		freemsg(mp);
2743 		return;
2744 	}
2745 	case TCPS_IDLE:
2746 		/*
2747 		 * Handle the case where the tcp_clean_death() has happened
2748 		 * on a connection (application hasn't closed yet) but a packet
2749 		 * was already queued on squeue before tcp_clean_death()
2750 		 * was processed. Calling tcp_clean_death() twice on same
2751 		 * connection can result in weird behaviour.
2752 		 */
2753 		freemsg(mp);
2754 		return;
2755 	default:
2756 		break;
2757 	}
2758 
2759 	/*
2760 	 * Already on the correct queue/perimeter.
2761 	 * If this is a detached connection and not an eager
2762 	 * connection hanging off a listener then new data
2763 	 * (past the FIN) will cause a reset.
2764 	 * We do a special check here where it
2765 	 * is out of the main line, rather than check
2766 	 * if we are detached every time we see new
2767 	 * data down below.
2768 	 */
2769 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
2770 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
2771 		TCPS_BUMP_MIB(tcps, tcpInClosed);
2772 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
2773 
2774 		freemsg(mp);
2775 		/*
2776 		 * This could be an SSL closure alert. We're detached so just
2777 		 * acknowledge it this last time.
2778 		 */
2779 		if (tcp->tcp_kssl_ctx != NULL) {
2780 			kssl_release_ctx(tcp->tcp_kssl_ctx);
2781 			tcp->tcp_kssl_ctx = NULL;
2782 
2783 			tcp->tcp_rnxt += seg_len;
2784 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
2785 			flags |= TH_ACK_NEEDED;
2786 			goto ack_check;
2787 		}
2788 
2789 		tcp_xmit_ctl("new data when detached", tcp,
2790 		    tcp->tcp_snxt, 0, TH_RST);
2791 		(void) tcp_clean_death(tcp, EPROTO);
2792 		return;
2793 	}
2794 
2795 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
2796 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
2797 	new_swnd = ntohs(tcpha->tha_win) <<
2798 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
2799 
2800 	if (tcp->tcp_snd_ts_ok) {
2801 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
2802 			/*
2803 			 * This segment is not acceptable.
2804 			 * Drop it and send back an ACK.
2805 			 */
2806 			freemsg(mp);
2807 			flags |= TH_ACK_NEEDED;
2808 			goto ack_check;
2809 		}
2810 	} else if (tcp->tcp_snd_sack_ok) {
2811 		tcpopt.tcp = tcp;
2812 		/*
2813 		 * SACK info in already updated in tcp_parse_options.  Ignore
2814 		 * all other TCP options...
2815 		 */
2816 		(void) tcp_parse_options(tcpha, &tcpopt);
2817 	}
2818 try_again:;
2819 	mss = tcp->tcp_mss;
2820 	gap = seg_seq - tcp->tcp_rnxt;
2821 	rgap = tcp->tcp_rwnd - (gap + seg_len);
2822 	/*
2823 	 * gap is the amount of sequence space between what we expect to see
2824 	 * and what we got for seg_seq.  A positive value for gap means
2825 	 * something got lost.  A negative value means we got some old stuff.
2826 	 */
2827 	if (gap < 0) {
2828 		/* Old stuff present.  Is the SYN in there? */
2829 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
2830 		    (seg_len != 0)) {
2831 			flags &= ~TH_SYN;
2832 			seg_seq++;
2833 			urp--;
2834 			/* Recompute the gaps after noting the SYN. */
2835 			goto try_again;
2836 		}
2837 		TCPS_BUMP_MIB(tcps, tcpInDataDupSegs);
2838 		TCPS_UPDATE_MIB(tcps, tcpInDataDupBytes,
2839 		    (seg_len > -gap ? -gap : seg_len));
2840 		/* Remove the old stuff from seg_len. */
2841 		seg_len += gap;
2842 		/*
2843 		 * Anything left?
2844 		 * Make sure to check for unack'd FIN when rest of data
2845 		 * has been previously ack'd.
2846 		 */
2847 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
2848 			/*
2849 			 * Resets are only valid if they lie within our offered
2850 			 * window.  If the RST bit is set, we just ignore this
2851 			 * segment.
2852 			 */
2853 			if (flags & TH_RST) {
2854 				freemsg(mp);
2855 				return;
2856 			}
2857 
2858 			/*
2859 			 * The arriving of dup data packets indicate that we
2860 			 * may have postponed an ack for too long, or the other
2861 			 * side's RTT estimate is out of shape. Start acking
2862 			 * more often.
2863 			 */
2864 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
2865 			    tcp->tcp_rack_cnt >= 1 &&
2866 			    tcp->tcp_rack_abs_max > 2) {
2867 				tcp->tcp_rack_abs_max--;
2868 			}
2869 			tcp->tcp_rack_cur_max = 1;
2870 
2871 			/*
2872 			 * This segment is "unacceptable".  None of its
2873 			 * sequence space lies within our advertized window.
2874 			 *
2875 			 * Adjust seg_len to the original value for tracing.
2876 			 */
2877 			seg_len -= gap;
2878 			if (connp->conn_debug) {
2879 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
2880 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
2881 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
2882 				    "seg_len %d, rnxt %u, snxt %u, %s",
2883 				    gap, rgap, flags, seg_seq, seg_ack,
2884 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
2885 				    tcp_display(tcp, NULL,
2886 				    DISP_ADDR_AND_PORT));
2887 			}
2888 
2889 			/*
2890 			 * Arrange to send an ACK in response to the
2891 			 * unacceptable segment per RFC 793 page 69. There
2892 			 * is only one small difference between ours and the
2893 			 * acceptability test in the RFC - we accept ACK-only
2894 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
2895 			 * will be generated.
2896 			 *
2897 			 * Note that we have to ACK an ACK-only packet at least
2898 			 * for stacks that send 0-length keep-alives with
2899 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
2900 			 * section 4.2.3.6. As long as we don't ever generate
2901 			 * an unacceptable packet in response to an incoming
2902 			 * packet that is unacceptable, it should not cause
2903 			 * "ACK wars".
2904 			 */
2905 			flags |=  TH_ACK_NEEDED;
2906 
2907 			/*
2908 			 * Continue processing this segment in order to use the
2909 			 * ACK information it contains, but skip all other
2910 			 * sequence-number processing.	Processing the ACK
2911 			 * information is necessary in order to
2912 			 * re-synchronize connections that may have lost
2913 			 * synchronization.
2914 			 *
2915 			 * We clear seg_len and flag fields related to
2916 			 * sequence number processing as they are not
2917 			 * to be trusted for an unacceptable segment.
2918 			 */
2919 			seg_len = 0;
2920 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
2921 			goto process_ack;
2922 		}
2923 
2924 		/* Fix seg_seq, and chew the gap off the front. */
2925 		seg_seq = tcp->tcp_rnxt;
2926 		urp += gap;
2927 		do {
2928 			mblk_t	*mp2;
2929 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
2930 			    (uintptr_t)UINT_MAX);
2931 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
2932 			if (gap > 0) {
2933 				mp->b_rptr = mp->b_wptr - gap;
2934 				break;
2935 			}
2936 			mp2 = mp;
2937 			mp = mp->b_cont;
2938 			freeb(mp2);
2939 		} while (gap < 0);
2940 		/*
2941 		 * If the urgent data has already been acknowledged, we
2942 		 * should ignore TH_URG below
2943 		 */
2944 		if (urp < 0)
2945 			flags &= ~TH_URG;
2946 	}
2947 	/*
2948 	 * rgap is the amount of stuff received out of window.  A negative
2949 	 * value is the amount out of window.
2950 	 */
2951 	if (rgap < 0) {
2952 		mblk_t	*mp2;
2953 
2954 		if (tcp->tcp_rwnd == 0) {
2955 			TCPS_BUMP_MIB(tcps, tcpInWinProbe);
2956 		} else {
2957 			TCPS_BUMP_MIB(tcps, tcpInDataPastWinSegs);
2958 			TCPS_UPDATE_MIB(tcps, tcpInDataPastWinBytes, -rgap);
2959 		}
2960 
2961 		/*
2962 		 * seg_len does not include the FIN, so if more than
2963 		 * just the FIN is out of window, we act like we don't
2964 		 * see it.  (If just the FIN is out of window, rgap
2965 		 * will be zero and we will go ahead and acknowledge
2966 		 * the FIN.)
2967 		 */
2968 		flags &= ~TH_FIN;
2969 
2970 		/* Fix seg_len and make sure there is something left. */
2971 		seg_len += rgap;
2972 		if (seg_len <= 0) {
2973 			/*
2974 			 * Resets are only valid if they lie within our offered
2975 			 * window.  If the RST bit is set, we just ignore this
2976 			 * segment.
2977 			 */
2978 			if (flags & TH_RST) {
2979 				freemsg(mp);
2980 				return;
2981 			}
2982 
2983 			/* Per RFC 793, we need to send back an ACK. */
2984 			flags |= TH_ACK_NEEDED;
2985 
2986 			/*
2987 			 * Send SIGURG as soon as possible i.e. even
2988 			 * if the TH_URG was delivered in a window probe
2989 			 * packet (which will be unacceptable).
2990 			 *
2991 			 * We generate a signal if none has been generated
2992 			 * for this connection or if this is a new urgent
2993 			 * byte. Also send a zero-length "unmarked" message
2994 			 * to inform SIOCATMARK that this is not the mark.
2995 			 *
2996 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
2997 			 * is sent up. This plus the check for old data
2998 			 * (gap >= 0) handles the wraparound of the sequence
2999 			 * number space without having to always track the
3000 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
3001 			 * this max in its rcv_up variable).
3002 			 *
3003 			 * This prevents duplicate SIGURGS due to a "late"
3004 			 * zero-window probe when the T_EXDATA_IND has already
3005 			 * been sent up.
3006 			 */
3007 			if ((flags & TH_URG) &&
3008 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
3009 			    tcp->tcp_urp_last))) {
3010 				if (IPCL_IS_NONSTR(connp)) {
3011 					if (!TCP_IS_DETACHED(tcp)) {
3012 						(*connp->conn_upcalls->
3013 						    su_signal_oob)
3014 						    (connp->conn_upper_handle,
3015 						    urp);
3016 					}
3017 				} else {
3018 					mp1 = allocb(0, BPRI_MED);
3019 					if (mp1 == NULL) {
3020 						freemsg(mp);
3021 						return;
3022 					}
3023 					if (!TCP_IS_DETACHED(tcp) &&
3024 					    !putnextctl1(connp->conn_rq,
3025 					    M_PCSIG, SIGURG)) {
3026 						/* Try again on the rexmit. */
3027 						freemsg(mp1);
3028 						freemsg(mp);
3029 						return;
3030 					}
3031 					/*
3032 					 * If the next byte would be the mark
3033 					 * then mark with MARKNEXT else mark
3034 					 * with NOTMARKNEXT.
3035 					 */
3036 					if (gap == 0 && urp == 0)
3037 						mp1->b_flag |= MSGMARKNEXT;
3038 					else
3039 						mp1->b_flag |= MSGNOTMARKNEXT;
3040 					freemsg(tcp->tcp_urp_mark_mp);
3041 					tcp->tcp_urp_mark_mp = mp1;
3042 					flags |= TH_SEND_URP_MARK;
3043 				}
3044 				tcp->tcp_urp_last_valid = B_TRUE;
3045 				tcp->tcp_urp_last = urp + seg_seq;
3046 			}
3047 			/*
3048 			 * If this is a zero window probe, continue to
3049 			 * process the ACK part.  But we need to set seg_len
3050 			 * to 0 to avoid data processing.  Otherwise just
3051 			 * drop the segment and send back an ACK.
3052 			 */
3053 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
3054 				flags &= ~(TH_SYN | TH_URG);
3055 				seg_len = 0;
3056 				goto process_ack;
3057 			} else {
3058 				freemsg(mp);
3059 				goto ack_check;
3060 			}
3061 		}
3062 		/* Pitch out of window stuff off the end. */
3063 		rgap = seg_len;
3064 		mp2 = mp;
3065 		do {
3066 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
3067 			    (uintptr_t)INT_MAX);
3068 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
3069 			if (rgap < 0) {
3070 				mp2->b_wptr += rgap;
3071 				if ((mp1 = mp2->b_cont) != NULL) {
3072 					mp2->b_cont = NULL;
3073 					freemsg(mp1);
3074 				}
3075 				break;
3076 			}
3077 		} while ((mp2 = mp2->b_cont) != NULL);
3078 	}
3079 ok:;
3080 	/*
3081 	 * TCP should check ECN info for segments inside the window only.
3082 	 * Therefore the check should be done here.
3083 	 */
3084 	if (tcp->tcp_ecn_ok) {
3085 		if (flags & TH_CWR) {
3086 			tcp->tcp_ecn_echo_on = B_FALSE;
3087 		}
3088 		/*
3089 		 * Note that both ECN_CE and CWR can be set in the
3090 		 * same segment.  In this case, we once again turn
3091 		 * on ECN_ECHO.
3092 		 */
3093 		if (connp->conn_ipversion == IPV4_VERSION) {
3094 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
3095 
3096 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
3097 				tcp->tcp_ecn_echo_on = B_TRUE;
3098 			}
3099 		} else {
3100 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
3101 
3102 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
3103 			    htonl(IPH_ECN_CE << 20)) {
3104 				tcp->tcp_ecn_echo_on = B_TRUE;
3105 			}
3106 		}
3107 	}
3108 
3109 	/*
3110 	 * Check whether we can update tcp_ts_recent.  This test is
3111 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
3112 	 * Extensions for High Performance: An Update", Internet Draft.
3113 	 */
3114 	if (tcp->tcp_snd_ts_ok &&
3115 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
3116 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
3117 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
3118 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
3119 	}
3120 
3121 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
3122 		/*
3123 		 * FIN in an out of order segment.  We record this in
3124 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
3125 		 * Clear the FIN so that any check on FIN flag will fail.
3126 		 * Remember that FIN also counts in the sequence number
3127 		 * space.  So we need to ack out of order FIN only segments.
3128 		 */
3129 		if (flags & TH_FIN) {
3130 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
3131 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
3132 			flags &= ~TH_FIN;
3133 			flags |= TH_ACK_NEEDED;
3134 		}
3135 		if (seg_len > 0) {
3136 			/* Fill in the SACK blk list. */
3137 			if (tcp->tcp_snd_sack_ok) {
3138 				tcp_sack_insert(tcp->tcp_sack_list,
3139 				    seg_seq, seg_seq + seg_len,
3140 				    &(tcp->tcp_num_sack_blk));
3141 			}
3142 
3143 			/*
3144 			 * Attempt reassembly and see if we have something
3145 			 * ready to go.
3146 			 */
3147 			mp = tcp_reass(tcp, mp, seg_seq);
3148 			/* Always ack out of order packets */
3149 			flags |= TH_ACK_NEEDED | TH_PUSH;
3150 			if (mp) {
3151 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
3152 				    (uintptr_t)INT_MAX);
3153 				seg_len = mp->b_cont ? msgdsize(mp) :
3154 				    (int)(mp->b_wptr - mp->b_rptr);
3155 				seg_seq = tcp->tcp_rnxt;
3156 				/*
3157 				 * A gap is filled and the seq num and len
3158 				 * of the gap match that of a previously
3159 				 * received FIN, put the FIN flag back in.
3160 				 */
3161 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
3162 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
3163 					flags |= TH_FIN;
3164 					tcp->tcp_valid_bits &=
3165 					    ~TCP_OFO_FIN_VALID;
3166 				}
3167 				if (tcp->tcp_reass_tid != 0) {
3168 					(void) TCP_TIMER_CANCEL(tcp,
3169 					    tcp->tcp_reass_tid);
3170 					/*
3171 					 * Restart the timer if there is still
3172 					 * data in the reassembly queue.
3173 					 */
3174 					if (tcp->tcp_reass_head != NULL) {
3175 						tcp->tcp_reass_tid = TCP_TIMER(
3176 						    tcp, tcp_reass_timer,
3177 						    tcps->tcps_reass_timeout);
3178 					} else {
3179 						tcp->tcp_reass_tid = 0;
3180 					}
3181 				}
3182 			} else {
3183 				/*
3184 				 * Keep going even with NULL mp.
3185 				 * There may be a useful ACK or something else
3186 				 * we don't want to miss.
3187 				 *
3188 				 * But TCP should not perform fast retransmit
3189 				 * because of the ack number.  TCP uses
3190 				 * seg_len == 0 to determine if it is a pure
3191 				 * ACK.  And this is not a pure ACK.
3192 				 */
3193 				seg_len = 0;
3194 				ofo_seg = B_TRUE;
3195 
3196 				if (tcps->tcps_reass_timeout != 0 &&
3197 				    tcp->tcp_reass_tid == 0) {
3198 					tcp->tcp_reass_tid = TCP_TIMER(tcp,
3199 					    tcp_reass_timer,
3200 					    tcps->tcps_reass_timeout);
3201 				}
3202 			}
3203 		}
3204 	} else if (seg_len > 0) {
3205 		TCPS_BUMP_MIB(tcps, tcpInDataInorderSegs);
3206 		TCPS_UPDATE_MIB(tcps, tcpInDataInorderBytes, seg_len);
3207 		/*
3208 		 * If an out of order FIN was received before, and the seq
3209 		 * num and len of the new segment match that of the FIN,
3210 		 * put the FIN flag back in.
3211 		 */
3212 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
3213 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
3214 			flags |= TH_FIN;
3215 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
3216 		}
3217 	}
3218 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
3219 	if (flags & TH_RST) {
3220 		freemsg(mp);
3221 		switch (tcp->tcp_state) {
3222 		case TCPS_SYN_RCVD:
3223 			(void) tcp_clean_death(tcp, ECONNREFUSED);
3224 			break;
3225 		case TCPS_ESTABLISHED:
3226 		case TCPS_FIN_WAIT_1:
3227 		case TCPS_FIN_WAIT_2:
3228 		case TCPS_CLOSE_WAIT:
3229 			(void) tcp_clean_death(tcp, ECONNRESET);
3230 			break;
3231 		case TCPS_CLOSING:
3232 		case TCPS_LAST_ACK:
3233 			(void) tcp_clean_death(tcp, 0);
3234 			break;
3235 		default:
3236 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
3237 			(void) tcp_clean_death(tcp, ENXIO);
3238 			break;
3239 		}
3240 		return;
3241 	}
3242 	if (flags & TH_SYN) {
3243 		/*
3244 		 * See RFC 793, Page 71
3245 		 *
3246 		 * The seq number must be in the window as it should
3247 		 * be "fixed" above.  If it is outside window, it should
3248 		 * be already rejected.  Note that we allow seg_seq to be
3249 		 * rnxt + rwnd because we want to accept 0 window probe.
3250 		 */
3251 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
3252 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
3253 		freemsg(mp);
3254 		/*
3255 		 * If the ACK flag is not set, just use our snxt as the
3256 		 * seq number of the RST segment.
3257 		 */
3258 		if (!(flags & TH_ACK)) {
3259 			seg_ack = tcp->tcp_snxt;
3260 		}
3261 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
3262 		    TH_RST|TH_ACK);
3263 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
3264 		(void) tcp_clean_death(tcp, ECONNRESET);
3265 		return;
3266 	}
3267 	/*
3268 	 * urp could be -1 when the urp field in the packet is 0
3269 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
3270 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
3271 	 */
3272 	if (flags & TH_URG && urp >= 0) {
3273 		if (!tcp->tcp_urp_last_valid ||
3274 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
3275 			/*
3276 			 * Non-STREAMS sockets handle the urgent data a litte
3277 			 * differently from STREAMS based sockets. There is no
3278 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
3279 			 * flags to keep SIOCATMARK happy. Instead a
3280 			 * su_signal_oob upcall is made to update the mark.
3281 			 * Neither is a T_EXDATA_IND mblk needed to be
3282 			 * prepended to the urgent data. The urgent data is
3283 			 * delivered using the su_recv upcall, where we set
3284 			 * the MSG_OOB flag to indicate that it is urg data.
3285 			 *
3286 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
3287 			 * are used by non-STREAMS sockets.
3288 			 */
3289 			if (IPCL_IS_NONSTR(connp)) {
3290 				if (!TCP_IS_DETACHED(tcp)) {
3291 					(*connp->conn_upcalls->su_signal_oob)
3292 					    (connp->conn_upper_handle, urp);
3293 				}
3294 			} else {
3295 				/*
3296 				 * If we haven't generated the signal yet for
3297 				 * this urgent pointer value, do it now.  Also,
3298 				 * send up a zero-length M_DATA indicating
3299 				 * whether or not this is the mark. The latter
3300 				 * is not needed when a T_EXDATA_IND is sent up.
3301 				 * However, if there are allocation failures
3302 				 * this code relies on the sender retransmitting
3303 				 * and the socket code for determining the mark
3304 				 * should not block waiting for the peer to
3305 				 * transmit. Thus, for simplicity we always
3306 				 * send up the mark indication.
3307 				 */
3308 				mp1 = allocb(0, BPRI_MED);
3309 				if (mp1 == NULL) {
3310 					freemsg(mp);
3311 					return;
3312 				}
3313 				if (!TCP_IS_DETACHED(tcp) &&
3314 				    !putnextctl1(connp->conn_rq, M_PCSIG,
3315 				    SIGURG)) {
3316 					/* Try again on the rexmit. */
3317 					freemsg(mp1);
3318 					freemsg(mp);
3319 					return;
3320 				}
3321 				/*
3322 				 * Mark with NOTMARKNEXT for now.
3323 				 * The code below will change this to MARKNEXT
3324 				 * if we are at the mark.
3325 				 *
3326 				 * If there are allocation failures (e.g. in
3327 				 * dupmsg below) the next time tcp_input_data
3328 				 * sees the urgent segment it will send up the
3329 				 * MSGMARKNEXT message.
3330 				 */
3331 				mp1->b_flag |= MSGNOTMARKNEXT;
3332 				freemsg(tcp->tcp_urp_mark_mp);
3333 				tcp->tcp_urp_mark_mp = mp1;
3334 				flags |= TH_SEND_URP_MARK;
3335 #ifdef DEBUG
3336 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
3337 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
3338 				    "last %x, %s",
3339 				    seg_seq, urp, tcp->tcp_urp_last,
3340 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
3341 #endif /* DEBUG */
3342 			}
3343 			tcp->tcp_urp_last_valid = B_TRUE;
3344 			tcp->tcp_urp_last = urp + seg_seq;
3345 		} else if (tcp->tcp_urp_mark_mp != NULL) {
3346 			/*
3347 			 * An allocation failure prevented the previous
3348 			 * tcp_input_data from sending up the allocated
3349 			 * MSG*MARKNEXT message - send it up this time
3350 			 * around.
3351 			 */
3352 			flags |= TH_SEND_URP_MARK;
3353 		}
3354 
3355 		/*
3356 		 * If the urgent byte is in this segment, make sure that it is
3357 		 * all by itself.  This makes it much easier to deal with the
3358 		 * possibility of an allocation failure on the T_exdata_ind.
3359 		 * Note that seg_len is the number of bytes in the segment, and
3360 		 * urp is the offset into the segment of the urgent byte.
3361 		 * urp < seg_len means that the urgent byte is in this segment.
3362 		 */
3363 		if (urp < seg_len) {
3364 			if (seg_len != 1) {
3365 				uint32_t  tmp_rnxt;
3366 				/*
3367 				 * Break it up and feed it back in.
3368 				 * Re-attach the IP header.
3369 				 */
3370 				mp->b_rptr = iphdr;
3371 				if (urp > 0) {
3372 					/*
3373 					 * There is stuff before the urgent
3374 					 * byte.
3375 					 */
3376 					mp1 = dupmsg(mp);
3377 					if (!mp1) {
3378 						/*
3379 						 * Trim from urgent byte on.
3380 						 * The rest will come back.
3381 						 */
3382 						(void) adjmsg(mp,
3383 						    urp - seg_len);
3384 						tcp_input_data(connp,
3385 						    mp, NULL, ira);
3386 						return;
3387 					}
3388 					(void) adjmsg(mp1, urp - seg_len);
3389 					/* Feed this piece back in. */
3390 					tmp_rnxt = tcp->tcp_rnxt;
3391 					tcp_input_data(connp, mp1, NULL, ira);
3392 					/*
3393 					 * If the data passed back in was not
3394 					 * processed (ie: bad ACK) sending
3395 					 * the remainder back in will cause a
3396 					 * loop. In this case, drop the
3397 					 * packet and let the sender try
3398 					 * sending a good packet.
3399 					 */
3400 					if (tmp_rnxt == tcp->tcp_rnxt) {
3401 						freemsg(mp);
3402 						return;
3403 					}
3404 				}
3405 				if (urp != seg_len - 1) {
3406 					uint32_t  tmp_rnxt;
3407 					/*
3408 					 * There is stuff after the urgent
3409 					 * byte.
3410 					 */
3411 					mp1 = dupmsg(mp);
3412 					if (!mp1) {
3413 						/*
3414 						 * Trim everything beyond the
3415 						 * urgent byte.  The rest will
3416 						 * come back.
3417 						 */
3418 						(void) adjmsg(mp,
3419 						    urp + 1 - seg_len);
3420 						tcp_input_data(connp,
3421 						    mp, NULL, ira);
3422 						return;
3423 					}
3424 					(void) adjmsg(mp1, urp + 1 - seg_len);
3425 					tmp_rnxt = tcp->tcp_rnxt;
3426 					tcp_input_data(connp, mp1, NULL, ira);
3427 					/*
3428 					 * If the data passed back in was not
3429 					 * processed (ie: bad ACK) sending
3430 					 * the remainder back in will cause a
3431 					 * loop. In this case, drop the
3432 					 * packet and let the sender try
3433 					 * sending a good packet.
3434 					 */
3435 					if (tmp_rnxt == tcp->tcp_rnxt) {
3436 						freemsg(mp);
3437 						return;
3438 					}
3439 				}
3440 				tcp_input_data(connp, mp, NULL, ira);
3441 				return;
3442 			}
3443 			/*
3444 			 * This segment contains only the urgent byte.  We
3445 			 * have to allocate the T_exdata_ind, if we can.
3446 			 */
3447 			if (IPCL_IS_NONSTR(connp)) {
3448 				int error;
3449 
3450 				(*connp->conn_upcalls->su_recv)
3451 				    (connp->conn_upper_handle, mp, seg_len,
3452 				    MSG_OOB, &error, NULL);
3453 				/*
3454 				 * We should never be in middle of a
3455 				 * fallback, the squeue guarantees that.
3456 				 */
3457 				ASSERT(error != EOPNOTSUPP);
3458 				mp = NULL;
3459 				goto update_ack;
3460 			} else if (!tcp->tcp_urp_mp) {
3461 				struct T_exdata_ind *tei;
3462 				mp1 = allocb(sizeof (struct T_exdata_ind),
3463 				    BPRI_MED);
3464 				if (!mp1) {
3465 					/*
3466 					 * Sigh... It'll be back.
3467 					 * Generate any MSG*MARK message now.
3468 					 */
3469 					freemsg(mp);
3470 					seg_len = 0;
3471 					if (flags & TH_SEND_URP_MARK) {
3472 
3473 
3474 						ASSERT(tcp->tcp_urp_mark_mp);
3475 						tcp->tcp_urp_mark_mp->b_flag &=
3476 						    ~MSGNOTMARKNEXT;
3477 						tcp->tcp_urp_mark_mp->b_flag |=
3478 						    MSGMARKNEXT;
3479 					}
3480 					goto ack_check;
3481 				}
3482 				mp1->b_datap->db_type = M_PROTO;
3483 				tei = (struct T_exdata_ind *)mp1->b_rptr;
3484 				tei->PRIM_type = T_EXDATA_IND;
3485 				tei->MORE_flag = 0;
3486 				mp1->b_wptr = (uchar_t *)&tei[1];
3487 				tcp->tcp_urp_mp = mp1;
3488 #ifdef DEBUG
3489 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
3490 				    "tcp_rput: allocated exdata_ind %s",
3491 				    tcp_display(tcp, NULL,
3492 				    DISP_PORT_ONLY));
3493 #endif /* DEBUG */
3494 				/*
3495 				 * There is no need to send a separate MSG*MARK
3496 				 * message since the T_EXDATA_IND will be sent
3497 				 * now.
3498 				 */
3499 				flags &= ~TH_SEND_URP_MARK;
3500 				freemsg(tcp->tcp_urp_mark_mp);
3501 				tcp->tcp_urp_mark_mp = NULL;
3502 			}
3503 			/*
3504 			 * Now we are all set.  On the next putnext upstream,
3505 			 * tcp_urp_mp will be non-NULL and will get prepended
3506 			 * to what has to be this piece containing the urgent
3507 			 * byte.  If for any reason we abort this segment below,
3508 			 * if it comes back, we will have this ready, or it
3509 			 * will get blown off in close.
3510 			 */
3511 		} else if (urp == seg_len) {
3512 			/*
3513 			 * The urgent byte is the next byte after this sequence
3514 			 * number. If this endpoint is non-STREAMS, then there
3515 			 * is nothing to do here since the socket has already
3516 			 * been notified about the urg pointer by the
3517 			 * su_signal_oob call above.
3518 			 *
3519 			 * In case of STREAMS, some more work might be needed.
3520 			 * If there is data it is marked with MSGMARKNEXT and
3521 			 * and any tcp_urp_mark_mp is discarded since it is not
3522 			 * needed. Otherwise, if the code above just allocated
3523 			 * a zero-length tcp_urp_mark_mp message, that message
3524 			 * is tagged with MSGMARKNEXT. Sending up these
3525 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
3526 			 * even though the T_EXDATA_IND will not be sent up
3527 			 * until the urgent byte arrives.
3528 			 */
3529 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
3530 				if (seg_len != 0) {
3531 					flags |= TH_MARKNEXT_NEEDED;
3532 					freemsg(tcp->tcp_urp_mark_mp);
3533 					tcp->tcp_urp_mark_mp = NULL;
3534 					flags &= ~TH_SEND_URP_MARK;
3535 				} else if (tcp->tcp_urp_mark_mp != NULL) {
3536 					flags |= TH_SEND_URP_MARK;
3537 					tcp->tcp_urp_mark_mp->b_flag &=
3538 					    ~MSGNOTMARKNEXT;
3539 					tcp->tcp_urp_mark_mp->b_flag |=
3540 					    MSGMARKNEXT;
3541 				}
3542 			}
3543 #ifdef DEBUG
3544 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
3545 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
3546 			    seg_len, flags,
3547 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
3548 #endif /* DEBUG */
3549 		}
3550 #ifdef DEBUG
3551 		else {
3552 			/* Data left until we hit mark */
3553 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
3554 			    "tcp_rput: URP %d bytes left, %s",
3555 			    urp - seg_len, tcp_display(tcp, NULL,
3556 			    DISP_PORT_ONLY));
3557 		}
3558 #endif /* DEBUG */
3559 	}
3560 
3561 process_ack:
3562 	if (!(flags & TH_ACK)) {
3563 		freemsg(mp);
3564 		goto xmit_check;
3565 	}
3566 	}
3567 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
3568 
3569 	if (bytes_acked > 0)
3570 		tcp->tcp_ip_forward_progress = B_TRUE;
3571 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
3572 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
3573 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
3574 			/* 3-way handshake complete - pass up the T_CONN_IND */
3575 			tcp_t	*listener = tcp->tcp_listener;
3576 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
3577 
3578 			tcp->tcp_tconnind_started = B_TRUE;
3579 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
3580 			/*
3581 			 * We are here means eager is fine but it can
3582 			 * get a TH_RST at any point between now and till
3583 			 * accept completes and disappear. We need to
3584 			 * ensure that reference to eager is valid after
3585 			 * we get out of eager's perimeter. So we do
3586 			 * an extra refhold.
3587 			 */
3588 			CONN_INC_REF(connp);
3589 
3590 			/*
3591 			 * The listener also exists because of the refhold
3592 			 * done in tcp_input_listener. Its possible that it
3593 			 * might have closed. We will check that once we
3594 			 * get inside listeners context.
3595 			 */
3596 			CONN_INC_REF(listener->tcp_connp);
3597 			if (listener->tcp_connp->conn_sqp ==
3598 			    connp->conn_sqp) {
3599 				/*
3600 				 * We optimize by not calling an SQUEUE_ENTER
3601 				 * on the listener since we know that the
3602 				 * listener and eager squeues are the same.
3603 				 * We are able to make this check safely only
3604 				 * because neither the eager nor the listener
3605 				 * can change its squeue. Only an active connect
3606 				 * can change its squeue
3607 				 */
3608 				tcp_send_conn_ind(listener->tcp_connp, mp,
3609 				    listener->tcp_connp->conn_sqp);
3610 				CONN_DEC_REF(listener->tcp_connp);
3611 			} else if (!tcp->tcp_loopback) {
3612 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
3613 				    mp, tcp_send_conn_ind,
3614 				    listener->tcp_connp, NULL, SQ_FILL,
3615 				    SQTAG_TCP_CONN_IND);
3616 			} else {
3617 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
3618 				    mp, tcp_send_conn_ind,
3619 				    listener->tcp_connp, NULL, SQ_PROCESS,
3620 				    SQTAG_TCP_CONN_IND);
3621 			}
3622 		}
3623 
3624 		/*
3625 		 * We are seeing the final ack in the three way
3626 		 * hand shake of a active open'ed connection
3627 		 * so we must send up a T_CONN_CON
3628 		 *
3629 		 * tcp_sendmsg() checks tcp_state without entering
3630 		 * the squeue so tcp_state should be updated before
3631 		 * sending up connection confirmation.
3632 		 */
3633 		tcp->tcp_state = TCPS_ESTABLISHED;
3634 
3635 		if (tcp->tcp_active_open) {
3636 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
3637 				freemsg(mp);
3638 				tcp->tcp_state = TCPS_SYN_RCVD;
3639 				return;
3640 			}
3641 			/*
3642 			 * Don't fuse the loopback endpoints for
3643 			 * simultaneous active opens.
3644 			 */
3645 			if (tcp->tcp_loopback) {
3646 				TCP_STAT(tcps, tcp_fusion_unfusable);
3647 				tcp->tcp_unfusable = B_TRUE;
3648 			}
3649 		}
3650 		TCPS_CONN_INC(tcps);
3651 
3652 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
3653 		bytes_acked--;
3654 		/* SYN was acked - making progress */
3655 		tcp->tcp_ip_forward_progress = B_TRUE;
3656 
3657 		/*
3658 		 * If SYN was retransmitted, need to reset all
3659 		 * retransmission info as this segment will be
3660 		 * treated as a dup ACK.
3661 		 */
3662 		if (tcp->tcp_rexmit) {
3663 			tcp->tcp_rexmit = B_FALSE;
3664 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
3665 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
3666 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
3667 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
3668 			tcp->tcp_ms_we_have_waited = 0;
3669 			tcp->tcp_cwnd = mss;
3670 		}
3671 
3672 		/*
3673 		 * We set the send window to zero here.
3674 		 * This is needed if there is data to be
3675 		 * processed already on the queue.
3676 		 * Later (at swnd_update label), the
3677 		 * "new_swnd > tcp_swnd" condition is satisfied
3678 		 * the XMIT_NEEDED flag is set in the current
3679 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
3680 		 * called if there is already data on queue in
3681 		 * this state.
3682 		 */
3683 		tcp->tcp_swnd = 0;
3684 
3685 		if (new_swnd > tcp->tcp_max_swnd)
3686 			tcp->tcp_max_swnd = new_swnd;
3687 		tcp->tcp_swl1 = seg_seq;
3688 		tcp->tcp_swl2 = seg_ack;
3689 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
3690 
3691 		/* Fuse when both sides are in ESTABLISHED state */
3692 		if (tcp->tcp_loopback && do_tcp_fusion)
3693 			tcp_fuse(tcp, iphdr, tcpha);
3694 
3695 	}
3696 	/* This code follows 4.4BSD-Lite2 mostly. */
3697 	if (bytes_acked < 0)
3698 		goto est;
3699 
3700 	/*
3701 	 * If TCP is ECN capable and the congestion experience bit is
3702 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
3703 	 * done once per window (or more loosely, per RTT).
3704 	 */
3705 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
3706 		tcp->tcp_cwr = B_FALSE;
3707 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
3708 		if (!tcp->tcp_cwr) {
3709 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
3710 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
3711 			tcp->tcp_cwnd = npkt * mss;
3712 			/*
3713 			 * If the cwnd is 0, use the timer to clock out
3714 			 * new segments.  This is required by the ECN spec.
3715 			 */
3716 			if (npkt == 0) {
3717 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
3718 				/*
3719 				 * This makes sure that when the ACK comes
3720 				 * back, we will increase tcp_cwnd by 1 MSS.
3721 				 */
3722 				tcp->tcp_cwnd_cnt = 0;
3723 			}
3724 			tcp->tcp_cwr = B_TRUE;
3725 			/*
3726 			 * This marks the end of the current window of in
3727 			 * flight data.  That is why we don't use
3728 			 * tcp_suna + tcp_swnd.  Only data in flight can
3729 			 * provide ECN info.
3730 			 */
3731 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
3732 			tcp->tcp_ecn_cwr_sent = B_FALSE;
3733 		}
3734 	}
3735 
3736 	mp1 = tcp->tcp_xmit_head;
3737 	if (bytes_acked == 0) {
3738 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
3739 			int dupack_cnt;
3740 
3741 			TCPS_BUMP_MIB(tcps, tcpInDupAck);
3742 			/*
3743 			 * Fast retransmit.  When we have seen exactly three
3744 			 * identical ACKs while we have unacked data
3745 			 * outstanding we take it as a hint that our peer
3746 			 * dropped something.
3747 			 *
3748 			 * If TCP is retransmitting, don't do fast retransmit.
3749 			 */
3750 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
3751 			    ! tcp->tcp_rexmit) {
3752 				/* Do Limited Transmit */
3753 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
3754 				    tcps->tcps_dupack_fast_retransmit) {
3755 					/*
3756 					 * RFC 3042
3757 					 *
3758 					 * What we need to do is temporarily
3759 					 * increase tcp_cwnd so that new
3760 					 * data can be sent if it is allowed
3761 					 * by the receive window (tcp_rwnd).
3762 					 * tcp_wput_data() will take care of
3763 					 * the rest.
3764 					 *
3765 					 * If the connection is SACK capable,
3766 					 * only do limited xmit when there
3767 					 * is SACK info.
3768 					 *
3769 					 * Note how tcp_cwnd is incremented.
3770 					 * The first dup ACK will increase
3771 					 * it by 1 MSS.  The second dup ACK
3772 					 * will increase it by 2 MSS.  This
3773 					 * means that only 1 new segment will
3774 					 * be sent for each dup ACK.
3775 					 */
3776 					if (tcp->tcp_unsent > 0 &&
3777 					    (!tcp->tcp_snd_sack_ok ||
3778 					    (tcp->tcp_snd_sack_ok &&
3779 					    tcp->tcp_notsack_list != NULL))) {
3780 						tcp->tcp_cwnd += mss <<
3781 						    (tcp->tcp_dupack_cnt - 1);
3782 						flags |= TH_LIMIT_XMIT;
3783 					}
3784 				} else if (dupack_cnt ==
3785 				    tcps->tcps_dupack_fast_retransmit) {
3786 
3787 				/*
3788 				 * If we have reduced tcp_ssthresh
3789 				 * because of ECN, do not reduce it again
3790 				 * unless it is already one window of data
3791 				 * away.  After one window of data, tcp_cwr
3792 				 * should then be cleared.  Note that
3793 				 * for non ECN capable connection, tcp_cwr
3794 				 * should always be false.
3795 				 *
3796 				 * Adjust cwnd since the duplicate
3797 				 * ack indicates that a packet was
3798 				 * dropped (due to congestion.)
3799 				 */
3800 				if (!tcp->tcp_cwr) {
3801 					npkt = ((tcp->tcp_snxt -
3802 					    tcp->tcp_suna) >> 1) / mss;
3803 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
3804 					    mss;
3805 					tcp->tcp_cwnd = (npkt +
3806 					    tcp->tcp_dupack_cnt) * mss;
3807 				}
3808 				if (tcp->tcp_ecn_ok) {
3809 					tcp->tcp_cwr = B_TRUE;
3810 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
3811 					tcp->tcp_ecn_cwr_sent = B_FALSE;
3812 				}
3813 
3814 				/*
3815 				 * We do Hoe's algorithm.  Refer to her
3816 				 * paper "Improving the Start-up Behavior
3817 				 * of a Congestion Control Scheme for TCP,"
3818 				 * appeared in SIGCOMM'96.
3819 				 *
3820 				 * Save highest seq no we have sent so far.
3821 				 * Be careful about the invisible FIN byte.
3822 				 */
3823 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
3824 				    (tcp->tcp_unsent == 0)) {
3825 					tcp->tcp_rexmit_max = tcp->tcp_fss;
3826 				} else {
3827 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
3828 				}
3829 
3830 				/*
3831 				 * Do not allow bursty traffic during.
3832 				 * fast recovery.  Refer to Fall and Floyd's
3833 				 * paper "Simulation-based Comparisons of
3834 				 * Tahoe, Reno and SACK TCP" (in CCR?)
3835 				 * This is a best current practise.
3836 				 */
3837 				tcp->tcp_snd_burst = TCP_CWND_SS;
3838 
3839 				/*
3840 				 * For SACK:
3841 				 * Calculate tcp_pipe, which is the
3842 				 * estimated number of bytes in
3843 				 * network.
3844 				 *
3845 				 * tcp_fack is the highest sack'ed seq num
3846 				 * TCP has received.
3847 				 *
3848 				 * tcp_pipe is explained in the above quoted
3849 				 * Fall and Floyd's paper.  tcp_fack is
3850 				 * explained in Mathis and Mahdavi's
3851 				 * "Forward Acknowledgment: Refining TCP
3852 				 * Congestion Control" in SIGCOMM '96.
3853 				 */
3854 				if (tcp->tcp_snd_sack_ok) {
3855 					if (tcp->tcp_notsack_list != NULL) {
3856 						tcp->tcp_pipe = tcp->tcp_snxt -
3857 						    tcp->tcp_fack;
3858 						tcp->tcp_sack_snxt = seg_ack;
3859 						flags |= TH_NEED_SACK_REXMIT;
3860 					} else {
3861 						/*
3862 						 * Always initialize tcp_pipe
3863 						 * even though we don't have
3864 						 * any SACK info.  If later
3865 						 * we get SACK info and
3866 						 * tcp_pipe is not initialized,
3867 						 * funny things will happen.
3868 						 */
3869 						tcp->tcp_pipe =
3870 						    tcp->tcp_cwnd_ssthresh;
3871 					}
3872 				} else {
3873 					flags |= TH_REXMIT_NEEDED;
3874 				} /* tcp_snd_sack_ok */
3875 
3876 				} else {
3877 					/*
3878 					 * Here we perform congestion
3879 					 * avoidance, but NOT slow start.
3880 					 * This is known as the Fast
3881 					 * Recovery Algorithm.
3882 					 */
3883 					if (tcp->tcp_snd_sack_ok &&
3884 					    tcp->tcp_notsack_list != NULL) {
3885 						flags |= TH_NEED_SACK_REXMIT;
3886 						tcp->tcp_pipe -= mss;
3887 						if (tcp->tcp_pipe < 0)
3888 							tcp->tcp_pipe = 0;
3889 					} else {
3890 					/*
3891 					 * We know that one more packet has
3892 					 * left the pipe thus we can update
3893 					 * cwnd.
3894 					 */
3895 					cwnd = tcp->tcp_cwnd + mss;
3896 					if (cwnd > tcp->tcp_cwnd_max)
3897 						cwnd = tcp->tcp_cwnd_max;
3898 					tcp->tcp_cwnd = cwnd;
3899 					if (tcp->tcp_unsent > 0)
3900 						flags |= TH_XMIT_NEEDED;
3901 					}
3902 				}
3903 			}
3904 		} else if (tcp->tcp_zero_win_probe) {
3905 			/*
3906 			 * If the window has opened, need to arrange
3907 			 * to send additional data.
3908 			 */
3909 			if (new_swnd != 0) {
3910 				/* tcp_suna != tcp_snxt */
3911 				/* Packet contains a window update */
3912 				TCPS_BUMP_MIB(tcps, tcpInWinUpdate);
3913 				tcp->tcp_zero_win_probe = 0;
3914 				tcp->tcp_timer_backoff = 0;
3915 				tcp->tcp_ms_we_have_waited = 0;
3916 
3917 				/*
3918 				 * Transmit starting with tcp_suna since
3919 				 * the one byte probe is not ack'ed.
3920 				 * If TCP has sent more than one identical
3921 				 * probe, tcp_rexmit will be set.  That means
3922 				 * tcp_ss_rexmit() will send out the one
3923 				 * byte along with new data.  Otherwise,
3924 				 * fake the retransmission.
3925 				 */
3926 				flags |= TH_XMIT_NEEDED;
3927 				if (!tcp->tcp_rexmit) {
3928 					tcp->tcp_rexmit = B_TRUE;
3929 					tcp->tcp_dupack_cnt = 0;
3930 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
3931 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
3932 				}
3933 			}
3934 		}
3935 		goto swnd_update;
3936 	}
3937 
3938 	/*
3939 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
3940 	 * If the ACK value acks something that we have not yet sent, it might
3941 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
3942 	 * other side.
3943 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
3944 	 * state is handled above, so we can always just drop the segment and
3945 	 * send an ACK here.
3946 	 *
3947 	 * In the case where the peer shrinks the window, we see the new window
3948 	 * update, but all the data sent previously is queued up by the peer.
3949 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
3950 	 * number, which was already sent, and within window, is recorded.
3951 	 * tcp_snxt is then updated.
3952 	 *
3953 	 * If the window has previously shrunk, and an ACK for data not yet
3954 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
3955 	 * the ACK is for data within the window at the time the window was
3956 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
3957 	 * the sequence number ACK'ed.
3958 	 *
3959 	 * If the ACK covers all the data sent at the time the window was
3960 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
3961 	 *
3962 	 * Should we send ACKs in response to ACK only segments?
3963 	 */
3964 
3965 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
3966 		if ((tcp->tcp_is_wnd_shrnk) &&
3967 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
3968 			uint32_t data_acked_ahead_snxt;
3969 
3970 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
3971 			tcp_update_xmit_tail(tcp, seg_ack);
3972 			tcp->tcp_unsent -= data_acked_ahead_snxt;
3973 		} else {
3974 			TCPS_BUMP_MIB(tcps, tcpInAckUnsent);
3975 			/* drop the received segment */
3976 			freemsg(mp);
3977 
3978 			/*
3979 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
3980 			 * greater than 0, check if the number of such
3981 			 * bogus ACks is greater than that count.  If yes,
3982 			 * don't send back any ACK.  This prevents TCP from
3983 			 * getting into an ACK storm if somehow an attacker
3984 			 * successfully spoofs an acceptable segment to our
3985 			 * peer.  If this continues (count > 2 X threshold),
3986 			 * we should abort this connection.
3987 			 */
3988 			if (tcp_drop_ack_unsent_cnt > 0 &&
3989 			    ++tcp->tcp_in_ack_unsent >
3990 			    tcp_drop_ack_unsent_cnt) {
3991 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
3992 				if (tcp->tcp_in_ack_unsent > 2 *
3993 				    tcp_drop_ack_unsent_cnt) {
3994 					(void) tcp_clean_death(tcp, EPROTO);
3995 				}
3996 				return;
3997 			}
3998 			mp = tcp_ack_mp(tcp);
3999 			if (mp != NULL) {
4000 				BUMP_LOCAL(tcp->tcp_obsegs);
4001 				TCPS_BUMP_MIB(tcps, tcpOutAck);
4002 				tcp_send_data(tcp, mp);
4003 			}
4004 			return;
4005 		}
4006 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
4007 	    tcp->tcp_snxt_shrunk)) {
4008 			tcp->tcp_is_wnd_shrnk = B_FALSE;
4009 	}
4010 
4011 	/*
4012 	 * TCP gets a new ACK, update the notsack'ed list to delete those
4013 	 * blocks that are covered by this ACK.
4014 	 */
4015 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
4016 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
4017 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
4018 	}
4019 
4020 	/*
4021 	 * If we got an ACK after fast retransmit, check to see
4022 	 * if it is a partial ACK.  If it is not and the congestion
4023 	 * window was inflated to account for the other side's
4024 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
4025 	 */
4026 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
4027 		ASSERT(tcp->tcp_rexmit == B_FALSE);
4028 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
4029 			tcp->tcp_dupack_cnt = 0;
4030 			/*
4031 			 * Restore the orig tcp_cwnd_ssthresh after
4032 			 * fast retransmit phase.
4033 			 */
4034 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
4035 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
4036 			}
4037 			tcp->tcp_rexmit_max = seg_ack;
4038 			tcp->tcp_cwnd_cnt = 0;
4039 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
4040 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
4041 
4042 			/*
4043 			 * Remove all notsack info to avoid confusion with
4044 			 * the next fast retrasnmit/recovery phase.
4045 			 */
4046 			if (tcp->tcp_snd_sack_ok) {
4047 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
4048 				    tcp);
4049 			}
4050 		} else {
4051 			if (tcp->tcp_snd_sack_ok &&
4052 			    tcp->tcp_notsack_list != NULL) {
4053 				flags |= TH_NEED_SACK_REXMIT;
4054 				tcp->tcp_pipe -= mss;
4055 				if (tcp->tcp_pipe < 0)
4056 					tcp->tcp_pipe = 0;
4057 			} else {
4058 				/*
4059 				 * Hoe's algorithm:
4060 				 *
4061 				 * Retransmit the unack'ed segment and
4062 				 * restart fast recovery.  Note that we
4063 				 * need to scale back tcp_cwnd to the
4064 				 * original value when we started fast
4065 				 * recovery.  This is to prevent overly
4066 				 * aggressive behaviour in sending new
4067 				 * segments.
4068 				 */
4069 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
4070 				    tcps->tcps_dupack_fast_retransmit * mss;
4071 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
4072 				flags |= TH_REXMIT_NEEDED;
4073 			}
4074 		}
4075 	} else {
4076 		tcp->tcp_dupack_cnt = 0;
4077 		if (tcp->tcp_rexmit) {
4078 			/*
4079 			 * TCP is retranmitting.  If the ACK ack's all
4080 			 * outstanding data, update tcp_rexmit_max and
4081 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
4082 			 * to the correct value.
4083 			 *
4084 			 * Note that SEQ_LEQ() is used.  This is to avoid
4085 			 * unnecessary fast retransmit caused by dup ACKs
4086 			 * received when TCP does slow start retransmission
4087 			 * after a time out.  During this phase, TCP may
4088 			 * send out segments which are already received.
4089 			 * This causes dup ACKs to be sent back.
4090 			 */
4091 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
4092 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
4093 					tcp->tcp_rexmit_nxt = seg_ack;
4094 				}
4095 				if (seg_ack != tcp->tcp_rexmit_max) {
4096 					flags |= TH_XMIT_NEEDED;
4097 				}
4098 			} else {
4099 				tcp->tcp_rexmit = B_FALSE;
4100 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
4101 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
4102 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
4103 			}
4104 			tcp->tcp_ms_we_have_waited = 0;
4105 		}
4106 	}
4107 
4108 	TCPS_BUMP_MIB(tcps, tcpInAckSegs);
4109 	TCPS_UPDATE_MIB(tcps, tcpInAckBytes, bytes_acked);
4110 	tcp->tcp_suna = seg_ack;
4111 	if (tcp->tcp_zero_win_probe != 0) {
4112 		tcp->tcp_zero_win_probe = 0;
4113 		tcp->tcp_timer_backoff = 0;
4114 	}
4115 
4116 	/*
4117 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
4118 	 * Note that it cannot be the SYN being ack'ed.  The code flow
4119 	 * will not reach here.
4120 	 */
4121 	if (mp1 == NULL) {
4122 		goto fin_acked;
4123 	}
4124 
4125 	/*
4126 	 * Update the congestion window.
4127 	 *
4128 	 * If TCP is not ECN capable or TCP is ECN capable but the
4129 	 * congestion experience bit is not set, increase the tcp_cwnd as
4130 	 * usual.
4131 	 */
4132 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
4133 		cwnd = tcp->tcp_cwnd;
4134 		add = mss;
4135 
4136 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
4137 			/*
4138 			 * This is to prevent an increase of less than 1 MSS of
4139 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
4140 			 * may send out tinygrams in order to preserve mblk
4141 			 * boundaries.
4142 			 *
4143 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
4144 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
4145 			 * increased by 1 MSS for every RTTs.
4146 			 */
4147 			if (tcp->tcp_cwnd_cnt <= 0) {
4148 				tcp->tcp_cwnd_cnt = cwnd + add;
4149 			} else {
4150 				tcp->tcp_cwnd_cnt -= add;
4151 				add = 0;
4152 			}
4153 		}
4154 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
4155 	}
4156 
4157 	/* See if the latest urgent data has been acknowledged */
4158 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
4159 	    SEQ_GT(seg_ack, tcp->tcp_urg))
4160 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
4161 
4162 	/* Can we update the RTT estimates? */
4163 	if (tcp->tcp_snd_ts_ok) {
4164 		/* Ignore zero timestamp echo-reply. */
4165 		if (tcpopt.tcp_opt_ts_ecr != 0) {
4166 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
4167 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
4168 		}
4169 
4170 		/* If needed, restart the timer. */
4171 		if (tcp->tcp_set_timer == 1) {
4172 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
4173 			tcp->tcp_set_timer = 0;
4174 		}
4175 		/*
4176 		 * Update tcp_csuna in case the other side stops sending
4177 		 * us timestamps.
4178 		 */
4179 		tcp->tcp_csuna = tcp->tcp_snxt;
4180 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
4181 		/*
4182 		 * An ACK sequence we haven't seen before, so get the RTT
4183 		 * and update the RTO. But first check if the timestamp is
4184 		 * valid to use.
4185 		 */
4186 		if ((mp1->b_next != NULL) &&
4187 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
4188 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
4189 			    (int32_t)(intptr_t)mp1->b_prev);
4190 		else
4191 			TCPS_BUMP_MIB(tcps, tcpRttNoUpdate);
4192 
4193 		/* Remeber the last sequence to be ACKed */
4194 		tcp->tcp_csuna = seg_ack;
4195 		if (tcp->tcp_set_timer == 1) {
4196 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
4197 			tcp->tcp_set_timer = 0;
4198 		}
4199 	} else {
4200 		TCPS_BUMP_MIB(tcps, tcpRttNoUpdate);
4201 	}
4202 
4203 	/* Eat acknowledged bytes off the xmit queue. */
4204 	for (;;) {
4205 		mblk_t	*mp2;
4206 		uchar_t	*wptr;
4207 
4208 		wptr = mp1->b_wptr;
4209 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
4210 		bytes_acked -= (int)(wptr - mp1->b_rptr);
4211 		if (bytes_acked < 0) {
4212 			mp1->b_rptr = wptr + bytes_acked;
4213 			/*
4214 			 * Set a new timestamp if all the bytes timed by the
4215 			 * old timestamp have been ack'ed.
4216 			 */
4217 			if (SEQ_GT(seg_ack,
4218 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
4219 				mp1->b_prev =
4220 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
4221 				mp1->b_next = NULL;
4222 			}
4223 			break;
4224 		}
4225 		mp1->b_next = NULL;
4226 		mp1->b_prev = NULL;
4227 		mp2 = mp1;
4228 		mp1 = mp1->b_cont;
4229 
4230 		/*
4231 		 * This notification is required for some zero-copy
4232 		 * clients to maintain a copy semantic. After the data
4233 		 * is ack'ed, client is safe to modify or reuse the buffer.
4234 		 */
4235 		if (tcp->tcp_snd_zcopy_aware &&
4236 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
4237 			tcp_zcopy_notify(tcp);
4238 		freeb(mp2);
4239 		if (bytes_acked == 0) {
4240 			if (mp1 == NULL) {
4241 				/* Everything is ack'ed, clear the tail. */
4242 				tcp->tcp_xmit_tail = NULL;
4243 				/*
4244 				 * Cancel the timer unless we are still
4245 				 * waiting for an ACK for the FIN packet.
4246 				 */
4247 				if (tcp->tcp_timer_tid != 0 &&
4248 				    tcp->tcp_snxt == tcp->tcp_suna) {
4249 					(void) TCP_TIMER_CANCEL(tcp,
4250 					    tcp->tcp_timer_tid);
4251 					tcp->tcp_timer_tid = 0;
4252 				}
4253 				goto pre_swnd_update;
4254 			}
4255 			if (mp2 != tcp->tcp_xmit_tail)
4256 				break;
4257 			tcp->tcp_xmit_tail = mp1;
4258 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
4259 			    (uintptr_t)INT_MAX);
4260 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
4261 			    mp1->b_rptr);
4262 			break;
4263 		}
4264 		if (mp1 == NULL) {
4265 			/*
4266 			 * More was acked but there is nothing more
4267 			 * outstanding.  This means that the FIN was
4268 			 * just acked or that we're talking to a clown.
4269 			 */
4270 fin_acked:
4271 			ASSERT(tcp->tcp_fin_sent);
4272 			tcp->tcp_xmit_tail = NULL;
4273 			if (tcp->tcp_fin_sent) {
4274 				/* FIN was acked - making progress */
4275 				if (!tcp->tcp_fin_acked)
4276 					tcp->tcp_ip_forward_progress = B_TRUE;
4277 				tcp->tcp_fin_acked = B_TRUE;
4278 				if (tcp->tcp_linger_tid != 0 &&
4279 				    TCP_TIMER_CANCEL(tcp,
4280 				    tcp->tcp_linger_tid) >= 0) {
4281 					tcp_stop_lingering(tcp);
4282 					freemsg(mp);
4283 					mp = NULL;
4284 				}
4285 			} else {
4286 				/*
4287 				 * We should never get here because
4288 				 * we have already checked that the
4289 				 * number of bytes ack'ed should be
4290 				 * smaller than or equal to what we
4291 				 * have sent so far (it is the
4292 				 * acceptability check of the ACK).
4293 				 * We can only get here if the send
4294 				 * queue is corrupted.
4295 				 *
4296 				 * Terminate the connection and
4297 				 * panic the system.  It is better
4298 				 * for us to panic instead of
4299 				 * continuing to avoid other disaster.
4300 				 */
4301 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
4302 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
4303 				panic("Memory corruption "
4304 				    "detected for connection %s.",
4305 				    tcp_display(tcp, NULL,
4306 				    DISP_ADDR_AND_PORT));
4307 				/*NOTREACHED*/
4308 			}
4309 			goto pre_swnd_update;
4310 		}
4311 		ASSERT(mp2 != tcp->tcp_xmit_tail);
4312 	}
4313 	if (tcp->tcp_unsent) {
4314 		flags |= TH_XMIT_NEEDED;
4315 	}
4316 pre_swnd_update:
4317 	tcp->tcp_xmit_head = mp1;
4318 swnd_update:
4319 	/*
4320 	 * The following check is different from most other implementations.
4321 	 * For bi-directional transfer, when segments are dropped, the
4322 	 * "normal" check will not accept a window update in those
4323 	 * retransmitted segemnts.  Failing to do that, TCP may send out
4324 	 * segments which are outside receiver's window.  As TCP accepts
4325 	 * the ack in those retransmitted segments, if the window update in
4326 	 * the same segment is not accepted, TCP will incorrectly calculates
4327 	 * that it can send more segments.  This can create a deadlock
4328 	 * with the receiver if its window becomes zero.
4329 	 */
4330 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
4331 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
4332 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
4333 		/*
4334 		 * The criteria for update is:
4335 		 *
4336 		 * 1. the segment acknowledges some data.  Or
4337 		 * 2. the segment is new, i.e. it has a higher seq num. Or
4338 		 * 3. the segment is not old and the advertised window is
4339 		 * larger than the previous advertised window.
4340 		 */
4341 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
4342 			flags |= TH_XMIT_NEEDED;
4343 		tcp->tcp_swnd = new_swnd;
4344 		if (new_swnd > tcp->tcp_max_swnd)
4345 			tcp->tcp_max_swnd = new_swnd;
4346 		tcp->tcp_swl1 = seg_seq;
4347 		tcp->tcp_swl2 = seg_ack;
4348 	}
4349 est:
4350 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
4351 
4352 		switch (tcp->tcp_state) {
4353 		case TCPS_FIN_WAIT_1:
4354 			if (tcp->tcp_fin_acked) {
4355 				tcp->tcp_state = TCPS_FIN_WAIT_2;
4356 				/*
4357 				 * We implement the non-standard BSD/SunOS
4358 				 * FIN_WAIT_2 flushing algorithm.
4359 				 * If there is no user attached to this
4360 				 * TCP endpoint, then this TCP struct
4361 				 * could hang around forever in FIN_WAIT_2
4362 				 * state if the peer forgets to send us
4363 				 * a FIN.  To prevent this, we wait only
4364 				 * 2*MSL (a convenient time value) for
4365 				 * the FIN to arrive.  If it doesn't show up,
4366 				 * we flush the TCP endpoint.  This algorithm,
4367 				 * though a violation of RFC-793, has worked
4368 				 * for over 10 years in BSD systems.
4369 				 * Note: SunOS 4.x waits 675 seconds before
4370 				 * flushing the FIN_WAIT_2 connection.
4371 				 */
4372 				TCP_TIMER_RESTART(tcp,
4373 				    tcps->tcps_fin_wait_2_flush_interval);
4374 			}
4375 			break;
4376 		case TCPS_FIN_WAIT_2:
4377 			break;	/* Shutdown hook? */
4378 		case TCPS_LAST_ACK:
4379 			freemsg(mp);
4380 			if (tcp->tcp_fin_acked) {
4381 				(void) tcp_clean_death(tcp, 0);
4382 				return;
4383 			}
4384 			goto xmit_check;
4385 		case TCPS_CLOSING:
4386 			if (tcp->tcp_fin_acked)
4387 				SET_TIME_WAIT(tcps, tcp, connp);
4388 			/*FALLTHRU*/
4389 		case TCPS_CLOSE_WAIT:
4390 			freemsg(mp);
4391 			goto xmit_check;
4392 		default:
4393 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
4394 			break;
4395 		}
4396 	}
4397 	if (flags & TH_FIN) {
4398 		/* Make sure we ack the fin */
4399 		flags |= TH_ACK_NEEDED;
4400 		if (!tcp->tcp_fin_rcvd) {
4401 			tcp->tcp_fin_rcvd = B_TRUE;
4402 			tcp->tcp_rnxt++;
4403 			tcpha = tcp->tcp_tcpha;
4404 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
4405 
4406 			/*
4407 			 * Generate the ordrel_ind at the end unless we
4408 			 * are an eager guy.
4409 			 * In the eager case tcp_rsrv will do this when run
4410 			 * after tcp_accept is done.
4411 			 */
4412 			if (tcp->tcp_listener == NULL &&
4413 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
4414 				flags |= TH_ORDREL_NEEDED;
4415 			switch (tcp->tcp_state) {
4416 			case TCPS_SYN_RCVD:
4417 			case TCPS_ESTABLISHED:
4418 				tcp->tcp_state = TCPS_CLOSE_WAIT;
4419 				/* Keepalive? */
4420 				break;
4421 			case TCPS_FIN_WAIT_1:
4422 				if (!tcp->tcp_fin_acked) {
4423 					tcp->tcp_state = TCPS_CLOSING;
4424 					break;
4425 				}
4426 				/* FALLTHRU */
4427 			case TCPS_FIN_WAIT_2:
4428 				SET_TIME_WAIT(tcps, tcp, connp);
4429 				if (seg_len) {
4430 					/*
4431 					 * implies data piggybacked on FIN.
4432 					 * break to handle data.
4433 					 */
4434 					break;
4435 				}
4436 				freemsg(mp);
4437 				goto ack_check;
4438 			}
4439 		}
4440 	}
4441 	if (mp == NULL)
4442 		goto xmit_check;
4443 	if (seg_len == 0) {
4444 		freemsg(mp);
4445 		goto xmit_check;
4446 	}
4447 	if (mp->b_rptr == mp->b_wptr) {
4448 		/*
4449 		 * The header has been consumed, so we remove the
4450 		 * zero-length mblk here.
4451 		 */
4452 		mp1 = mp;
4453 		mp = mp->b_cont;
4454 		freeb(mp1);
4455 	}
4456 update_ack:
4457 	tcpha = tcp->tcp_tcpha;
4458 	tcp->tcp_rack_cnt++;
4459 	{
4460 		uint32_t cur_max;
4461 
4462 		cur_max = tcp->tcp_rack_cur_max;
4463 		if (tcp->tcp_rack_cnt >= cur_max) {
4464 			/*
4465 			 * We have more unacked data than we should - send
4466 			 * an ACK now.
4467 			 */
4468 			flags |= TH_ACK_NEEDED;
4469 			cur_max++;
4470 			if (cur_max > tcp->tcp_rack_abs_max)
4471 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
4472 			else
4473 				tcp->tcp_rack_cur_max = cur_max;
4474 		} else if (TCP_IS_DETACHED(tcp)) {
4475 			/* We don't have an ACK timer for detached TCP. */
4476 			flags |= TH_ACK_NEEDED;
4477 		} else if (seg_len < mss) {
4478 			/*
4479 			 * If we get a segment that is less than an mss, and we
4480 			 * already have unacknowledged data, and the amount
4481 			 * unacknowledged is not a multiple of mss, then we
4482 			 * better generate an ACK now.  Otherwise, this may be
4483 			 * the tail piece of a transaction, and we would rather
4484 			 * wait for the response.
4485 			 */
4486 			uint32_t udif;
4487 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
4488 			    (uintptr_t)INT_MAX);
4489 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
4490 			if (udif && (udif % mss))
4491 				flags |= TH_ACK_NEEDED;
4492 			else
4493 				flags |= TH_ACK_TIMER_NEEDED;
4494 		} else {
4495 			/* Start delayed ack timer */
4496 			flags |= TH_ACK_TIMER_NEEDED;
4497 		}
4498 	}
4499 	tcp->tcp_rnxt += seg_len;
4500 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
4501 
4502 	if (mp == NULL)
4503 		goto xmit_check;
4504 
4505 	/* Update SACK list */
4506 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
4507 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
4508 		    &(tcp->tcp_num_sack_blk));
4509 	}
4510 
4511 	if (tcp->tcp_urp_mp) {
4512 		tcp->tcp_urp_mp->b_cont = mp;
4513 		mp = tcp->tcp_urp_mp;
4514 		tcp->tcp_urp_mp = NULL;
4515 		/* Ready for a new signal. */
4516 		tcp->tcp_urp_last_valid = B_FALSE;
4517 #ifdef DEBUG
4518 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
4519 		    "tcp_rput: sending exdata_ind %s",
4520 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4521 #endif /* DEBUG */
4522 	}
4523 
4524 	/*
4525 	 * Check for ancillary data changes compared to last segment.
4526 	 */
4527 	if (connp->conn_recv_ancillary.crb_all != 0) {
4528 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
4529 		if (mp == NULL)
4530 			return;
4531 	}
4532 
4533 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
4534 		/*
4535 		 * Side queue inbound data until the accept happens.
4536 		 * tcp_accept/tcp_rput drains this when the accept happens.
4537 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
4538 		 * T_EXDATA_IND) it is queued on b_next.
4539 		 * XXX Make urgent data use this. Requires:
4540 		 *	Removing tcp_listener check for TH_URG
4541 		 *	Making M_PCPROTO and MARK messages skip the eager case
4542 		 */
4543 
4544 		if (tcp->tcp_kssl_pending) {
4545 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
4546 			    mblk_t *, mp);
4547 			tcp_kssl_input(tcp, mp, ira->ira_cred);
4548 		} else {
4549 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
4550 		}
4551 	} else if (IPCL_IS_NONSTR(connp)) {
4552 		/*
4553 		 * Non-STREAMS socket
4554 		 *
4555 		 * Note that no KSSL processing is done here, because
4556 		 * KSSL is not supported for non-STREAMS sockets.
4557 		 */
4558 		boolean_t push = flags & (TH_PUSH|TH_FIN);
4559 		int error;
4560 
4561 		if ((*connp->conn_upcalls->su_recv)(
4562 		    connp->conn_upper_handle,
4563 		    mp, seg_len, 0, &error, &push) <= 0) {
4564 			/*
4565 			 * We should never be in middle of a
4566 			 * fallback, the squeue guarantees that.
4567 			 */
4568 			ASSERT(error != EOPNOTSUPP);
4569 			if (error == ENOSPC)
4570 				tcp->tcp_rwnd -= seg_len;
4571 		} else if (push) {
4572 			/* PUSH bit set and sockfs is not flow controlled */
4573 			flags |= tcp_rwnd_reopen(tcp);
4574 		}
4575 	} else {
4576 		/* STREAMS socket */
4577 		if (mp->b_datap->db_type != M_DATA ||
4578 		    (flags & TH_MARKNEXT_NEEDED)) {
4579 			if (tcp->tcp_rcv_list != NULL) {
4580 				flags |= tcp_rcv_drain(tcp);
4581 			}
4582 			ASSERT(tcp->tcp_rcv_list == NULL ||
4583 			    tcp->tcp_fused_sigurg);
4584 
4585 			if (flags & TH_MARKNEXT_NEEDED) {
4586 #ifdef DEBUG
4587 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
4588 				    "tcp_rput: sending MSGMARKNEXT %s",
4589 				    tcp_display(tcp, NULL,
4590 				    DISP_PORT_ONLY));
4591 #endif /* DEBUG */
4592 				mp->b_flag |= MSGMARKNEXT;
4593 				flags &= ~TH_MARKNEXT_NEEDED;
4594 			}
4595 
4596 			/* Does this need SSL processing first? */
4597 			if ((tcp->tcp_kssl_ctx != NULL) &&
4598 			    (DB_TYPE(mp) == M_DATA)) {
4599 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
4600 				    mblk_t *, mp);
4601 				tcp_kssl_input(tcp, mp, ira->ira_cred);
4602 			} else {
4603 				if (is_system_labeled())
4604 					tcp_setcred_data(mp, ira);
4605 
4606 				putnext(connp->conn_rq, mp);
4607 				if (!canputnext(connp->conn_rq))
4608 					tcp->tcp_rwnd -= seg_len;
4609 			}
4610 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
4611 		    (DB_TYPE(mp) == M_DATA)) {
4612 			/* Does this need SSL processing first? */
4613 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
4614 			tcp_kssl_input(tcp, mp, ira->ira_cred);
4615 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
4616 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
4617 			if (tcp->tcp_rcv_list != NULL) {
4618 				/*
4619 				 * Enqueue the new segment first and then
4620 				 * call tcp_rcv_drain() to send all data
4621 				 * up.  The other way to do this is to
4622 				 * send all queued data up and then call
4623 				 * putnext() to send the new segment up.
4624 				 * This way can remove the else part later
4625 				 * on.
4626 				 *
4627 				 * We don't do this to avoid one more call to
4628 				 * canputnext() as tcp_rcv_drain() needs to
4629 				 * call canputnext().
4630 				 */
4631 				tcp_rcv_enqueue(tcp, mp, seg_len,
4632 				    ira->ira_cred);
4633 				flags |= tcp_rcv_drain(tcp);
4634 			} else {
4635 				if (is_system_labeled())
4636 					tcp_setcred_data(mp, ira);
4637 
4638 				putnext(connp->conn_rq, mp);
4639 				if (!canputnext(connp->conn_rq))
4640 					tcp->tcp_rwnd -= seg_len;
4641 			}
4642 		} else {
4643 			/*
4644 			 * Enqueue all packets when processing an mblk
4645 			 * from the co queue and also enqueue normal packets.
4646 			 */
4647 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
4648 		}
4649 		/*
4650 		 * Make sure the timer is running if we have data waiting
4651 		 * for a push bit. This provides resiliency against
4652 		 * implementations that do not correctly generate push bits.
4653 		 */
4654 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
4655 			/*
4656 			 * The connection may be closed at this point, so don't
4657 			 * do anything for a detached tcp.
4658 			 */
4659 			if (!TCP_IS_DETACHED(tcp))
4660 				tcp->tcp_push_tid = TCP_TIMER(tcp,
4661 				    tcp_push_timer,
4662 				    tcps->tcps_push_timer_interval);
4663 		}
4664 	}
4665 
4666 xmit_check:
4667 	/* Is there anything left to do? */
4668 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
4669 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
4670 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
4671 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
4672 		goto done;
4673 
4674 	/* Any transmit work to do and a non-zero window? */
4675 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
4676 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
4677 		if (flags & TH_REXMIT_NEEDED) {
4678 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
4679 
4680 			TCPS_BUMP_MIB(tcps, tcpOutFastRetrans);
4681 			if (snd_size > mss)
4682 				snd_size = mss;
4683 			if (snd_size > tcp->tcp_swnd)
4684 				snd_size = tcp->tcp_swnd;
4685 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
4686 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
4687 			    B_TRUE);
4688 
4689 			if (mp1 != NULL) {
4690 				tcp->tcp_xmit_head->b_prev =
4691 				    (mblk_t *)LBOLT_FASTPATH;
4692 				tcp->tcp_csuna = tcp->tcp_snxt;
4693 				TCPS_BUMP_MIB(tcps, tcpRetransSegs);
4694 				TCPS_UPDATE_MIB(tcps, tcpRetransBytes,
4695 				    snd_size);
4696 				tcp_send_data(tcp, mp1);
4697 			}
4698 		}
4699 		if (flags & TH_NEED_SACK_REXMIT) {
4700 			tcp_sack_rexmit(tcp, &flags);
4701 		}
4702 		/*
4703 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
4704 		 * out new segment.  Note that tcp_rexmit should not be
4705 		 * set, otherwise TH_LIMIT_XMIT should not be set.
4706 		 */
4707 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
4708 			if (!tcp->tcp_rexmit) {
4709 				tcp_wput_data(tcp, NULL, B_FALSE);
4710 			} else {
4711 				tcp_ss_rexmit(tcp);
4712 			}
4713 		}
4714 		/*
4715 		 * Adjust tcp_cwnd back to normal value after sending
4716 		 * new data segments.
4717 		 */
4718 		if (flags & TH_LIMIT_XMIT) {
4719 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
4720 			/*
4721 			 * This will restart the timer.  Restarting the
4722 			 * timer is used to avoid a timeout before the
4723 			 * limited transmitted segment's ACK gets back.
4724 			 */
4725 			if (tcp->tcp_xmit_head != NULL)
4726 				tcp->tcp_xmit_head->b_prev =
4727 				    (mblk_t *)LBOLT_FASTPATH;
4728 		}
4729 
4730 		/* Anything more to do? */
4731 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
4732 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
4733 			goto done;
4734 	}
4735 ack_check:
4736 	if (flags & TH_SEND_URP_MARK) {
4737 		ASSERT(tcp->tcp_urp_mark_mp);
4738 		ASSERT(!IPCL_IS_NONSTR(connp));
4739 		/*
4740 		 * Send up any queued data and then send the mark message
4741 		 */
4742 		if (tcp->tcp_rcv_list != NULL) {
4743 			flags |= tcp_rcv_drain(tcp);
4744 
4745 		}
4746 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
4747 		mp1 = tcp->tcp_urp_mark_mp;
4748 		tcp->tcp_urp_mark_mp = NULL;
4749 		if (is_system_labeled())
4750 			tcp_setcred_data(mp1, ira);
4751 
4752 		putnext(connp->conn_rq, mp1);
4753 #ifdef DEBUG
4754 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
4755 		    "tcp_rput: sending zero-length %s %s",
4756 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
4757 		    "MSGNOTMARKNEXT"),
4758 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4759 #endif /* DEBUG */
4760 		flags &= ~TH_SEND_URP_MARK;
4761 	}
4762 	if (flags & TH_ACK_NEEDED) {
4763 		/*
4764 		 * Time to send an ack for some reason.
4765 		 */
4766 		mp1 = tcp_ack_mp(tcp);
4767 
4768 		if (mp1 != NULL) {
4769 			tcp_send_data(tcp, mp1);
4770 			BUMP_LOCAL(tcp->tcp_obsegs);
4771 			TCPS_BUMP_MIB(tcps, tcpOutAck);
4772 		}
4773 		if (tcp->tcp_ack_tid != 0) {
4774 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4775 			tcp->tcp_ack_tid = 0;
4776 		}
4777 	}
4778 	if (flags & TH_ACK_TIMER_NEEDED) {
4779 		/*
4780 		 * Arrange for deferred ACK or push wait timeout.
4781 		 * Start timer if it is not already running.
4782 		 */
4783 		if (tcp->tcp_ack_tid == 0) {
4784 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
4785 			    tcp->tcp_localnet ?
4786 			    tcps->tcps_local_dack_interval :
4787 			    tcps->tcps_deferred_ack_interval);
4788 		}
4789 	}
4790 	if (flags & TH_ORDREL_NEEDED) {
4791 		/*
4792 		 * Send up the ordrel_ind unless we are an eager guy.
4793 		 * In the eager case tcp_rsrv will do this when run
4794 		 * after tcp_accept is done.
4795 		 */
4796 		ASSERT(tcp->tcp_listener == NULL);
4797 		ASSERT(!tcp->tcp_detached);
4798 
4799 		if (IPCL_IS_NONSTR(connp)) {
4800 			ASSERT(tcp->tcp_ordrel_mp == NULL);
4801 			tcp->tcp_ordrel_done = B_TRUE;
4802 			(*connp->conn_upcalls->su_opctl)
4803 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
4804 			goto done;
4805 		}
4806 
4807 		if (tcp->tcp_rcv_list != NULL) {
4808 			/*
4809 			 * Push any mblk(s) enqueued from co processing.
4810 			 */
4811 			flags |= tcp_rcv_drain(tcp);
4812 		}
4813 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
4814 
4815 		mp1 = tcp->tcp_ordrel_mp;
4816 		tcp->tcp_ordrel_mp = NULL;
4817 		tcp->tcp_ordrel_done = B_TRUE;
4818 		putnext(connp->conn_rq, mp1);
4819 	}
4820 done:
4821 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
4822 }
4823 
4824 /*
4825  * Attach ancillary data to a received TCP segments for the
4826  * ancillary pieces requested by the application that are
4827  * different than they were in the previous data segment.
4828  *
4829  * Save the "current" values once memory allocation is ok so that
4830  * when memory allocation fails we can just wait for the next data segment.
4831  */
4832 static mblk_t *
4833 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
4834     ip_recv_attr_t *ira)
4835 {
4836 	struct T_optdata_ind *todi;
4837 	int optlen;
4838 	uchar_t *optptr;
4839 	struct T_opthdr *toh;
4840 	crb_t addflag;	/* Which pieces to add */
4841 	mblk_t *mp1;
4842 	conn_t	*connp = tcp->tcp_connp;
4843 
4844 	optlen = 0;
4845 	addflag.crb_all = 0;
4846 	/* If app asked for pktinfo and the index has changed ... */
4847 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
4848 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
4849 		optlen += sizeof (struct T_opthdr) +
4850 		    sizeof (struct in6_pktinfo);
4851 		addflag.crb_ip_recvpktinfo = 1;
4852 	}
4853 	/* If app asked for hoplimit and it has changed ... */
4854 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
4855 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
4856 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
4857 		addflag.crb_ipv6_recvhoplimit = 1;
4858 	}
4859 	/* If app asked for tclass and it has changed ... */
4860 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
4861 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
4862 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
4863 		addflag.crb_ipv6_recvtclass = 1;
4864 	}
4865 	/*
4866 	 * If app asked for hopbyhop headers and it has changed ...
4867 	 * For security labels, note that (1) security labels can't change on
4868 	 * a connected socket at all, (2) we're connected to at most one peer,
4869 	 * (3) if anything changes, then it must be some other extra option.
4870 	 */
4871 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
4872 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
4873 	    (ipp->ipp_fields & IPPF_HOPOPTS),
4874 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
4875 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
4876 		addflag.crb_ipv6_recvhopopts = 1;
4877 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
4878 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
4879 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
4880 			return (mp);
4881 	}
4882 	/* If app asked for dst headers before routing headers ... */
4883 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
4884 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
4885 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
4886 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
4887 		optlen += sizeof (struct T_opthdr) +
4888 		    ipp->ipp_rthdrdstoptslen;
4889 		addflag.crb_ipv6_recvrthdrdstopts = 1;
4890 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
4891 		    &tcp->tcp_rthdrdstoptslen,
4892 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
4893 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
4894 			return (mp);
4895 	}
4896 	/* If app asked for routing headers and it has changed ... */
4897 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
4898 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
4899 	    (ipp->ipp_fields & IPPF_RTHDR),
4900 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
4901 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
4902 		addflag.crb_ipv6_recvrthdr = 1;
4903 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
4904 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
4905 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
4906 			return (mp);
4907 	}
4908 	/* If app asked for dest headers and it has changed ... */
4909 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
4910 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
4911 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
4912 	    (ipp->ipp_fields & IPPF_DSTOPTS),
4913 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
4914 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
4915 		addflag.crb_ipv6_recvdstopts = 1;
4916 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
4917 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
4918 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
4919 			return (mp);
4920 	}
4921 
4922 	if (optlen == 0) {
4923 		/* Nothing to add */
4924 		return (mp);
4925 	}
4926 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
4927 	if (mp1 == NULL) {
4928 		/*
4929 		 * Defer sending ancillary data until the next TCP segment
4930 		 * arrives.
4931 		 */
4932 		return (mp);
4933 	}
4934 	mp1->b_cont = mp;
4935 	mp = mp1;
4936 	mp->b_wptr += sizeof (*todi) + optlen;
4937 	mp->b_datap->db_type = M_PROTO;
4938 	todi = (struct T_optdata_ind *)mp->b_rptr;
4939 	todi->PRIM_type = T_OPTDATA_IND;
4940 	todi->DATA_flag = 1;	/* MORE data */
4941 	todi->OPT_length = optlen;
4942 	todi->OPT_offset = sizeof (*todi);
4943 	optptr = (uchar_t *)&todi[1];
4944 	/*
4945 	 * If app asked for pktinfo and the index has changed ...
4946 	 * Note that the local address never changes for the connection.
4947 	 */
4948 	if (addflag.crb_ip_recvpktinfo) {
4949 		struct in6_pktinfo *pkti;
4950 		uint_t ifindex;
4951 
4952 		ifindex = ira->ira_ruifindex;
4953 		toh = (struct T_opthdr *)optptr;
4954 		toh->level = IPPROTO_IPV6;
4955 		toh->name = IPV6_PKTINFO;
4956 		toh->len = sizeof (*toh) + sizeof (*pkti);
4957 		toh->status = 0;
4958 		optptr += sizeof (*toh);
4959 		pkti = (struct in6_pktinfo *)optptr;
4960 		pkti->ipi6_addr = connp->conn_laddr_v6;
4961 		pkti->ipi6_ifindex = ifindex;
4962 		optptr += sizeof (*pkti);
4963 		ASSERT(OK_32PTR(optptr));
4964 		/* Save as "last" value */
4965 		tcp->tcp_recvifindex = ifindex;
4966 	}
4967 	/* If app asked for hoplimit and it has changed ... */
4968 	if (addflag.crb_ipv6_recvhoplimit) {
4969 		toh = (struct T_opthdr *)optptr;
4970 		toh->level = IPPROTO_IPV6;
4971 		toh->name = IPV6_HOPLIMIT;
4972 		toh->len = sizeof (*toh) + sizeof (uint_t);
4973 		toh->status = 0;
4974 		optptr += sizeof (*toh);
4975 		*(uint_t *)optptr = ipp->ipp_hoplimit;
4976 		optptr += sizeof (uint_t);
4977 		ASSERT(OK_32PTR(optptr));
4978 		/* Save as "last" value */
4979 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
4980 	}
4981 	/* If app asked for tclass and it has changed ... */
4982 	if (addflag.crb_ipv6_recvtclass) {
4983 		toh = (struct T_opthdr *)optptr;
4984 		toh->level = IPPROTO_IPV6;
4985 		toh->name = IPV6_TCLASS;
4986 		toh->len = sizeof (*toh) + sizeof (uint_t);
4987 		toh->status = 0;
4988 		optptr += sizeof (*toh);
4989 		*(uint_t *)optptr = ipp->ipp_tclass;
4990 		optptr += sizeof (uint_t);
4991 		ASSERT(OK_32PTR(optptr));
4992 		/* Save as "last" value */
4993 		tcp->tcp_recvtclass = ipp->ipp_tclass;
4994 	}
4995 	if (addflag.crb_ipv6_recvhopopts) {
4996 		toh = (struct T_opthdr *)optptr;
4997 		toh->level = IPPROTO_IPV6;
4998 		toh->name = IPV6_HOPOPTS;
4999 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
5000 		toh->status = 0;
5001 		optptr += sizeof (*toh);
5002 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
5003 		optptr += ipp->ipp_hopoptslen;
5004 		ASSERT(OK_32PTR(optptr));
5005 		/* Save as last value */
5006 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
5007 		    (ipp->ipp_fields & IPPF_HOPOPTS),
5008 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
5009 	}
5010 	if (addflag.crb_ipv6_recvrthdrdstopts) {
5011 		toh = (struct T_opthdr *)optptr;
5012 		toh->level = IPPROTO_IPV6;
5013 		toh->name = IPV6_RTHDRDSTOPTS;
5014 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
5015 		toh->status = 0;
5016 		optptr += sizeof (*toh);
5017 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
5018 		optptr += ipp->ipp_rthdrdstoptslen;
5019 		ASSERT(OK_32PTR(optptr));
5020 		/* Save as last value */
5021 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
5022 		    &tcp->tcp_rthdrdstoptslen,
5023 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
5024 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
5025 	}
5026 	if (addflag.crb_ipv6_recvrthdr) {
5027 		toh = (struct T_opthdr *)optptr;
5028 		toh->level = IPPROTO_IPV6;
5029 		toh->name = IPV6_RTHDR;
5030 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
5031 		toh->status = 0;
5032 		optptr += sizeof (*toh);
5033 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
5034 		optptr += ipp->ipp_rthdrlen;
5035 		ASSERT(OK_32PTR(optptr));
5036 		/* Save as last value */
5037 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
5038 		    (ipp->ipp_fields & IPPF_RTHDR),
5039 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
5040 	}
5041 	if (addflag.crb_ipv6_recvdstopts) {
5042 		toh = (struct T_opthdr *)optptr;
5043 		toh->level = IPPROTO_IPV6;
5044 		toh->name = IPV6_DSTOPTS;
5045 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
5046 		toh->status = 0;
5047 		optptr += sizeof (*toh);
5048 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
5049 		optptr += ipp->ipp_dstoptslen;
5050 		ASSERT(OK_32PTR(optptr));
5051 		/* Save as last value */
5052 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
5053 		    (ipp->ipp_fields & IPPF_DSTOPTS),
5054 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
5055 	}
5056 	ASSERT(optptr == mp->b_wptr);
5057 	return (mp);
5058 }
5059 
5060 /* The minimum of smoothed mean deviation in RTO calculation. */
5061 #define	TCP_SD_MIN	400
5062 
5063 /*
5064  * Set RTO for this connection.  The formula is from Jacobson and Karels'
5065  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
5066  * are the same as those in Appendix A.2 of that paper.
5067  *
5068  * m = new measurement
5069  * sa = smoothed RTT average (8 * average estimates).
5070  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
5071  */
5072 static void
5073 tcp_set_rto(tcp_t *tcp, clock_t rtt)
5074 {
5075 	long m = TICK_TO_MSEC(rtt);
5076 	clock_t sa = tcp->tcp_rtt_sa;
5077 	clock_t sv = tcp->tcp_rtt_sd;
5078 	clock_t rto;
5079 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5080 
5081 	TCPS_BUMP_MIB(tcps, tcpRttUpdate);
5082 	tcp->tcp_rtt_update++;
5083 
5084 	/* tcp_rtt_sa is not 0 means this is a new sample. */
5085 	if (sa != 0) {
5086 		/*
5087 		 * Update average estimator:
5088 		 *	new rtt = 7/8 old rtt + 1/8 Error
5089 		 */
5090 
5091 		/* m is now Error in estimate. */
5092 		m -= sa >> 3;
5093 		if ((sa += m) <= 0) {
5094 			/*
5095 			 * Don't allow the smoothed average to be negative.
5096 			 * We use 0 to denote reinitialization of the
5097 			 * variables.
5098 			 */
5099 			sa = 1;
5100 		}
5101 
5102 		/*
5103 		 * Update deviation estimator:
5104 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
5105 		 */
5106 		if (m < 0)
5107 			m = -m;
5108 		m -= sv >> 2;
5109 		sv += m;
5110 	} else {
5111 		/*
5112 		 * This follows BSD's implementation.  So the reinitialized
5113 		 * RTO is 3 * m.  We cannot go less than 2 because if the
5114 		 * link is bandwidth dominated, doubling the window size
5115 		 * during slow start means doubling the RTT.  We want to be
5116 		 * more conservative when we reinitialize our estimates.  3
5117 		 * is just a convenient number.
5118 		 */
5119 		sa = m << 3;
5120 		sv = m << 1;
5121 	}
5122 	if (sv < TCP_SD_MIN) {
5123 		/*
5124 		 * We do not know that if sa captures the delay ACK
5125 		 * effect as in a long train of segments, a receiver
5126 		 * does not delay its ACKs.  So set the minimum of sv
5127 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
5128 		 * of BSD DATO.  That means the minimum of mean
5129 		 * deviation is 100 ms.
5130 		 *
5131 		 */
5132 		sv = TCP_SD_MIN;
5133 	}
5134 	tcp->tcp_rtt_sa = sa;
5135 	tcp->tcp_rtt_sd = sv;
5136 	/*
5137 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
5138 	 *
5139 	 * Add tcp_rexmit_interval extra in case of extreme environment
5140 	 * where the algorithm fails to work.  The default value of
5141 	 * tcp_rexmit_interval_extra should be 0.
5142 	 *
5143 	 * As we use a finer grained clock than BSD and update
5144 	 * RTO for every ACKs, add in another .25 of RTT to the
5145 	 * deviation of RTO to accomodate burstiness of 1/4 of
5146 	 * window size.
5147 	 */
5148 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
5149 
5150 	if (rto > tcps->tcps_rexmit_interval_max) {
5151 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
5152 	} else if (rto < tcps->tcps_rexmit_interval_min) {
5153 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
5154 	} else {
5155 		tcp->tcp_rto = rto;
5156 	}
5157 
5158 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
5159 	tcp->tcp_timer_backoff = 0;
5160 }
5161 
5162 /*
5163  * On a labeled system we have some protocols above TCP, such as RPC, which
5164  * appear to assume that every mblk in a chain has a db_credp.
5165  */
5166 static void
5167 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
5168 {
5169 	ASSERT(is_system_labeled());
5170 	ASSERT(ira->ira_cred != NULL);
5171 
5172 	while (mp != NULL) {
5173 		mblk_setcred(mp, ira->ira_cred, NOPID);
5174 		mp = mp->b_cont;
5175 	}
5176 }
5177 
5178 uint_t
5179 tcp_rwnd_reopen(tcp_t *tcp)
5180 {
5181 	uint_t ret = 0;
5182 	uint_t thwin;
5183 	conn_t *connp = tcp->tcp_connp;
5184 
5185 	/* Learn the latest rwnd information that we sent to the other side. */
5186 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
5187 	    << tcp->tcp_rcv_ws;
5188 	/* This is peer's calculated send window (our receive window). */
5189 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
5190 	/*
5191 	 * Increase the receive window to max.  But we need to do receiver
5192 	 * SWS avoidance.  This means that we need to check the increase of
5193 	 * of receive window is at least 1 MSS.
5194 	 */
5195 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
5196 		/*
5197 		 * If the window that the other side knows is less than max
5198 		 * deferred acks segments, send an update immediately.
5199 		 */
5200 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
5201 			TCPS_BUMP_MIB(tcp->tcp_tcps, tcpOutWinUpdate);
5202 			ret = TH_ACK_NEEDED;
5203 		}
5204 		tcp->tcp_rwnd = connp->conn_rcvbuf;
5205 	}
5206 	return (ret);
5207 }
5208 
5209 /*
5210  * Handle a packet that has been reclassified by TCP.
5211  * This function drops the ref on connp that the caller had.
5212  */
5213 void
5214 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
5215 {
5216 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5217 
5218 	if (connp->conn_incoming_ifindex != 0 &&
5219 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
5220 		freemsg(mp);
5221 		CONN_DEC_REF(connp);
5222 		return;
5223 	}
5224 
5225 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
5226 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
5227 		ip6_t *ip6h;
5228 		ipha_t *ipha;
5229 
5230 		if (ira->ira_flags & IRAF_IS_IPV4) {
5231 			ipha = (ipha_t *)mp->b_rptr;
5232 			ip6h = NULL;
5233 		} else {
5234 			ipha = NULL;
5235 			ip6h = (ip6_t *)mp->b_rptr;
5236 		}
5237 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
5238 		if (mp == NULL) {
5239 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
5240 			/* Note that mp is NULL */
5241 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
5242 			CONN_DEC_REF(connp);
5243 			return;
5244 		}
5245 	}
5246 
5247 	if (IPCL_IS_TCP(connp)) {
5248 		/*
5249 		 * do not drain, certain use cases can blow
5250 		 * the stack
5251 		 */
5252 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
5253 		    connp->conn_recv, connp, ira,
5254 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
5255 	} else {
5256 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
5257 		(connp->conn_recv)(connp, mp, NULL,
5258 		    ira);
5259 		CONN_DEC_REF(connp);
5260 	}
5261 
5262 }
5263 
5264 /* ARGSUSED */
5265 static void
5266 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5267 {
5268 	conn_t	*connp = (conn_t *)arg;
5269 	tcp_t	*tcp = connp->conn_tcp;
5270 	queue_t	*q = connp->conn_rq;
5271 
5272 	ASSERT(!IPCL_IS_NONSTR(connp));
5273 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
5274 	tcp->tcp_rsrv_mp = mp;
5275 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
5276 
5277 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
5278 		return;
5279 	}
5280 
5281 	if (tcp->tcp_fused) {
5282 		tcp_fuse_backenable(tcp);
5283 		return;
5284 	}
5285 
5286 	if (canputnext(q)) {
5287 		/* Not flow-controlled, open rwnd */
5288 		tcp->tcp_rwnd = connp->conn_rcvbuf;
5289 
5290 		/*
5291 		 * Send back a window update immediately if TCP is above
5292 		 * ESTABLISHED state and the increase of the rcv window
5293 		 * that the other side knows is at least 1 MSS after flow
5294 		 * control is lifted.
5295 		 */
5296 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
5297 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
5298 			tcp_xmit_ctl(NULL, tcp,
5299 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
5300 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
5301 		}
5302 	}
5303 }
5304 
5305 /*
5306  * The read side service routine is called mostly when we get back-enabled as a
5307  * result of flow control relief.  Since we don't actually queue anything in
5308  * TCP, we have no data to send out of here.  What we do is clear the receive
5309  * window, and send out a window update.
5310  */
5311 void
5312 tcp_rsrv(queue_t *q)
5313 {
5314 	conn_t		*connp = Q_TO_CONN(q);
5315 	tcp_t		*tcp = connp->conn_tcp;
5316 	mblk_t		*mp;
5317 
5318 	/* No code does a putq on the read side */
5319 	ASSERT(q->q_first == NULL);
5320 
5321 	/*
5322 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
5323 	 * been run.  So just return.
5324 	 */
5325 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
5326 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
5327 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
5328 		return;
5329 	}
5330 	tcp->tcp_rsrv_mp = NULL;
5331 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
5332 
5333 	CONN_INC_REF(connp);
5334 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
5335 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
5336 }
5337 
5338 /* At minimum we need 8 bytes in the TCP header for the lookup */
5339 #define	ICMP_MIN_TCP_HDR	8
5340 
5341 /*
5342  * tcp_icmp_input is called as conn_recvicmp to process ICMP error messages
5343  * passed up by IP. The message is always received on the correct tcp_t.
5344  * Assumes that IP has pulled up everything up to and including the ICMP header.
5345  */
5346 /* ARGSUSED2 */
5347 void
5348 tcp_icmp_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
5349 {
5350 	conn_t		*connp = (conn_t *)arg1;
5351 	icmph_t		*icmph;
5352 	ipha_t		*ipha;
5353 	int		iph_hdr_length;
5354 	tcpha_t		*tcpha;
5355 	uint32_t	seg_seq;
5356 	tcp_t		*tcp = connp->conn_tcp;
5357 
5358 	/* Assume IP provides aligned packets */
5359 	ASSERT(OK_32PTR(mp->b_rptr));
5360 	ASSERT((MBLKL(mp) >= sizeof (ipha_t)));
5361 
5362 	/*
5363 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
5364 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
5365 	 */
5366 	if (!(ira->ira_flags & IRAF_IS_IPV4)) {
5367 		tcp_icmp_error_ipv6(tcp, mp, ira);
5368 		return;
5369 	}
5370 
5371 	/* Skip past the outer IP and ICMP headers */
5372 	iph_hdr_length = ira->ira_ip_hdr_length;
5373 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
5374 	/*
5375 	 * If we don't have the correct outer IP header length
5376 	 * or if we don't have a complete inner IP header
5377 	 * drop it.
5378 	 */
5379 	if (iph_hdr_length < sizeof (ipha_t) ||
5380 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
5381 noticmpv4:
5382 		freemsg(mp);
5383 		return;
5384 	}
5385 	ipha = (ipha_t *)&icmph[1];
5386 
5387 	/* Skip past the inner IP and find the ULP header */
5388 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
5389 	tcpha = (tcpha_t *)((char *)ipha + iph_hdr_length);
5390 	/*
5391 	 * If we don't have the correct inner IP header length or if the ULP
5392 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
5393 	 * bytes of TCP header, drop it.
5394 	 */
5395 	if (iph_hdr_length < sizeof (ipha_t) ||
5396 	    ipha->ipha_protocol != IPPROTO_TCP ||
5397 	    (uchar_t *)tcpha + ICMP_MIN_TCP_HDR > mp->b_wptr) {
5398 		goto noticmpv4;
5399 	}
5400 
5401 	seg_seq = ntohl(tcpha->tha_seq);
5402 	switch (icmph->icmph_type) {
5403 	case ICMP_DEST_UNREACHABLE:
5404 		switch (icmph->icmph_code) {
5405 		case ICMP_FRAGMENTATION_NEEDED:
5406 			/*
5407 			 * Update Path MTU, then try to send something out.
5408 			 */
5409 			tcp_update_pmtu(tcp, B_TRUE);
5410 			tcp_rexmit_after_error(tcp);
5411 			break;
5412 		case ICMP_PORT_UNREACHABLE:
5413 		case ICMP_PROTOCOL_UNREACHABLE:
5414 			switch (tcp->tcp_state) {
5415 			case TCPS_SYN_SENT:
5416 			case TCPS_SYN_RCVD:
5417 				/*
5418 				 * ICMP can snipe away incipient
5419 				 * TCP connections as long as
5420 				 * seq number is same as initial
5421 				 * send seq number.
5422 				 */
5423 				if (seg_seq == tcp->tcp_iss) {
5424 					(void) tcp_clean_death(tcp,
5425 					    ECONNREFUSED);
5426 				}
5427 				break;
5428 			}
5429 			break;
5430 		case ICMP_HOST_UNREACHABLE:
5431 		case ICMP_NET_UNREACHABLE:
5432 			/* Record the error in case we finally time out. */
5433 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
5434 				tcp->tcp_client_errno = EHOSTUNREACH;
5435 			else
5436 				tcp->tcp_client_errno = ENETUNREACH;
5437 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
5438 				if (tcp->tcp_listener != NULL &&
5439 				    tcp->tcp_listener->tcp_syn_defense) {
5440 					/*
5441 					 * Ditch the half-open connection if we
5442 					 * suspect a SYN attack is under way.
5443 					 */
5444 					(void) tcp_clean_death(tcp,
5445 					    tcp->tcp_client_errno);
5446 				}
5447 			}
5448 			break;
5449 		default:
5450 			break;
5451 		}
5452 		break;
5453 	case ICMP_SOURCE_QUENCH: {
5454 		/*
5455 		 * use a global boolean to control
5456 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
5457 		 * The default is false.
5458 		 */
5459 		if (tcp_icmp_source_quench) {
5460 			/*
5461 			 * Reduce the sending rate as if we got a
5462 			 * retransmit timeout
5463 			 */
5464 			uint32_t npkt;
5465 
5466 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
5467 			    tcp->tcp_mss;
5468 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
5469 			tcp->tcp_cwnd = tcp->tcp_mss;
5470 			tcp->tcp_cwnd_cnt = 0;
5471 		}
5472 		break;
5473 	}
5474 	}
5475 	freemsg(mp);
5476 }
5477 
5478 /*
5479  * tcp_icmp_error_ipv6 is called from tcp_icmp_input to process ICMPv6
5480  * error messages passed up by IP.
5481  * Assumes that IP has pulled up all the extension headers as well
5482  * as the ICMPv6 header.
5483  */
5484 static void
5485 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, ip_recv_attr_t *ira)
5486 {
5487 	icmp6_t		*icmp6;
5488 	ip6_t		*ip6h;
5489 	uint16_t	iph_hdr_length = ira->ira_ip_hdr_length;
5490 	tcpha_t		*tcpha;
5491 	uint8_t		*nexthdrp;
5492 	uint32_t	seg_seq;
5493 
5494 	/*
5495 	 * Verify that we have a complete IP header.
5496 	 */
5497 	ASSERT((MBLKL(mp) >= sizeof (ip6_t)));
5498 
5499 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
5500 	ip6h = (ip6_t *)&icmp6[1];
5501 	/*
5502 	 * Verify if we have a complete ICMP and inner IP header.
5503 	 */
5504 	if ((uchar_t *)&ip6h[1] > mp->b_wptr) {
5505 noticmpv6:
5506 		freemsg(mp);
5507 		return;
5508 	}
5509 
5510 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
5511 		goto noticmpv6;
5512 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
5513 	/*
5514 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
5515 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
5516 	 * packet.
5517 	 */
5518 	if ((*nexthdrp != IPPROTO_TCP) ||
5519 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
5520 		goto noticmpv6;
5521 	}
5522 
5523 	seg_seq = ntohl(tcpha->tha_seq);
5524 	switch (icmp6->icmp6_type) {
5525 	case ICMP6_PACKET_TOO_BIG:
5526 		/*
5527 		 * Update Path MTU, then try to send something out.
5528 		 */
5529 		tcp_update_pmtu(tcp, B_TRUE);
5530 		tcp_rexmit_after_error(tcp);
5531 		break;
5532 	case ICMP6_DST_UNREACH:
5533 		switch (icmp6->icmp6_code) {
5534 		case ICMP6_DST_UNREACH_NOPORT:
5535 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
5536 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
5537 			    (seg_seq == tcp->tcp_iss)) {
5538 				(void) tcp_clean_death(tcp, ECONNREFUSED);
5539 			}
5540 			break;
5541 		case ICMP6_DST_UNREACH_ADMIN:
5542 		case ICMP6_DST_UNREACH_NOROUTE:
5543 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
5544 		case ICMP6_DST_UNREACH_ADDR:
5545 			/* Record the error in case we finally time out. */
5546 			tcp->tcp_client_errno = EHOSTUNREACH;
5547 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
5548 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
5549 			    (seg_seq == tcp->tcp_iss)) {
5550 				if (tcp->tcp_listener != NULL &&
5551 				    tcp->tcp_listener->tcp_syn_defense) {
5552 					/*
5553 					 * Ditch the half-open connection if we
5554 					 * suspect a SYN attack is under way.
5555 					 */
5556 					(void) tcp_clean_death(tcp,
5557 					    tcp->tcp_client_errno);
5558 				}
5559 			}
5560 
5561 
5562 			break;
5563 		default:
5564 			break;
5565 		}
5566 		break;
5567 	case ICMP6_PARAM_PROB:
5568 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
5569 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
5570 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
5571 		    (uchar_t *)nexthdrp) {
5572 			if (tcp->tcp_state == TCPS_SYN_SENT ||
5573 			    tcp->tcp_state == TCPS_SYN_RCVD) {
5574 				(void) tcp_clean_death(tcp, ECONNREFUSED);
5575 			}
5576 			break;
5577 		}
5578 		break;
5579 
5580 	case ICMP6_TIME_EXCEEDED:
5581 	default:
5582 		break;
5583 	}
5584 	freemsg(mp);
5585 }
5586 
5587 /*
5588  * CALLED OUTSIDE OF SQUEUE! It can not follow any pointers that tcp might
5589  * change. But it can refer to fields like tcp_suna and tcp_snxt.
5590  *
5591  * Function tcp_verifyicmp is called as conn_verifyicmp to verify the ICMP
5592  * error messages received by IP. The message is always received on the correct
5593  * tcp_t.
5594  */
5595 /* ARGSUSED */
5596 boolean_t
5597 tcp_verifyicmp(conn_t *connp, void *arg2, icmph_t *icmph, icmp6_t *icmp6,
5598     ip_recv_attr_t *ira)
5599 {
5600 	tcpha_t		*tcpha = (tcpha_t *)arg2;
5601 	uint32_t	seq = ntohl(tcpha->tha_seq);
5602 	tcp_t		*tcp = connp->conn_tcp;
5603 
5604 	/*
5605 	 * TCP sequence number contained in payload of the ICMP error message
5606 	 * should be within the range SND.UNA <= SEG.SEQ < SND.NXT. Otherwise,
5607 	 * the message is either a stale ICMP error, or an attack from the
5608 	 * network. Fail the verification.
5609 	 */
5610 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
5611 		return (B_FALSE);
5612 
5613 	/* For "too big" we also check the ignore flag */
5614 	if (ira->ira_flags & IRAF_IS_IPV4) {
5615 		ASSERT(icmph != NULL);
5616 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
5617 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
5618 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
5619 			return (B_FALSE);
5620 	} else {
5621 		ASSERT(icmp6 != NULL);
5622 		if (icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG &&
5623 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
5624 			return (B_FALSE);
5625 	}
5626 	return (B_TRUE);
5627 }
5628