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