xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp_output.c (revision ab82c29b6e890d0f1241f9cd0cefda3430f46bd5)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2014, 2017 by Delphix. All rights reserved.
25  * Copyright 2019 Joyent, Inc.
26  */
27 
28 /* This file contains all TCP output processing functions. */
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/strsun.h>
33 #include <sys/strsubr.h>
34 #include <sys/stropts.h>
35 #include <sys/strlog.h>
36 #define	_SUN_TPI_VERSION 2
37 #include <sys/tihdr.h>
38 #include <sys/suntpi.h>
39 #include <sys/xti_inet.h>
40 #include <sys/timod.h>
41 #include <sys/pattr.h>
42 #include <sys/squeue_impl.h>
43 #include <sys/squeue.h>
44 #include <sys/sockio.h>
45 #include <sys/tsol/tnet.h>
46 
47 #include <inet/common.h>
48 #include <inet/ip.h>
49 #include <inet/tcp.h>
50 #include <inet/tcp_impl.h>
51 #include <inet/snmpcom.h>
52 #include <inet/proto_set.h>
53 #include <inet/ipsec_impl.h>
54 #include <inet/ip_ndp.h>
55 
56 static mblk_t	*tcp_get_seg_mp(tcp_t *, uint32_t, int32_t *);
57 static void	tcp_wput_cmdblk(queue_t *, mblk_t *);
58 static void	tcp_wput_flush(tcp_t *, mblk_t *);
59 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
60 static int	tcp_xmit_end(tcp_t *);
61 static int	tcp_send(tcp_t *, const int, const int, const int,
62 		    const int, int *, uint32_t *, int *, mblk_t **, mblk_t *);
63 static void	tcp_xmit_early_reset(char *, mblk_t *, uint32_t, uint32_t,
64 		    int, ip_recv_attr_t *, ip_stack_t *, conn_t *);
65 static boolean_t	tcp_send_rst_chk(tcp_stack_t *);
66 static void	tcp_process_shrunk_swnd(tcp_t *, uint32_t);
67 static void	tcp_fill_header(tcp_t *, uchar_t *, int);
68 
69 /*
70  * Functions called directly via squeue having a prototype of edesc_t.
71  */
72 static void	tcp_wput_nondata(void *, mblk_t *, void *, ip_recv_attr_t *);
73 static void	tcp_wput_ioctl(void *, mblk_t *, void *, ip_recv_attr_t *);
74 static void	tcp_wput_proto(void *, mblk_t *, void *, ip_recv_attr_t *);
75 
76 /*
77  * This controls how tiny a write must be before we try to copy it
78  * into the mblk on the tail of the transmit queue.  Not much
79  * speedup is observed for values larger than sixteen.  Zero will
80  * disable the optimisation.
81  */
82 static int tcp_tx_pull_len = 16;
83 
84 static void
85 cc_after_idle(tcp_t *tcp)
86 {
87 	uint32_t old_cwnd = tcp->tcp_cwnd;
88 
89 	if (CC_ALGO(tcp)->after_idle != NULL)
90 		CC_ALGO(tcp)->after_idle(&tcp->tcp_ccv);
91 
92 	DTRACE_PROBE3(cwnd__cc__after__idle, tcp_t *, tcp, uint32_t, old_cwnd,
93 	    uint32_t, tcp->tcp_cwnd);
94 }
95 
96 int
97 tcp_wput(queue_t *q, mblk_t *mp)
98 {
99 	conn_t	*connp = Q_TO_CONN(q);
100 	tcp_t	*tcp;
101 	void (*output_proc)();
102 	t_scalar_t type;
103 	uchar_t *rptr;
104 	struct iocblk	*iocp;
105 	size_t size;
106 
107 	ASSERT(connp->conn_ref >= 2);
108 
109 	switch (DB_TYPE(mp)) {
110 	case M_DATA:
111 		tcp = connp->conn_tcp;
112 		ASSERT(tcp != NULL);
113 
114 		size = msgdsize(mp);
115 
116 		mutex_enter(&tcp->tcp_non_sq_lock);
117 		tcp->tcp_squeue_bytes += size;
118 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
119 			tcp_setqfull(tcp);
120 		}
121 		mutex_exit(&tcp->tcp_non_sq_lock);
122 
123 		CONN_INC_REF(connp);
124 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
125 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
126 		return (0);
127 
128 	case M_CMD:
129 		tcp_wput_cmdblk(q, mp);
130 		return (0);
131 
132 	case M_PROTO:
133 	case M_PCPROTO:
134 		/*
135 		 * if it is a snmp message, don't get behind the squeue
136 		 */
137 		tcp = connp->conn_tcp;
138 		rptr = mp->b_rptr;
139 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
140 			type = ((union T_primitives *)rptr)->type;
141 		} else {
142 			if (connp->conn_debug) {
143 				(void) strlog(TCP_MOD_ID, 0, 1,
144 				    SL_ERROR|SL_TRACE,
145 				    "tcp_wput_proto, dropping one...");
146 			}
147 			freemsg(mp);
148 			return (0);
149 		}
150 		if (type == T_SVR4_OPTMGMT_REQ) {
151 			/*
152 			 * All Solaris components should pass a db_credp
153 			 * for this TPI message, hence we ASSERT.
154 			 * But in case there is some other M_PROTO that looks
155 			 * like a TPI message sent by some other kernel
156 			 * component, we check and return an error.
157 			 */
158 			cred_t	*cr = msg_getcred(mp, NULL);
159 
160 			ASSERT(cr != NULL);
161 			if (cr == NULL) {
162 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
163 				return (0);
164 			}
165 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
166 			    cr)) {
167 				/*
168 				 * This was a SNMP request
169 				 */
170 				return (0);
171 			} else {
172 				output_proc = tcp_wput_proto;
173 			}
174 		} else {
175 			output_proc = tcp_wput_proto;
176 		}
177 		break;
178 	case M_IOCTL:
179 		/*
180 		 * Most ioctls can be processed right away without going via
181 		 * squeues - process them right here. Those that do require
182 		 * squeue (currently _SIOCSOCKFALLBACK)
183 		 * are processed by tcp_wput_ioctl().
184 		 */
185 		iocp = (struct iocblk *)mp->b_rptr;
186 		tcp = connp->conn_tcp;
187 
188 		switch (iocp->ioc_cmd) {
189 		case TCP_IOC_ABORT_CONN:
190 			tcp_ioctl_abort_conn(q, mp);
191 			return (0);
192 		case TI_GETPEERNAME:
193 		case TI_GETMYNAME:
194 			mi_copyin(q, mp, NULL,
195 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
196 			return (0);
197 
198 		default:
199 			output_proc = tcp_wput_ioctl;
200 			break;
201 		}
202 		break;
203 	default:
204 		output_proc = tcp_wput_nondata;
205 		break;
206 	}
207 
208 	CONN_INC_REF(connp);
209 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
210 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
211 	return (0);
212 }
213 
214 /*
215  * The TCP normal data output path.
216  * NOTE: the logic of the fast path is duplicated from this function.
217  */
218 void
219 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
220 {
221 	int		len;
222 	mblk_t		*local_time;
223 	mblk_t		*mp1;
224 	uint32_t	snxt;
225 	int		tail_unsent;
226 	int		tcpstate;
227 	int		usable = 0;
228 	mblk_t		*xmit_tail;
229 	int32_t		mss;
230 	int32_t		num_sack_blk = 0;
231 	int32_t		total_hdr_len;
232 	int32_t		tcp_hdr_len;
233 	int		rc;
234 	conn_t		*connp = tcp->tcp_connp;
235 	clock_t		now = LBOLT_FASTPATH;
236 
237 	tcpstate = tcp->tcp_state;
238 	if (mp == NULL) {
239 		/*
240 		 * tcp_wput_data() with NULL mp should only be called when
241 		 * there is unsent data.
242 		 */
243 		ASSERT(tcp->tcp_unsent > 0);
244 		/* Really tacky... but we need this for detached closes. */
245 		len = tcp->tcp_unsent;
246 		goto data_null;
247 	}
248 
249 	ASSERT(mp->b_datap->db_type == M_DATA);
250 	/*
251 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
252 	 * or before a connection attempt has begun.
253 	 */
254 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
255 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
256 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
257 #ifdef DEBUG
258 			cmn_err(CE_WARN,
259 			    "tcp_wput_data: data after ordrel, %s",
260 			    tcp_display(tcp, NULL,
261 			    DISP_ADDR_AND_PORT));
262 #else
263 			if (connp->conn_debug) {
264 				(void) strlog(TCP_MOD_ID, 0, 1,
265 				    SL_TRACE|SL_ERROR,
266 				    "tcp_wput_data: data after ordrel, %s\n",
267 				    tcp_display(tcp, NULL,
268 				    DISP_ADDR_AND_PORT));
269 			}
270 #endif /* DEBUG */
271 		}
272 		if (tcp->tcp_snd_zcopy_aware &&
273 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
274 			tcp_zcopy_notify(tcp);
275 		freemsg(mp);
276 		mutex_enter(&tcp->tcp_non_sq_lock);
277 		if (tcp->tcp_flow_stopped &&
278 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
279 			tcp_clrqfull(tcp);
280 		}
281 		mutex_exit(&tcp->tcp_non_sq_lock);
282 		return;
283 	}
284 
285 	/* Strip empties */
286 	for (;;) {
287 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
288 		    (uintptr_t)INT_MAX);
289 		len = (int)(mp->b_wptr - mp->b_rptr);
290 		if (len > 0)
291 			break;
292 		mp1 = mp;
293 		mp = mp->b_cont;
294 		freeb(mp1);
295 		if (mp == NULL) {
296 			return;
297 		}
298 	}
299 
300 	/* If we are the first on the list ... */
301 	if (tcp->tcp_xmit_head == NULL) {
302 		tcp->tcp_xmit_head = mp;
303 		tcp->tcp_xmit_tail = mp;
304 		tcp->tcp_xmit_tail_unsent = len;
305 	} else {
306 		/* If tiny tx and room in txq tail, pullup to save mblks. */
307 		struct datab *dp;
308 
309 		mp1 = tcp->tcp_xmit_last;
310 		if (len < tcp_tx_pull_len &&
311 		    (dp = mp1->b_datap)->db_ref == 1 &&
312 		    dp->db_lim - mp1->b_wptr >= len) {
313 			ASSERT(len > 0);
314 			ASSERT(!mp1->b_cont);
315 			if (len == 1) {
316 				*mp1->b_wptr++ = *mp->b_rptr;
317 			} else {
318 				bcopy(mp->b_rptr, mp1->b_wptr, len);
319 				mp1->b_wptr += len;
320 			}
321 			if (mp1 == tcp->tcp_xmit_tail)
322 				tcp->tcp_xmit_tail_unsent += len;
323 			mp1->b_cont = mp->b_cont;
324 			if (tcp->tcp_snd_zcopy_aware &&
325 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
326 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
327 			freeb(mp);
328 			mp = mp1;
329 		} else {
330 			tcp->tcp_xmit_last->b_cont = mp;
331 		}
332 		len += tcp->tcp_unsent;
333 	}
334 
335 	/* Tack on however many more positive length mblks we have */
336 	if ((mp1 = mp->b_cont) != NULL) {
337 		do {
338 			int tlen;
339 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
340 			    (uintptr_t)INT_MAX);
341 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
342 			if (tlen <= 0) {
343 				mp->b_cont = mp1->b_cont;
344 				freeb(mp1);
345 			} else {
346 				len += tlen;
347 				mp = mp1;
348 			}
349 		} while ((mp1 = mp->b_cont) != NULL);
350 	}
351 	tcp->tcp_xmit_last = mp;
352 	tcp->tcp_unsent = len;
353 
354 	if (urgent)
355 		usable = 1;
356 
357 data_null:
358 	snxt = tcp->tcp_snxt;
359 	xmit_tail = tcp->tcp_xmit_tail;
360 	tail_unsent = tcp->tcp_xmit_tail_unsent;
361 
362 	/*
363 	 * Note that tcp_mss has been adjusted to take into account the
364 	 * timestamp option if applicable.  Because SACK options do not
365 	 * appear in every TCP segments and they are of variable lengths,
366 	 * they cannot be included in tcp_mss.  Thus we need to calculate
367 	 * the actual segment length when we need to send a segment which
368 	 * includes SACK options.
369 	 */
370 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
371 		int32_t	opt_len;
372 
373 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
374 		    tcp->tcp_num_sack_blk);
375 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
376 		    2 + TCPOPT_HEADER_LEN;
377 		mss = tcp->tcp_mss - opt_len;
378 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
379 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
380 	} else {
381 		mss = tcp->tcp_mss;
382 		total_hdr_len = connp->conn_ht_iphc_len;
383 		tcp_hdr_len = connp->conn_ht_ulp_len;
384 	}
385 
386 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
387 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
388 		cc_after_idle(tcp);
389 	}
390 	if (tcpstate == TCPS_SYN_RCVD) {
391 		/*
392 		 * The three-way connection establishment handshake is not
393 		 * complete yet. We want to queue the data for transmission
394 		 * after entering ESTABLISHED state (RFC793). A jump to
395 		 * "done" label effectively leaves data on the queue.
396 		 */
397 		goto done;
398 	} else {
399 		int usable_r;
400 
401 		/*
402 		 * In the special case when cwnd is zero, which can only
403 		 * happen if the connection is ECN capable, return now.
404 		 * New segments is sent using tcp_timer().  The timer
405 		 * is set in tcp_input_data().
406 		 */
407 		if (tcp->tcp_cwnd == 0) {
408 			/*
409 			 * Note that tcp_cwnd is 0 before 3-way handshake is
410 			 * finished.
411 			 */
412 			ASSERT(tcp->tcp_ecn_ok ||
413 			    tcp->tcp_state < TCPS_ESTABLISHED);
414 			return;
415 		}
416 
417 		/* NOTE: trouble if xmitting while SYN not acked? */
418 		usable_r = snxt - tcp->tcp_suna;
419 		usable_r = tcp->tcp_swnd - usable_r;
420 
421 		/*
422 		 * Check if the receiver has shrunk the window.  If
423 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
424 		 * cannot be set as there is unsent data, so FIN cannot
425 		 * be sent out.  Otherwise, we need to take into account
426 		 * of FIN as it consumes an "invisible" sequence number.
427 		 */
428 		ASSERT(tcp->tcp_fin_sent == 0);
429 		if (usable_r < 0) {
430 			/*
431 			 * The receiver has shrunk the window and we have sent
432 			 * -usable_r date beyond the window, re-adjust.
433 			 *
434 			 * If TCP window scaling is enabled, there can be
435 			 * round down error as the advertised receive window
436 			 * is actually right shifted n bits.  This means that
437 			 * the lower n bits info is wiped out.  It will look
438 			 * like the window is shrunk.  Do a check here to
439 			 * see if the shrunk amount is actually within the
440 			 * error in window calculation.  If it is, just
441 			 * return.  Note that this check is inside the
442 			 * shrunk window check.  This makes sure that even
443 			 * though tcp_process_shrunk_swnd() is not called,
444 			 * we will stop further processing.
445 			 */
446 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
447 				tcp_process_shrunk_swnd(tcp, -usable_r);
448 			}
449 			return;
450 		}
451 
452 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
453 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
454 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
455 
456 		/* usable = MIN(usable, unsent) */
457 		if (usable_r > len)
458 			usable_r = len;
459 
460 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
461 		if (usable_r > 0) {
462 			usable = usable_r;
463 		} else {
464 			/* Bypass all other unnecessary processing. */
465 			goto done;
466 		}
467 	}
468 
469 	local_time = (mblk_t *)(intptr_t)gethrtime();
470 
471 	/*
472 	 * "Our" Nagle Algorithm.  This is not the same as in the old
473 	 * BSD.  This is more in line with the true intent of Nagle.
474 	 *
475 	 * The conditions are:
476 	 * 1. The amount of unsent data (or amount of data which can be
477 	 *    sent, whichever is smaller) is less than Nagle limit.
478 	 * 2. The last sent size is also less than Nagle limit.
479 	 * 3. There is unack'ed data.
480 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
481 	 *    Nagle algorithm.  This reduces the probability that urgent
482 	 *    bytes get "merged" together.
483 	 * 5. The app has not closed the connection.  This eliminates the
484 	 *    wait time of the receiving side waiting for the last piece of
485 	 *    (small) data.
486 	 *
487 	 * If all are satisified, exit without sending anything.  Note
488 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
489 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
490 	 * 4095).
491 	 */
492 	if (usable < (int)tcp->tcp_naglim &&
493 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
494 	    snxt != tcp->tcp_suna &&
495 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
496 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
497 		goto done;
498 	}
499 
500 	/*
501 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
502 	 * is set, then we have to force TCP not to send partial segment
503 	 * (smaller than MSS bytes). We are calculating the usable now
504 	 * based on full mss and will save the rest of remaining data for
505 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
506 	 * something to do zero window probe.
507 	 */
508 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
509 		if (usable < mss)
510 			goto done;
511 		usable = (usable / mss) * mss;
512 	}
513 
514 	/* Update the latest receive window size in TCP header. */
515 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
516 
517 	/* Send the packet. */
518 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
519 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
520 	    local_time);
521 
522 	/* Pretend that all we were trying to send really got sent */
523 	if (rc < 0 && tail_unsent < 0) {
524 		do {
525 			xmit_tail = xmit_tail->b_cont;
526 			xmit_tail->b_prev = local_time;
527 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
528 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
529 			tail_unsent += (int)(xmit_tail->b_wptr -
530 			    xmit_tail->b_rptr);
531 		} while (tail_unsent < 0);
532 	}
533 done:;
534 	tcp->tcp_xmit_tail = xmit_tail;
535 	tcp->tcp_xmit_tail_unsent = tail_unsent;
536 	len = tcp->tcp_snxt - snxt;
537 	if (len) {
538 		/*
539 		 * If new data was sent, need to update the notsack
540 		 * list, which is, afterall, data blocks that have
541 		 * not been sack'ed by the receiver.  New data is
542 		 * not sack'ed.
543 		 */
544 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
545 			/* len is a negative value. */
546 			tcp->tcp_pipe -= len;
547 			tcp_notsack_update(&(tcp->tcp_notsack_list),
548 			    tcp->tcp_snxt, snxt,
549 			    &(tcp->tcp_num_notsack_blk),
550 			    &(tcp->tcp_cnt_notsack_list));
551 		}
552 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
553 		tcp->tcp_rack = tcp->tcp_rnxt;
554 		tcp->tcp_rack_cnt = 0;
555 		if ((snxt + len) == tcp->tcp_suna) {
556 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
557 		}
558 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
559 		/*
560 		 * Didn't send anything. Make sure the timer is running
561 		 * so that we will probe a zero window.
562 		 */
563 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
564 	}
565 	/* Note that len is the amount we just sent but with a negative sign */
566 	tcp->tcp_unsent += len;
567 	mutex_enter(&tcp->tcp_non_sq_lock);
568 	if (tcp->tcp_flow_stopped) {
569 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
570 			tcp_clrqfull(tcp);
571 		}
572 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
573 		if (!(tcp->tcp_detached))
574 			tcp_setqfull(tcp);
575 	}
576 	mutex_exit(&tcp->tcp_non_sq_lock);
577 }
578 
579 /*
580  * Initial STREAMS write side put() procedure for sockets. It tries to
581  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
582  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
583  * are handled by tcp_wput() as usual.
584  *
585  * All further messages will also be handled by tcp_wput() because we cannot
586  * be sure that the above short cut is safe later.
587  */
588 int
589 tcp_wput_sock(queue_t *wq, mblk_t *mp)
590 {
591 	conn_t			*connp = Q_TO_CONN(wq);
592 	tcp_t			*tcp = connp->conn_tcp;
593 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
594 
595 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
596 	wq->q_qinfo = &tcp_winit;
597 
598 	ASSERT(IPCL_IS_TCP(connp));
599 	ASSERT(TCP_IS_SOCKET(tcp));
600 
601 	if (DB_TYPE(mp) == M_PCPROTO &&
602 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
603 	    car->PRIM_type == T_CAPABILITY_REQ) {
604 		tcp_capability_req(tcp, mp);
605 		return (0);
606 	}
607 
608 	tcp_wput(wq, mp);
609 	return (0);
610 }
611 
612 /* ARGSUSED */
613 int
614 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
615 {
616 #ifdef DEBUG
617 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
618 #endif
619 	freemsg(mp);
620 	return (0);
621 }
622 
623 /*
624  * Call by tcp_wput() to handle misc non M_DATA messages.
625  */
626 /* ARGSUSED */
627 static void
628 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
629 {
630 	conn_t	*connp = (conn_t *)arg;
631 	tcp_t	*tcp = connp->conn_tcp;
632 
633 	ASSERT(DB_TYPE(mp) != M_IOCTL);
634 	/*
635 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
636 	 * Once the close starts, streamhead and sockfs will not let any data
637 	 * packets come down (close ensures that there are no threads using the
638 	 * queue and no new threads will come down) but since qprocsoff()
639 	 * hasn't happened yet, a M_FLUSH or some non data message might
640 	 * get reflected back (in response to our own FLUSHRW) and get
641 	 * processed after tcp_close() is done. The conn would still be valid
642 	 * because a ref would have added but we need to check the state
643 	 * before actually processing the packet.
644 	 */
645 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
646 		freemsg(mp);
647 		return;
648 	}
649 
650 	switch (DB_TYPE(mp)) {
651 	case M_IOCDATA:
652 		tcp_wput_iocdata(tcp, mp);
653 		break;
654 	case M_FLUSH:
655 		tcp_wput_flush(tcp, mp);
656 		break;
657 	default:
658 		ip_wput_nondata(connp->conn_wq, mp);
659 		break;
660 	}
661 }
662 
663 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
664 static void
665 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
666 {
667 	uchar_t	fval = *mp->b_rptr;
668 	mblk_t	*tail;
669 	conn_t	*connp = tcp->tcp_connp;
670 	queue_t	*q = connp->conn_wq;
671 
672 	/* TODO: How should flush interact with urgent data? */
673 	if ((fval & FLUSHW) && tcp->tcp_xmit_head != NULL &&
674 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
675 		/*
676 		 * Flush only data that has not yet been put on the wire.  If
677 		 * we flush data that we have already transmitted, life, as we
678 		 * know it, may come to an end.
679 		 */
680 		tail = tcp->tcp_xmit_tail;
681 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
682 		tcp->tcp_xmit_tail_unsent = 0;
683 		tcp->tcp_unsent = 0;
684 		if (tail->b_wptr != tail->b_rptr)
685 			tail = tail->b_cont;
686 		if (tail) {
687 			mblk_t **excess = &tcp->tcp_xmit_head;
688 			for (;;) {
689 				mblk_t *mp1 = *excess;
690 				if (mp1 == tail)
691 					break;
692 				tcp->tcp_xmit_tail = mp1;
693 				tcp->tcp_xmit_last = mp1;
694 				excess = &mp1->b_cont;
695 			}
696 			*excess = NULL;
697 			tcp_close_mpp(&tail);
698 			if (tcp->tcp_snd_zcopy_aware)
699 				tcp_zcopy_notify(tcp);
700 		}
701 		/*
702 		 * We have no unsent data, so unsent must be less than
703 		 * conn_sndlowat, so re-enable flow.
704 		 */
705 		mutex_enter(&tcp->tcp_non_sq_lock);
706 		if (tcp->tcp_flow_stopped) {
707 			tcp_clrqfull(tcp);
708 		}
709 		mutex_exit(&tcp->tcp_non_sq_lock);
710 	}
711 	/*
712 	 * TODO: you can't just flush these, you have to increase rwnd for one
713 	 * thing.  For another, how should urgent data interact?
714 	 */
715 	if (fval & FLUSHR) {
716 		*mp->b_rptr = fval & ~FLUSHW;
717 		/* XXX */
718 		qreply(q, mp);
719 		return;
720 	}
721 	freemsg(mp);
722 }
723 
724 /*
725  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
726  * messages.
727  */
728 static void
729 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
730 {
731 	mblk_t		*mp1;
732 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
733 	STRUCT_HANDLE(strbuf, sb);
734 	uint_t		addrlen;
735 	conn_t		*connp = tcp->tcp_connp;
736 	queue_t		*q = connp->conn_wq;
737 
738 	/* Make sure it is one of ours. */
739 	switch (iocp->ioc_cmd) {
740 	case TI_GETMYNAME:
741 	case TI_GETPEERNAME:
742 		break;
743 	default:
744 		/*
745 		 * If the conn is closing, then error the ioctl here. Otherwise
746 		 * use the CONN_IOCTLREF_* macros to hold off tcp_close until
747 		 * we're done here.
748 		 */
749 		mutex_enter(&connp->conn_lock);
750 		if (connp->conn_state_flags & CONN_CLOSING) {
751 			mutex_exit(&connp->conn_lock);
752 			iocp->ioc_error = EINVAL;
753 			mp->b_datap->db_type = M_IOCNAK;
754 			iocp->ioc_count = 0;
755 			qreply(q, mp);
756 			return;
757 		}
758 
759 		CONN_INC_IOCTLREF_LOCKED(connp);
760 		ip_wput_nondata(q, mp);
761 		CONN_DEC_IOCTLREF(connp);
762 		return;
763 	}
764 	switch (mi_copy_state(q, mp, &mp1)) {
765 	case -1:
766 		return;
767 	case MI_COPY_CASE(MI_COPY_IN, 1):
768 		break;
769 	case MI_COPY_CASE(MI_COPY_OUT, 1):
770 		/* Copy out the strbuf. */
771 		mi_copyout(q, mp);
772 		return;
773 	case MI_COPY_CASE(MI_COPY_OUT, 2):
774 		/* All done. */
775 		mi_copy_done(q, mp, 0);
776 		return;
777 	default:
778 		mi_copy_done(q, mp, EPROTO);
779 		return;
780 	}
781 	/* Check alignment of the strbuf */
782 	if (!OK_32PTR(mp1->b_rptr)) {
783 		mi_copy_done(q, mp, EINVAL);
784 		return;
785 	}
786 
787 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
788 
789 	if (connp->conn_family == AF_INET)
790 		addrlen = sizeof (sin_t);
791 	else
792 		addrlen = sizeof (sin6_t);
793 
794 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
795 		mi_copy_done(q, mp, EINVAL);
796 		return;
797 	}
798 
799 	switch (iocp->ioc_cmd) {
800 	case TI_GETMYNAME:
801 		break;
802 	case TI_GETPEERNAME:
803 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
804 			mi_copy_done(q, mp, ENOTCONN);
805 			return;
806 		}
807 		break;
808 	}
809 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
810 	if (!mp1)
811 		return;
812 
813 	STRUCT_FSET(sb, len, addrlen);
814 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
815 	case TI_GETMYNAME:
816 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
817 		    &addrlen);
818 		break;
819 	case TI_GETPEERNAME:
820 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
821 		    &addrlen);
822 		break;
823 	}
824 	mp1->b_wptr += addrlen;
825 	/* Copy out the address */
826 	mi_copyout(q, mp);
827 }
828 
829 /*
830  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
831  * messages.
832  */
833 /* ARGSUSED */
834 static void
835 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
836 {
837 	conn_t		*connp = (conn_t *)arg;
838 	tcp_t		*tcp = connp->conn_tcp;
839 	queue_t		*q = connp->conn_wq;
840 	struct iocblk	*iocp;
841 
842 	ASSERT(DB_TYPE(mp) == M_IOCTL);
843 	/*
844 	 * Try and ASSERT the minimum possible references on the
845 	 * conn early enough. Since we are executing on write side,
846 	 * the connection is obviously not detached and that means
847 	 * there is a ref each for TCP and IP. Since we are behind
848 	 * the squeue, the minimum references needed are 3. If the
849 	 * conn is in classifier hash list, there should be an
850 	 * extra ref for that (we check both the possibilities).
851 	 */
852 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
853 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
854 
855 	iocp = (struct iocblk *)mp->b_rptr;
856 	switch (iocp->ioc_cmd) {
857 	case _SIOCSOCKFALLBACK:
858 		/*
859 		 * Either sockmod is about to be popped and the socket
860 		 * would now be treated as a plain stream, or a module
861 		 * is about to be pushed so we could no longer use read-
862 		 * side synchronous streams for fused loopback tcp.
863 		 * Drain any queued data and disable direct sockfs
864 		 * interface from now on.
865 		 */
866 		if (!tcp->tcp_issocket) {
867 			DB_TYPE(mp) = M_IOCNAK;
868 			iocp->ioc_error = EINVAL;
869 		} else {
870 			tcp_use_pure_tpi(tcp);
871 			DB_TYPE(mp) = M_IOCACK;
872 			iocp->ioc_error = 0;
873 		}
874 		iocp->ioc_count = 0;
875 		iocp->ioc_rval = 0;
876 		qreply(q, mp);
877 		return;
878 	}
879 
880 	/*
881 	 * If the conn is closing, then error the ioctl here. Otherwise bump the
882 	 * conn_ioctlref to hold off tcp_close until we're done here.
883 	 */
884 	mutex_enter(&(connp)->conn_lock);
885 	if ((connp)->conn_state_flags & CONN_CLOSING) {
886 		mutex_exit(&(connp)->conn_lock);
887 		iocp->ioc_error = EINVAL;
888 		mp->b_datap->db_type = M_IOCNAK;
889 		iocp->ioc_count = 0;
890 		qreply(q, mp);
891 		return;
892 	}
893 
894 	CONN_INC_IOCTLREF_LOCKED(connp);
895 	ip_wput_nondata(q, mp);
896 	CONN_DEC_IOCTLREF(connp);
897 }
898 
899 /*
900  * This routine is called by tcp_wput() to handle all TPI requests.
901  */
902 /* ARGSUSED */
903 static void
904 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
905 {
906 	conn_t		*connp = (conn_t *)arg;
907 	tcp_t		*tcp = connp->conn_tcp;
908 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
909 	uchar_t		*rptr;
910 	t_scalar_t	type;
911 	cred_t		*cr;
912 
913 	/*
914 	 * Try and ASSERT the minimum possible references on the
915 	 * conn early enough. Since we are executing on write side,
916 	 * the connection is obviously not detached and that means
917 	 * there is a ref each for TCP and IP. Since we are behind
918 	 * the squeue, the minimum references needed are 3. If the
919 	 * conn is in classifier hash list, there should be an
920 	 * extra ref for that (we check both the possibilities).
921 	 */
922 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
923 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
924 
925 	rptr = mp->b_rptr;
926 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
927 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
928 		type = ((union T_primitives *)rptr)->type;
929 		if (type == T_EXDATA_REQ) {
930 			tcp_output_urgent(connp, mp, arg2, NULL);
931 		} else if (type != T_DATA_REQ) {
932 			goto non_urgent_data;
933 		} else {
934 			/* TODO: options, flags, ... from user */
935 			/* Set length to zero for reclamation below */
936 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
937 			freeb(mp);
938 		}
939 		return;
940 	} else {
941 		if (connp->conn_debug) {
942 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
943 			    "tcp_wput_proto, dropping one...");
944 		}
945 		freemsg(mp);
946 		return;
947 	}
948 
949 non_urgent_data:
950 
951 	switch ((int)tprim->type) {
952 	case O_T_BIND_REQ:	/* bind request */
953 	case T_BIND_REQ:	/* new semantics bind request */
954 		tcp_tpi_bind(tcp, mp);
955 		break;
956 	case T_UNBIND_REQ:	/* unbind request */
957 		tcp_tpi_unbind(tcp, mp);
958 		break;
959 	case O_T_CONN_RES:	/* old connection response XXX */
960 	case T_CONN_RES:	/* connection response */
961 		tcp_tli_accept(tcp, mp);
962 		break;
963 	case T_CONN_REQ:	/* connection request */
964 		tcp_tpi_connect(tcp, mp);
965 		break;
966 	case T_DISCON_REQ:	/* disconnect request */
967 		tcp_disconnect(tcp, mp);
968 		break;
969 	case T_CAPABILITY_REQ:
970 		tcp_capability_req(tcp, mp);	/* capability request */
971 		break;
972 	case T_INFO_REQ:	/* information request */
973 		tcp_info_req(tcp, mp);
974 		break;
975 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
976 	case T_OPTMGMT_REQ:
977 		/*
978 		 * Note:  no support for snmpcom_req() through new
979 		 * T_OPTMGMT_REQ. See comments in ip.c
980 		 */
981 
982 		/*
983 		 * All Solaris components should pass a db_credp
984 		 * for this TPI message, hence we ASSERT.
985 		 * But in case there is some other M_PROTO that looks
986 		 * like a TPI message sent by some other kernel
987 		 * component, we check and return an error.
988 		 */
989 		cr = msg_getcred(mp, NULL);
990 		ASSERT(cr != NULL);
991 		if (cr == NULL) {
992 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
993 			return;
994 		}
995 		/*
996 		 * If EINPROGRESS is returned, the request has been queued
997 		 * for subsequent processing by ip_restart_optmgmt(), which
998 		 * will do the CONN_DEC_REF().
999 		 */
1000 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
1001 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
1002 		} else {
1003 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
1004 		}
1005 		break;
1006 
1007 	case T_UNITDATA_REQ:	/* unitdata request */
1008 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
1009 		break;
1010 	case T_ORDREL_REQ:	/* orderly release req */
1011 		freemsg(mp);
1012 
1013 		if (tcp->tcp_fused)
1014 			tcp_unfuse(tcp);
1015 
1016 		if (tcp_xmit_end(tcp) != 0) {
1017 			/*
1018 			 * We were crossing FINs and got a reset from
1019 			 * the other side. Just ignore it.
1020 			 */
1021 			if (connp->conn_debug) {
1022 				(void) strlog(TCP_MOD_ID, 0, 1,
1023 				    SL_ERROR|SL_TRACE,
1024 				    "tcp_wput_proto, T_ORDREL_REQ out of "
1025 				    "state %s",
1026 				    tcp_display(tcp, NULL,
1027 				    DISP_ADDR_AND_PORT));
1028 			}
1029 		}
1030 		break;
1031 	case T_ADDR_REQ:
1032 		tcp_addr_req(tcp, mp);
1033 		break;
1034 	default:
1035 		if (connp->conn_debug) {
1036 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
1037 			    "tcp_wput_proto, bogus TPI msg, type %d",
1038 			    tprim->type);
1039 		}
1040 		/*
1041 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
1042 		 * to recover.
1043 		 */
1044 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
1045 		break;
1046 	}
1047 }
1048 
1049 /*
1050  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
1051  */
1052 static void
1053 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
1054 {
1055 	void	*data;
1056 	mblk_t	*datamp = mp->b_cont;
1057 	conn_t	*connp = Q_TO_CONN(q);
1058 	tcp_t	*tcp = connp->conn_tcp;
1059 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
1060 
1061 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
1062 		cmdp->cb_error = EPROTO;
1063 		qreply(q, mp);
1064 		return;
1065 	}
1066 
1067 	data = datamp->b_rptr;
1068 
1069 	switch (cmdp->cb_cmd) {
1070 	case TI_GETPEERNAME:
1071 		if (tcp->tcp_state < TCPS_SYN_RCVD)
1072 			cmdp->cb_error = ENOTCONN;
1073 		else
1074 			cmdp->cb_error = conn_getpeername(connp, data,
1075 			    &cmdp->cb_len);
1076 		break;
1077 	case TI_GETMYNAME:
1078 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
1079 		break;
1080 	default:
1081 		cmdp->cb_error = EINVAL;
1082 		break;
1083 	}
1084 
1085 	qreply(q, mp);
1086 }
1087 
1088 /*
1089  * The TCP fast path write put procedure.
1090  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
1091  */
1092 /* ARGSUSED */
1093 void
1094 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1095 {
1096 	int		len;
1097 	int		hdrlen;
1098 	int		plen;
1099 	mblk_t		*mp1;
1100 	uchar_t		*rptr;
1101 	uint32_t	snxt;
1102 	tcpha_t		*tcpha;
1103 	struct datab	*db;
1104 	uint32_t	suna;
1105 	uint32_t	mss;
1106 	ipaddr_t	*dst;
1107 	ipaddr_t	*src;
1108 	uint32_t	sum;
1109 	int		usable;
1110 	conn_t		*connp = (conn_t *)arg;
1111 	tcp_t		*tcp = connp->conn_tcp;
1112 	uint32_t	msize;
1113 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1114 	ip_xmit_attr_t	*ixa;
1115 	clock_t		now;
1116 
1117 	/*
1118 	 * Try and ASSERT the minimum possible references on the
1119 	 * conn early enough. Since we are executing on write side,
1120 	 * the connection is obviously not detached and that means
1121 	 * there is a ref each for TCP and IP. Since we are behind
1122 	 * the squeue, the minimum references needed are 3. If the
1123 	 * conn is in classifier hash list, there should be an
1124 	 * extra ref for that (we check both the possibilities).
1125 	 */
1126 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
1127 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
1128 
1129 	ASSERT(DB_TYPE(mp) == M_DATA);
1130 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
1131 
1132 	mutex_enter(&tcp->tcp_non_sq_lock);
1133 	tcp->tcp_squeue_bytes -= msize;
1134 	mutex_exit(&tcp->tcp_non_sq_lock);
1135 
1136 	/* Bypass tcp protocol for fused tcp loopback */
1137 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
1138 		return;
1139 
1140 	mss = tcp->tcp_mss;
1141 	/*
1142 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
1143 	 * down. Do backoff, now.
1144 	 */
1145 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
1146 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
1147 
1148 
1149 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
1150 	len = (int)(mp->b_wptr - mp->b_rptr);
1151 
1152 	/*
1153 	 * Criteria for fast path:
1154 	 *
1155 	 *   1. no unsent data
1156 	 *   2. single mblk in request
1157 	 *   3. connection established
1158 	 *   4. data in mblk
1159 	 *   5. len <= mss
1160 	 *   6. no tcp_valid bits
1161 	 */
1162 	if ((tcp->tcp_unsent != 0) ||
1163 	    (tcp->tcp_cork) ||
1164 	    (mp->b_cont != NULL) ||
1165 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
1166 	    (len == 0) ||
1167 	    (len > mss) ||
1168 	    (tcp->tcp_valid_bits != 0)) {
1169 		tcp_wput_data(tcp, mp, B_FALSE);
1170 		return;
1171 	}
1172 
1173 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
1174 	ASSERT(tcp->tcp_fin_sent == 0);
1175 
1176 	/* queue new packet onto retransmission queue */
1177 	if (tcp->tcp_xmit_head == NULL) {
1178 		tcp->tcp_xmit_head = mp;
1179 	} else {
1180 		tcp->tcp_xmit_last->b_cont = mp;
1181 	}
1182 	tcp->tcp_xmit_last = mp;
1183 	tcp->tcp_xmit_tail = mp;
1184 
1185 	/* find out how much we can send */
1186 	/* BEGIN CSTYLED */
1187 	/*
1188 	 *    un-acked	   usable
1189 	 *  |--------------|-----------------|
1190 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
1191 	 */
1192 	/* END CSTYLED */
1193 
1194 	/* start sending from tcp_snxt */
1195 	snxt = tcp->tcp_snxt;
1196 
1197 	/*
1198 	 * Check to see if this connection has been idle for some time and no
1199 	 * ACK is expected. If so, then the congestion window size is no longer
1200 	 * meaningfully tied to current network conditions.
1201 	 *
1202 	 * We reinitialize tcp_cwnd, and slow start again to get back the
1203 	 * connection's "self-clock" as described in Van Jacobson's 1988 paper
1204 	 * "Congestion avoidance and control".
1205 	 */
1206 	now = LBOLT_FASTPATH;
1207 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
1208 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
1209 		cc_after_idle(tcp);
1210 	}
1211 
1212 	usable = tcp->tcp_swnd;		/* tcp window size */
1213 	if (usable > tcp->tcp_cwnd)
1214 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
1215 	usable -= snxt;		/* subtract stuff already sent */
1216 	suna = tcp->tcp_suna;
1217 	usable += suna;
1218 	/* usable can be < 0 if the congestion window is smaller */
1219 	if (len > usable) {
1220 		/* Can't send complete M_DATA in one shot */
1221 		goto slow;
1222 	}
1223 
1224 	mutex_enter(&tcp->tcp_non_sq_lock);
1225 	if (tcp->tcp_flow_stopped &&
1226 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
1227 		tcp_clrqfull(tcp);
1228 	}
1229 	mutex_exit(&tcp->tcp_non_sq_lock);
1230 
1231 	/*
1232 	 * determine if anything to send (Nagle).
1233 	 *
1234 	 *   1. len < tcp_mss (i.e. small)
1235 	 *   2. unacknowledged data present
1236 	 *   3. len < nagle limit
1237 	 *   4. last packet sent < nagle limit (previous packet sent)
1238 	 */
1239 	if ((len < mss) && (snxt != suna) &&
1240 	    (len < (int)tcp->tcp_naglim) &&
1241 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
1242 		/*
1243 		 * This was the first unsent packet and normally
1244 		 * mss < xmit_hiwater so there is no need to worry
1245 		 * about flow control. The next packet will go
1246 		 * through the flow control check in tcp_wput_data().
1247 		 */
1248 		/* leftover work from above */
1249 		tcp->tcp_unsent = len;
1250 		tcp->tcp_xmit_tail_unsent = len;
1251 
1252 		return;
1253 	}
1254 
1255 	/*
1256 	 * len <= tcp->tcp_mss && len == unsent so no sender silly window.  Can
1257 	 * send now.
1258 	 */
1259 
1260 	if (snxt == suna) {
1261 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
1262 	}
1263 
1264 	/* we have always sent something */
1265 	tcp->tcp_rack_cnt = 0;
1266 
1267 	tcp->tcp_snxt = snxt + len;
1268 	tcp->tcp_rack = tcp->tcp_rnxt;
1269 
1270 	if ((mp1 = dupb(mp)) == 0)
1271 		goto no_memory;
1272 	mp->b_prev = (mblk_t *)(intptr_t)gethrtime();
1273 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
1274 
1275 	/* adjust tcp header information */
1276 	tcpha = tcp->tcp_tcpha;
1277 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
1278 
1279 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
1280 	sum = (sum >> 16) + (sum & 0xFFFF);
1281 	tcpha->tha_sum = htons(sum);
1282 
1283 	tcpha->tha_seq = htonl(snxt);
1284 
1285 	TCPS_BUMP_MIB(tcps, tcpOutDataSegs);
1286 	TCPS_UPDATE_MIB(tcps, tcpOutDataBytes, len);
1287 	TCPS_BUMP_MIB(tcps, tcpHCOutSegs);
1288 	tcp->tcp_cs.tcp_out_data_segs++;
1289 	tcp->tcp_cs.tcp_out_data_bytes += len;
1290 
1291 	/* Update the latest receive window size in TCP header. */
1292 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
1293 
1294 	tcp->tcp_last_sent_len = (ushort_t)len;
1295 
1296 	plen = len + connp->conn_ht_iphc_len;
1297 
1298 	ixa = connp->conn_ixa;
1299 	ixa->ixa_pktlen = plen;
1300 
1301 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
1302 		tcp->tcp_ipha->ipha_length = htons(plen);
1303 	} else {
1304 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
1305 	}
1306 
1307 	/* see if we need to allocate a mblk for the headers */
1308 	hdrlen = connp->conn_ht_iphc_len;
1309 	rptr = mp1->b_rptr - hdrlen;
1310 	db = mp1->b_datap;
1311 	if ((db->db_ref != 2) || rptr < db->db_base ||
1312 	    (!OK_32PTR(rptr))) {
1313 		/* NOTE: we assume allocb returns an OK_32PTR */
1314 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
1315 		if (!mp) {
1316 			freemsg(mp1);
1317 			goto no_memory;
1318 		}
1319 		mp->b_cont = mp1;
1320 		mp1 = mp;
1321 		/* Leave room for Link Level header */
1322 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
1323 		mp1->b_wptr = &rptr[hdrlen];
1324 	}
1325 	mp1->b_rptr = rptr;
1326 
1327 	/* Fill in the timestamp option. */
1328 	if (tcp->tcp_snd_ts_ok) {
1329 		U32_TO_BE32(now,
1330 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH + 4);
1331 		U32_TO_BE32(tcp->tcp_ts_recent,
1332 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH + 8);
1333 	} else {
1334 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
1335 	}
1336 
1337 	/* copy header into outgoing packet */
1338 	dst = (ipaddr_t *)rptr;
1339 	src = (ipaddr_t *)connp->conn_ht_iphc;
1340 	dst[0] = src[0];
1341 	dst[1] = src[1];
1342 	dst[2] = src[2];
1343 	dst[3] = src[3];
1344 	dst[4] = src[4];
1345 	dst[5] = src[5];
1346 	dst[6] = src[6];
1347 	dst[7] = src[7];
1348 	dst[8] = src[8];
1349 	dst[9] = src[9];
1350 	if (hdrlen -= 40) {
1351 		hdrlen >>= 2;
1352 		dst += 10;
1353 		src += 10;
1354 		do {
1355 			*dst++ = *src++;
1356 		} while (--hdrlen);
1357 	}
1358 
1359 	/*
1360 	 * Set the ECN info in the TCP header.  Note that this
1361 	 * is not the template header.
1362 	 */
1363 	if (tcp->tcp_ecn_ok) {
1364 		TCP_SET_ECT(tcp, rptr);
1365 
1366 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
1367 		if (tcp->tcp_ecn_echo_on)
1368 			tcpha->tha_flags |= TH_ECE;
1369 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
1370 			tcpha->tha_flags |= TH_CWR;
1371 			tcp->tcp_ecn_cwr_sent = B_TRUE;
1372 		}
1373 	}
1374 
1375 	if (tcp->tcp_ip_forward_progress) {
1376 		tcp->tcp_ip_forward_progress = B_FALSE;
1377 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
1378 	} else {
1379 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
1380 	}
1381 	tcp_send_data(tcp, mp1);
1382 	return;
1383 
1384 	/*
1385 	 * If we ran out of memory, we pretend to have sent the packet
1386 	 * and that it was lost on the wire.
1387 	 */
1388 no_memory:
1389 	return;
1390 
1391 slow:
1392 	/* leftover work from above */
1393 	tcp->tcp_unsent = len;
1394 	tcp->tcp_xmit_tail_unsent = len;
1395 	tcp_wput_data(tcp, NULL, B_FALSE);
1396 }
1397 
1398 /* ARGSUSED2 */
1399 void
1400 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1401 {
1402 	int len;
1403 	uint32_t msize;
1404 	conn_t *connp = (conn_t *)arg;
1405 	tcp_t *tcp = connp->conn_tcp;
1406 
1407 	msize = msgdsize(mp);
1408 
1409 	len = msize - 1;
1410 	if (len < 0) {
1411 		freemsg(mp);
1412 		return;
1413 	}
1414 
1415 	/*
1416 	 * Try to force urgent data out on the wire. Even if we have unsent
1417 	 * data this will at least send the urgent flag.
1418 	 * XXX does not handle more flag correctly.
1419 	 */
1420 	len += tcp->tcp_unsent;
1421 	len += tcp->tcp_snxt;
1422 	tcp->tcp_urg = len;
1423 	tcp->tcp_valid_bits |= TCP_URG_VALID;
1424 
1425 	/* Bypass tcp protocol for fused tcp loopback */
1426 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
1427 		return;
1428 
1429 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
1430 	if (DB_TYPE(mp) != M_DATA) {
1431 		mblk_t *mp1 = mp;
1432 		ASSERT(!IPCL_IS_NONSTR(connp));
1433 		mp = mp->b_cont;
1434 		freeb(mp1);
1435 	}
1436 	tcp_wput_data(tcp, mp, B_TRUE);
1437 }
1438 
1439 /*
1440  * Called by streams close routine via squeues when our client blows off its
1441  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
1442  * connection politely" When SO_LINGER is set (with a non-zero linger time and
1443  * it is not a nonblocking socket) then this routine sleeps until the FIN is
1444  * acked.
1445  *
1446  * NOTE: tcp_close potentially returns error when lingering.
1447  * However, the stream head currently does not pass these errors
1448  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
1449  * errors to the application (from tsleep()) and not errors
1450  * like ECONNRESET caused by receiving a reset packet.
1451  */
1452 
1453 /* ARGSUSED */
1454 void
1455 tcp_close_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1456 {
1457 	char	*msg;
1458 	conn_t	*connp = (conn_t *)arg;
1459 	tcp_t	*tcp = connp->conn_tcp;
1460 	clock_t	delta = 0;
1461 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1462 
1463 	/*
1464 	 * When a non-STREAMS socket is being closed, it does not always
1465 	 * stick around waiting for tcp_close_output to run and can therefore
1466 	 * have dropped a reference already. So adjust the asserts accordingly.
1467 	 */
1468 	ASSERT((connp->conn_fanout != NULL &&
1469 	    connp->conn_ref >= (IPCL_IS_NONSTR(connp) ? 3 : 4)) ||
1470 	    (connp->conn_fanout == NULL &&
1471 	    connp->conn_ref >= (IPCL_IS_NONSTR(connp) ? 2 : 3)));
1472 
1473 	mutex_enter(&tcp->tcp_eager_lock);
1474 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
1475 		/*
1476 		 * Cleanup for listener. For non-STREAM sockets sockfs will
1477 		 * close all the eagers on 'q', so in that case only deal
1478 		 * with 'q0'.
1479 		 */
1480 		tcp_eager_cleanup(tcp, IPCL_IS_NONSTR(connp) ? 1 : 0);
1481 		tcp->tcp_wait_for_eagers = 1;
1482 	}
1483 	mutex_exit(&tcp->tcp_eager_lock);
1484 
1485 	tcp->tcp_lso = B_FALSE;
1486 
1487 	msg = NULL;
1488 	switch (tcp->tcp_state) {
1489 	case TCPS_CLOSED:
1490 	case TCPS_IDLE:
1491 		break;
1492 	case TCPS_BOUND:
1493 		if (tcp->tcp_listener != NULL) {
1494 			ASSERT(IPCL_IS_NONSTR(connp));
1495 			/*
1496 			 * Unlink from the listener and drop the reference
1497 			 * put on it by the eager. tcp_closei_local will not
1498 			 * do it because tcp_tconnind_started is TRUE.
1499 			 */
1500 			mutex_enter(&tcp->tcp_saved_listener->tcp_eager_lock);
1501 			tcp_eager_unlink(tcp);
1502 			mutex_exit(&tcp->tcp_saved_listener->tcp_eager_lock);
1503 			CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
1504 		}
1505 		break;
1506 	case TCPS_LISTEN:
1507 		break;
1508 	case TCPS_SYN_SENT:
1509 		msg = "tcp_close, during connect";
1510 		break;
1511 	case TCPS_SYN_RCVD:
1512 		/*
1513 		 * Close during the connect 3-way handshake
1514 		 * but here there may or may not be pending data
1515 		 * already on queue. Process almost same as in
1516 		 * the ESTABLISHED state.
1517 		 */
1518 		/* FALLTHRU */
1519 	default:
1520 		if (tcp->tcp_fused)
1521 			tcp_unfuse(tcp);
1522 
1523 		/*
1524 		 * If SO_LINGER has set a zero linger time, abort the
1525 		 * connection with a reset.
1526 		 */
1527 		if (connp->conn_linger && connp->conn_lingertime == 0) {
1528 			msg = "tcp_close, zero lingertime";
1529 			break;
1530 		}
1531 
1532 		/*
1533 		 * Abort connection if there is unread data queued.
1534 		 */
1535 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
1536 			msg = "tcp_close, unread data";
1537 			break;
1538 		}
1539 
1540 		/*
1541 		 * Abort connection if it is being closed without first
1542 		 * being accepted. This can happen if a listening non-STREAM
1543 		 * socket wants to get rid of the socket, for example, if the
1544 		 * listener is closing.
1545 		 */
1546 		if (tcp->tcp_listener != NULL) {
1547 			ASSERT(IPCL_IS_NONSTR(connp));
1548 			msg = "tcp_close, close before accept";
1549 
1550 			/*
1551 			 * Unlink from the listener and drop the reference
1552 			 * put on it by the eager. tcp_closei_local will not
1553 			 * do it because tcp_tconnind_started is TRUE.
1554 			 */
1555 			mutex_enter(&tcp->tcp_saved_listener->tcp_eager_lock);
1556 			tcp_eager_unlink(tcp);
1557 			mutex_exit(&tcp->tcp_saved_listener->tcp_eager_lock);
1558 			CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
1559 			break;
1560 		}
1561 
1562 		/*
1563 		 * Transmit the FIN before detaching the tcp_t.
1564 		 * After tcp_detach returns this queue/perimeter
1565 		 * no longer owns the tcp_t thus others can modify it.
1566 		 */
1567 		(void) tcp_xmit_end(tcp);
1568 
1569 		/*
1570 		 * If lingering on close then wait until the fin is acked,
1571 		 * the SO_LINGER time passes, or a reset is sent/received.
1572 		 */
1573 		if (connp->conn_linger && connp->conn_lingertime > 0 &&
1574 		    !(tcp->tcp_fin_acked) &&
1575 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
1576 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
1577 				tcp->tcp_client_errno = EWOULDBLOCK;
1578 			} else if (tcp->tcp_client_errno == 0) {
1579 
1580 				ASSERT(tcp->tcp_linger_tid == 0);
1581 
1582 				/* conn_lingertime is in sec. */
1583 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
1584 				    tcp_close_linger_timeout,
1585 				    connp->conn_lingertime * MILLISEC);
1586 
1587 				/* tcp_close_linger_timeout will finish close */
1588 				if (tcp->tcp_linger_tid == 0)
1589 					tcp->tcp_client_errno = ENOSR;
1590 				else
1591 					return;
1592 			}
1593 
1594 			/*
1595 			 * Check if we need to detach or just close
1596 			 * the instance.
1597 			 */
1598 			if (tcp->tcp_state <= TCPS_LISTEN)
1599 				break;
1600 		}
1601 
1602 		/*
1603 		 * Make sure that no other thread will access the conn_rq of
1604 		 * this instance (through lookups etc.) as conn_rq will go
1605 		 * away shortly.
1606 		 */
1607 		tcp_acceptor_hash_remove(tcp);
1608 
1609 		mutex_enter(&tcp->tcp_non_sq_lock);
1610 		if (tcp->tcp_flow_stopped) {
1611 			tcp_clrqfull(tcp);
1612 		}
1613 		mutex_exit(&tcp->tcp_non_sq_lock);
1614 
1615 		if (tcp->tcp_timer_tid != 0) {
1616 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
1617 			tcp->tcp_timer_tid = 0;
1618 		}
1619 		/*
1620 		 * Need to cancel those timers which will not be used when
1621 		 * TCP is detached.  This has to be done before the conn_wq
1622 		 * is set to NULL.
1623 		 */
1624 		tcp_timers_stop(tcp);
1625 
1626 		tcp->tcp_detached = B_TRUE;
1627 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
1628 			tcp_time_wait_append(tcp);
1629 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
1630 			ASSERT(connp->conn_ref >=
1631 			    (IPCL_IS_NONSTR(connp) ? 2 : 3));
1632 			goto finish;
1633 		}
1634 
1635 		/*
1636 		 * If delta is zero the timer event wasn't executed and was
1637 		 * successfully canceled. In this case we need to restart it
1638 		 * with the minimal delta possible.
1639 		 */
1640 		if (delta >= 0)
1641 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
1642 			    delta ? delta : 1);
1643 
1644 		ASSERT(connp->conn_ref >= (IPCL_IS_NONSTR(connp) ? 2 : 3));
1645 		goto finish;
1646 	}
1647 
1648 	/* Detach did not complete. Still need to remove q from stream. */
1649 	if (msg) {
1650 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
1651 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
1652 			TCPS_BUMP_MIB(tcps, tcpEstabResets);
1653 		if (tcp->tcp_state == TCPS_SYN_SENT ||
1654 		    tcp->tcp_state == TCPS_SYN_RCVD)
1655 			TCPS_BUMP_MIB(tcps, tcpAttemptFails);
1656 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
1657 	}
1658 
1659 	tcp_closei_local(tcp);
1660 	CONN_DEC_REF(connp);
1661 	ASSERT(connp->conn_ref >= (IPCL_IS_NONSTR(connp) ? 1 : 2));
1662 
1663 finish:
1664 	/*
1665 	 * Don't change the queues in the case of a listener that has
1666 	 * eagers in its q or q0. It could surprise the eagers.
1667 	 * Instead wait for the eagers outside the squeue.
1668 	 *
1669 	 * For non-STREAMS sockets tcp_wait_for_eagers implies that
1670 	 * we should delay the su_closed upcall until all eagers have
1671 	 * dropped their references.
1672 	 */
1673 	if (!tcp->tcp_wait_for_eagers) {
1674 		tcp->tcp_detached = B_TRUE;
1675 		connp->conn_rq = NULL;
1676 		connp->conn_wq = NULL;
1677 
1678 		/* non-STREAM socket, release the upper handle */
1679 		if (IPCL_IS_NONSTR(connp)) {
1680 			ASSERT(connp->conn_upper_handle != NULL);
1681 			(*connp->conn_upcalls->su_closed)
1682 			    (connp->conn_upper_handle);
1683 			connp->conn_upper_handle = NULL;
1684 			connp->conn_upcalls = NULL;
1685 		}
1686 	}
1687 
1688 	/* Signal tcp_close() to finish closing. */
1689 	mutex_enter(&tcp->tcp_closelock);
1690 	tcp->tcp_closed = 1;
1691 	cv_signal(&tcp->tcp_closecv);
1692 	mutex_exit(&tcp->tcp_closelock);
1693 }
1694 
1695 /* ARGSUSED */
1696 void
1697 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1698 {
1699 	conn_t	*connp = (conn_t *)arg;
1700 	tcp_t	*tcp = connp->conn_tcp;
1701 
1702 	freemsg(mp);
1703 
1704 	if (tcp->tcp_fused)
1705 		tcp_unfuse(tcp);
1706 
1707 	if (tcp_xmit_end(tcp) != 0) {
1708 		/*
1709 		 * We were crossing FINs and got a reset from
1710 		 * the other side. Just ignore it.
1711 		 */
1712 		if (connp->conn_debug) {
1713 			(void) strlog(TCP_MOD_ID, 0, 1,
1714 			    SL_ERROR|SL_TRACE,
1715 			    "tcp_shutdown_output() out of state %s",
1716 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
1717 		}
1718 	}
1719 }
1720 
1721 #pragma inline(tcp_send_data)
1722 
1723 void
1724 tcp_send_data(tcp_t *tcp, mblk_t *mp)
1725 {
1726 	conn_t		*connp = tcp->tcp_connp;
1727 
1728 	/*
1729 	 * Check here to avoid sending zero-copy message down to IP when
1730 	 * ZEROCOPY capability has turned off. We only need to deal with
1731 	 * the race condition between sockfs and the notification here.
1732 	 * Since we have tried to backoff the tcp_xmit_head when turning
1733 	 * zero-copy off and new messages in tcp_output(), we simply drop
1734 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
1735 	 * is not true.
1736 	 */
1737 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
1738 	    !tcp->tcp_xmit_zc_clean) {
1739 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
1740 		freemsg(mp);
1741 		return;
1742 	}
1743 
1744 	DTRACE_TCP5(send, mblk_t *, NULL, ip_xmit_attr_t *, connp->conn_ixa,
1745 	    __dtrace_tcp_void_ip_t *, mp->b_rptr, tcp_t *, tcp,
1746 	    __dtrace_tcp_tcph_t *,
1747 	    &mp->b_rptr[connp->conn_ixa->ixa_ip_hdr_length]);
1748 
1749 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
1750 	(void) conn_ip_output(mp, connp->conn_ixa);
1751 }
1752 
1753 /* ARGSUSED2 */
1754 void
1755 tcp_send_synack(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1756 {
1757 	conn_t	*econnp = (conn_t *)arg;
1758 	tcp_t	*tcp = econnp->conn_tcp;
1759 	ip_xmit_attr_t *ixa = econnp->conn_ixa;
1760 
1761 	/* Guard against a RST having blown it away while on the squeue */
1762 	if (tcp->tcp_state == TCPS_CLOSED) {
1763 		freemsg(mp);
1764 		return;
1765 	}
1766 
1767 	/*
1768 	 * In the off-chance that the eager received and responded to
1769 	 * some other packet while the SYN|ACK was queued, we recalculate
1770 	 * the ixa_pktlen. It would be better to fix the SYN/accept
1771 	 * multithreading scheme to avoid this complexity.
1772 	 */
1773 	ixa->ixa_pktlen = msgdsize(mp);
1774 	(void) conn_ip_output(mp, ixa);
1775 }
1776 
1777 /*
1778  * tcp_send() is called by tcp_wput_data() and returns one of the following:
1779  *
1780  * -1 = failed allocation.
1781  *  0 = We've either successfully sent data, or our usable send window is too
1782  *      small and we'd rather wait until later before sending again.
1783  */
1784 static int
1785 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
1786     const int tcp_hdr_len, const int num_sack_blk, int *usable,
1787     uint32_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
1788 {
1789 	int		num_lso_seg = 1;
1790 	uint_t		lso_usable = 0;
1791 	boolean_t	do_lso_send = B_FALSE;
1792 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1793 	conn_t		*connp = tcp->tcp_connp;
1794 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
1795 
1796 	/*
1797 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
1798 	 * the underlying connection is LSO capable. Will check whether having
1799 	 * enough available data to initiate LSO transmission in the for(){}
1800 	 * loops.
1801 	 */
1802 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
1803 		do_lso_send = B_TRUE;
1804 
1805 	for (;;) {
1806 		struct datab	*db;
1807 		tcpha_t		*tcpha;
1808 		uint32_t	sum;
1809 		mblk_t		*mp, *mp1;
1810 		uchar_t		*rptr;
1811 		int		len;
1812 
1813 		/*
1814 		 * Calculate the maximum payload length we can send at one
1815 		 * time.
1816 		 */
1817 		if (do_lso_send) {
1818 			/*
1819 			 * Determine whether or not it's possible to do LSO,
1820 			 * and if so, how much data we can send.
1821 			 */
1822 			if ((*usable - 1) / mss >= 1) {
1823 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
1824 				num_lso_seg = lso_usable / mss;
1825 				if (lso_usable % mss) {
1826 					num_lso_seg++;
1827 					tcp->tcp_last_sent_len = (ushort_t)
1828 					    (lso_usable % mss);
1829 				} else {
1830 					tcp->tcp_last_sent_len = (ushort_t)mss;
1831 				}
1832 			} else {
1833 				do_lso_send = B_FALSE;
1834 				num_lso_seg = 1;
1835 				lso_usable = mss;
1836 			}
1837 		}
1838 
1839 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
1840 
1841 		len = mss;
1842 		if (len > *usable) {
1843 			ASSERT(do_lso_send == B_FALSE);
1844 
1845 			len = *usable;
1846 			if (len <= 0) {
1847 				/* Terminate the loop */
1848 				break;	/* success; too small */
1849 			}
1850 			/*
1851 			 * Sender silly-window avoidance.
1852 			 * Ignore this if we are going to send a
1853 			 * zero window probe out.
1854 			 *
1855 			 * TODO: force data into microscopic window?
1856 			 *	==> (!pushed || (unsent > usable))
1857 			 */
1858 			if (len < (tcp->tcp_max_swnd >> 1) &&
1859 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
1860 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
1861 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
1862 				/*
1863 				 * If the retransmit timer is not running
1864 				 * we start it so that we will retransmit
1865 				 * in the case when the receiver has
1866 				 * decremented the window.
1867 				 */
1868 				if (*snxt == tcp->tcp_snxt &&
1869 				    *snxt == tcp->tcp_suna) {
1870 					/*
1871 					 * We are not supposed to send
1872 					 * anything.  So let's wait a little
1873 					 * bit longer before breaking SWS
1874 					 * avoidance.
1875 					 *
1876 					 * What should the value be?
1877 					 * Suggestion: MAX(init rexmit time,
1878 					 * tcp->tcp_rto)
1879 					 */
1880 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
1881 				}
1882 				break;	/* success; too small */
1883 			}
1884 		}
1885 
1886 		tcpha = tcp->tcp_tcpha;
1887 
1888 		/*
1889 		 * The reason to adjust len here is that we need to set flags
1890 		 * and calculate checksum.
1891 		 */
1892 		if (do_lso_send)
1893 			len = lso_usable;
1894 
1895 		*usable -= len; /* Approximate - can be adjusted later */
1896 		if (*usable > 0)
1897 			tcpha->tha_flags = TH_ACK;
1898 		else
1899 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
1900 
1901 		/*
1902 		 * Prime pump for IP's checksumming on our behalf.
1903 		 * Include the adjustment for a source route if any.
1904 		 * In case of LSO, the partial pseudo-header checksum should
1905 		 * exclusive TCP length, so zero tha_sum before IP calculate
1906 		 * pseudo-header checksum for partial checksum offload.
1907 		 */
1908 		if (do_lso_send) {
1909 			sum = 0;
1910 		} else {
1911 			sum = len + tcp_hdr_len + connp->conn_sum;
1912 			sum = (sum >> 16) + (sum & 0xFFFF);
1913 		}
1914 		tcpha->tha_sum = htons(sum);
1915 		tcpha->tha_seq = htonl(*snxt);
1916 
1917 		/*
1918 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
1919 		 * set.  For the case when TCP_FSS_VALID is the only valid
1920 		 * bit (normal active close), branch off only when we think
1921 		 * that the FIN flag needs to be set.  Note for this case,
1922 		 * that (snxt + len) may not reflect the actual seg_len,
1923 		 * as len may be further reduced in tcp_xmit_mp().  If len
1924 		 * gets modified, we will end up here again.
1925 		 */
1926 		if (tcp->tcp_valid_bits != 0 &&
1927 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
1928 		    ((*snxt + len) == tcp->tcp_fss))) {
1929 			uchar_t		*prev_rptr;
1930 			uint32_t	prev_snxt = tcp->tcp_snxt;
1931 
1932 			if (*tail_unsent == 0) {
1933 				ASSERT((*xmit_tail)->b_cont != NULL);
1934 				*xmit_tail = (*xmit_tail)->b_cont;
1935 				prev_rptr = (*xmit_tail)->b_rptr;
1936 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
1937 				    (*xmit_tail)->b_rptr);
1938 			} else {
1939 				prev_rptr = (*xmit_tail)->b_rptr;
1940 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
1941 				    *tail_unsent;
1942 			}
1943 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
1944 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
1945 			/* Restore tcp_snxt so we get amount sent right. */
1946 			tcp->tcp_snxt = prev_snxt;
1947 			if (prev_rptr == (*xmit_tail)->b_rptr) {
1948 				/*
1949 				 * If the previous timestamp is still in use,
1950 				 * don't stomp on it.
1951 				 */
1952 				if ((*xmit_tail)->b_next == NULL) {
1953 					(*xmit_tail)->b_prev = local_time;
1954 					(*xmit_tail)->b_next =
1955 					    (mblk_t *)(uintptr_t)(*snxt);
1956 				}
1957 			} else
1958 				(*xmit_tail)->b_rptr = prev_rptr;
1959 
1960 			if (mp == NULL) {
1961 				return (-1);
1962 			}
1963 			mp1 = mp->b_cont;
1964 
1965 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
1966 				tcp->tcp_last_sent_len = (ushort_t)len;
1967 			while (mp1->b_cont) {
1968 				*xmit_tail = (*xmit_tail)->b_cont;
1969 				(*xmit_tail)->b_prev = local_time;
1970 				(*xmit_tail)->b_next =
1971 				    (mblk_t *)(uintptr_t)(*snxt);
1972 				mp1 = mp1->b_cont;
1973 			}
1974 			*snxt += len;
1975 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
1976 			TCPS_BUMP_MIB(tcps, tcpHCOutSegs);
1977 			TCPS_BUMP_MIB(tcps, tcpOutDataSegs);
1978 			TCPS_UPDATE_MIB(tcps, tcpOutDataBytes, len);
1979 			tcp->tcp_cs.tcp_out_data_segs++;
1980 			tcp->tcp_cs.tcp_out_data_bytes += len;
1981 			tcp_send_data(tcp, mp);
1982 			continue;
1983 		}
1984 
1985 		*snxt += len;	/* Adjust later if we don't send all of len */
1986 		TCPS_BUMP_MIB(tcps, tcpHCOutSegs);
1987 		TCPS_BUMP_MIB(tcps, tcpOutDataSegs);
1988 		TCPS_UPDATE_MIB(tcps, tcpOutDataBytes, len);
1989 		tcp->tcp_cs.tcp_out_data_segs++;
1990 		tcp->tcp_cs.tcp_out_data_bytes += len;
1991 
1992 		if (*tail_unsent) {
1993 			/* Are the bytes above us in flight? */
1994 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
1995 			if (rptr != (*xmit_tail)->b_rptr) {
1996 				*tail_unsent -= len;
1997 				if (len <= mss) /* LSO is unusable */
1998 					tcp->tcp_last_sent_len = (ushort_t)len;
1999 				len += total_hdr_len;
2000 				ixa->ixa_pktlen = len;
2001 
2002 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
2003 					tcp->tcp_ipha->ipha_length = htons(len);
2004 				} else {
2005 					tcp->tcp_ip6h->ip6_plen =
2006 					    htons(len - IPV6_HDR_LEN);
2007 				}
2008 
2009 				mp = dupb(*xmit_tail);
2010 				if (mp == NULL) {
2011 					return (-1);	/* out_of_mem */
2012 				}
2013 				mp->b_rptr = rptr;
2014 				/*
2015 				 * If the old timestamp is no longer in use,
2016 				 * sample a new timestamp now.
2017 				 */
2018 				if ((*xmit_tail)->b_next == NULL) {
2019 					(*xmit_tail)->b_prev = local_time;
2020 					(*xmit_tail)->b_next =
2021 					    (mblk_t *)(uintptr_t)(*snxt-len);
2022 				}
2023 				goto must_alloc;
2024 			}
2025 		} else {
2026 			*xmit_tail = (*xmit_tail)->b_cont;
2027 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
2028 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
2029 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
2030 			    (*xmit_tail)->b_rptr);
2031 		}
2032 
2033 		(*xmit_tail)->b_prev = local_time;
2034 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
2035 
2036 		*tail_unsent -= len;
2037 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
2038 			tcp->tcp_last_sent_len = (ushort_t)len;
2039 
2040 		len += total_hdr_len;
2041 		ixa->ixa_pktlen = len;
2042 
2043 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
2044 			tcp->tcp_ipha->ipha_length = htons(len);
2045 		} else {
2046 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
2047 		}
2048 
2049 		mp = dupb(*xmit_tail);
2050 		if (mp == NULL) {
2051 			return (-1);	/* out_of_mem */
2052 		}
2053 
2054 		len = total_hdr_len;
2055 		/*
2056 		 * There are four reasons to allocate a new hdr mblk:
2057 		 *  1) The bytes above us are in use by another packet
2058 		 *  2) We don't have good alignment
2059 		 *  3) The mblk is being shared
2060 		 *  4) We don't have enough room for a header
2061 		 */
2062 		rptr = mp->b_rptr - len;
2063 		if (!OK_32PTR(rptr) ||
2064 		    ((db = mp->b_datap), db->db_ref != 2) ||
2065 		    rptr < db->db_base) {
2066 			/* NOTE: we assume allocb returns an OK_32PTR */
2067 
2068 		must_alloc:;
2069 			mp1 = allocb(connp->conn_ht_iphc_allocated +
2070 			    tcps->tcps_wroff_xtra, BPRI_MED);
2071 			if (mp1 == NULL) {
2072 				freemsg(mp);
2073 				return (-1);	/* out_of_mem */
2074 			}
2075 			mp1->b_cont = mp;
2076 			mp = mp1;
2077 			/* Leave room for Link Level header */
2078 			len = total_hdr_len;
2079 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
2080 			mp->b_wptr = &rptr[len];
2081 		}
2082 
2083 		/*
2084 		 * Fill in the header using the template header, and add
2085 		 * options such as time-stamp, ECN and/or SACK, as needed.
2086 		 */
2087 		tcp_fill_header(tcp, rptr, num_sack_blk);
2088 
2089 		mp->b_rptr = rptr;
2090 
2091 		if (*tail_unsent) {
2092 			int spill = *tail_unsent;
2093 
2094 			mp1 = mp->b_cont;
2095 			if (mp1 == NULL)
2096 				mp1 = mp;
2097 
2098 			/*
2099 			 * If we're a little short, tack on more mblks until
2100 			 * there is no more spillover.
2101 			 */
2102 			while (spill < 0) {
2103 				mblk_t *nmp;
2104 				int nmpsz;
2105 
2106 				nmp = (*xmit_tail)->b_cont;
2107 				nmpsz = MBLKL(nmp);
2108 
2109 				/*
2110 				 * Excess data in mblk; can we split it?
2111 				 * If LSO is enabled for the connection,
2112 				 * keep on splitting as this is a transient
2113 				 * send path.
2114 				 */
2115 				if (!do_lso_send && (spill + nmpsz > 0)) {
2116 					/*
2117 					 * Don't split if stream head was
2118 					 * told to break up larger writes
2119 					 * into smaller ones.
2120 					 */
2121 					if (tcp->tcp_maxpsz_multiplier > 0)
2122 						break;
2123 
2124 					/*
2125 					 * Next mblk is less than SMSS/2
2126 					 * rounded up to nearest 64-byte;
2127 					 * let it get sent as part of the
2128 					 * next segment.
2129 					 */
2130 					if (tcp->tcp_localnet &&
2131 					    !tcp->tcp_cork &&
2132 					    (nmpsz < roundup((mss >> 1), 64)))
2133 						break;
2134 				}
2135 
2136 				*xmit_tail = nmp;
2137 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
2138 				/* Stash for rtt use later */
2139 				(*xmit_tail)->b_prev = local_time;
2140 				(*xmit_tail)->b_next =
2141 				    (mblk_t *)(uintptr_t)(*snxt - len);
2142 				mp1->b_cont = dupb(*xmit_tail);
2143 				mp1 = mp1->b_cont;
2144 
2145 				spill += nmpsz;
2146 				if (mp1 == NULL) {
2147 					*tail_unsent = spill;
2148 					freemsg(mp);
2149 					return (-1);	/* out_of_mem */
2150 				}
2151 			}
2152 
2153 			/* Trim back any surplus on the last mblk */
2154 			if (spill >= 0) {
2155 				mp1->b_wptr -= spill;
2156 				*tail_unsent = spill;
2157 			} else {
2158 				/*
2159 				 * We did not send everything we could in
2160 				 * order to remain within the b_cont limit.
2161 				 */
2162 				*usable -= spill;
2163 				*snxt += spill;
2164 				tcp->tcp_last_sent_len += spill;
2165 				TCPS_UPDATE_MIB(tcps, tcpOutDataBytes, spill);
2166 				tcp->tcp_cs.tcp_out_data_bytes += spill;
2167 				/*
2168 				 * Adjust the checksum
2169 				 */
2170 				tcpha = (tcpha_t *)(rptr +
2171 				    ixa->ixa_ip_hdr_length);
2172 				sum += spill;
2173 				sum = (sum >> 16) + (sum & 0xFFFF);
2174 				tcpha->tha_sum = htons(sum);
2175 				if (connp->conn_ipversion == IPV4_VERSION) {
2176 					sum = ntohs(
2177 					    ((ipha_t *)rptr)->ipha_length) +
2178 					    spill;
2179 					((ipha_t *)rptr)->ipha_length =
2180 					    htons(sum);
2181 				} else {
2182 					sum = ntohs(
2183 					    ((ip6_t *)rptr)->ip6_plen) +
2184 					    spill;
2185 					((ip6_t *)rptr)->ip6_plen =
2186 					    htons(sum);
2187 				}
2188 				ixa->ixa_pktlen += spill;
2189 				*tail_unsent = 0;
2190 			}
2191 		}
2192 		if (tcp->tcp_ip_forward_progress) {
2193 			tcp->tcp_ip_forward_progress = B_FALSE;
2194 			ixa->ixa_flags |= IXAF_REACH_CONF;
2195 		} else {
2196 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
2197 		}
2198 
2199 		if (do_lso_send) {
2200 			/* Append LSO information to the mp. */
2201 			lso_info_set(mp, mss, HW_LSO);
2202 			ixa->ixa_fragsize = IP_MAXPACKET;
2203 			ixa->ixa_extra_ident = num_lso_seg - 1;
2204 
2205 			DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg,
2206 			    boolean_t, B_TRUE);
2207 
2208 			tcp_send_data(tcp, mp);
2209 
2210 			/*
2211 			 * Restore values of ixa_fragsize and ixa_extra_ident.
2212 			 */
2213 			ixa->ixa_fragsize = ixa->ixa_pmtu;
2214 			ixa->ixa_extra_ident = 0;
2215 			TCPS_BUMP_MIB(tcps, tcpHCOutSegs);
2216 			TCP_STAT(tcps, tcp_lso_times);
2217 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
2218 		} else {
2219 			/*
2220 			 * Make sure to clean up LSO information. Wherever a
2221 			 * new mp uses the prepended header room after dupb(),
2222 			 * lso_info_cleanup() should be called.
2223 			 */
2224 			lso_info_cleanup(mp);
2225 			tcp_send_data(tcp, mp);
2226 			TCPS_BUMP_MIB(tcps, tcpHCOutSegs);
2227 		}
2228 	}
2229 
2230 	return (0);
2231 }
2232 
2233 /*
2234  * Initiate closedown sequence on an active connection.  (May be called as
2235  * writer.)  Return value zero for OK return, non-zero for error return.
2236  */
2237 static int
2238 tcp_xmit_end(tcp_t *tcp)
2239 {
2240 	mblk_t		*mp;
2241 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2242 	iulp_t		uinfo;
2243 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2244 	conn_t		*connp = tcp->tcp_connp;
2245 
2246 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
2247 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
2248 		/*
2249 		 * Invalid state, only states TCPS_SYN_RCVD,
2250 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
2251 		 */
2252 		return (-1);
2253 	}
2254 
2255 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
2256 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
2257 	/*
2258 	 * If there is nothing more unsent, send the FIN now.
2259 	 * Otherwise, it will go out with the last segment.
2260 	 */
2261 	if (tcp->tcp_unsent == 0) {
2262 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
2263 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
2264 
2265 		if (mp) {
2266 			tcp_send_data(tcp, mp);
2267 		} else {
2268 			/*
2269 			 * Couldn't allocate msg.  Pretend we got it out.
2270 			 * Wait for rexmit timeout.
2271 			 */
2272 			tcp->tcp_snxt = tcp->tcp_fss + 1;
2273 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
2274 		}
2275 
2276 		/*
2277 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
2278 		 * changed.
2279 		 */
2280 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
2281 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
2282 		}
2283 	} else {
2284 		/*
2285 		 * If tcp->tcp_cork is set, then the data will not get sent,
2286 		 * so we have to check that and unset it first.
2287 		 */
2288 		if (tcp->tcp_cork)
2289 			tcp->tcp_cork = B_FALSE;
2290 		tcp_wput_data(tcp, NULL, B_FALSE);
2291 	}
2292 
2293 	/*
2294 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
2295 	 * is 0, don't update the cache.
2296 	 */
2297 	if (tcps->tcps_rtt_updates == 0 ||
2298 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
2299 		return (0);
2300 
2301 	/*
2302 	 * We do not have a good algorithm to update ssthresh at this time.
2303 	 * So don't do any update.
2304 	 */
2305 	bzero(&uinfo, sizeof (uinfo));
2306 	uinfo.iulp_rtt = NSEC2MSEC(tcp->tcp_rtt_sa);
2307 	uinfo.iulp_rtt_sd = NSEC2MSEC(tcp->tcp_rtt_sd);
2308 
2309 	/*
2310 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
2311 	 * if source routed but we don't.
2312 	 */
2313 	if (connp->conn_ipversion == IPV4_VERSION) {
2314 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
2315 			return (0);
2316 		}
2317 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
2318 	} else {
2319 		uint_t ifindex;
2320 
2321 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
2322 		    &tcp->tcp_ip6h->ip6_dst))) {
2323 			return (0);
2324 		}
2325 		ifindex = 0;
2326 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
2327 			ip_xmit_attr_t *ixa = connp->conn_ixa;
2328 
2329 			/*
2330 			 * If we are going to create a DCE we'd better have
2331 			 * an ifindex
2332 			 */
2333 			if (ixa->ixa_nce != NULL) {
2334 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
2335 				    ill_phyint->phyint_ifindex;
2336 			} else {
2337 				return (0);
2338 			}
2339 		}
2340 
2341 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
2342 		    ipst);
2343 	}
2344 	return (0);
2345 }
2346 
2347 /*
2348  * Send out a control packet on the tcp connection specified.  This routine
2349  * is typically called where we need a simple ACK or RST generated.
2350  */
2351 void
2352 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
2353 {
2354 	uchar_t		*rptr;
2355 	tcpha_t		*tcpha;
2356 	ipha_t		*ipha = NULL;
2357 	ip6_t		*ip6h = NULL;
2358 	uint32_t	sum;
2359 	int		total_hdr_len;
2360 	int		ip_hdr_len;
2361 	mblk_t		*mp;
2362 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2363 	conn_t		*connp = tcp->tcp_connp;
2364 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
2365 
2366 	/*
2367 	 * Save sum for use in source route later.
2368 	 */
2369 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
2370 	total_hdr_len = connp->conn_ht_iphc_len;
2371 	ip_hdr_len = ixa->ixa_ip_hdr_length;
2372 
2373 	/* If a text string is passed in with the request, pass it to strlog. */
2374 	if (str != NULL && connp->conn_debug) {
2375 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
2376 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
2377 		    str, seq, ack, ctl);
2378 	}
2379 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
2380 	    BPRI_MED);
2381 	if (mp == NULL) {
2382 		return;
2383 	}
2384 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
2385 	mp->b_rptr = rptr;
2386 	mp->b_wptr = &rptr[total_hdr_len];
2387 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
2388 
2389 	ixa->ixa_pktlen = total_hdr_len;
2390 
2391 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
2392 		ipha = (ipha_t *)rptr;
2393 		ipha->ipha_length = htons(total_hdr_len);
2394 	} else {
2395 		ip6h = (ip6_t *)rptr;
2396 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
2397 	}
2398 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
2399 	tcpha->tha_flags = (uint8_t)ctl;
2400 	if (ctl & TH_RST) {
2401 		TCPS_BUMP_MIB(tcps, tcpOutRsts);
2402 		TCPS_BUMP_MIB(tcps, tcpOutControl);
2403 		/*
2404 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
2405 		 */
2406 		if (tcp->tcp_snd_ts_ok &&
2407 		    tcp->tcp_state > TCPS_SYN_SENT) {
2408 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
2409 			*(mp->b_wptr) = TCPOPT_EOL;
2410 
2411 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
2412 
2413 			if (connp->conn_ipversion == IPV4_VERSION) {
2414 				ipha->ipha_length = htons(total_hdr_len -
2415 				    TCPOPT_REAL_TS_LEN);
2416 			} else {
2417 				ip6h->ip6_plen = htons(total_hdr_len -
2418 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
2419 			}
2420 			tcpha->tha_offset_and_reserved -= (3 << 4);
2421 			sum -= TCPOPT_REAL_TS_LEN;
2422 		}
2423 	}
2424 	if (ctl & TH_ACK) {
2425 		if (tcp->tcp_snd_ts_ok) {
2426 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
2427 
2428 			U32_TO_BE32(llbolt,
2429 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
2430 			U32_TO_BE32(tcp->tcp_ts_recent,
2431 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
2432 		}
2433 
2434 		/* Update the latest receive window size in TCP header. */
2435 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
2436 		/* Track what we sent to the peer */
2437 		tcp->tcp_tcpha->tha_win = tcpha->tha_win;
2438 		tcp->tcp_rack = ack;
2439 		tcp->tcp_rack_cnt = 0;
2440 		TCPS_BUMP_MIB(tcps, tcpOutAck);
2441 	}
2442 	TCPS_BUMP_MIB(tcps, tcpHCOutSegs);
2443 	tcpha->tha_seq = htonl(seq);
2444 	tcpha->tha_ack = htonl(ack);
2445 	/*
2446 	 * Include the adjustment for a source route if any.
2447 	 */
2448 	sum = (sum >> 16) + (sum & 0xFFFF);
2449 	tcpha->tha_sum = htons(sum);
2450 	tcp_send_data(tcp, mp);
2451 }
2452 
2453 /*
2454  * Generate a reset based on an inbound packet, connp is set by caller
2455  * when RST is in response to an unexpected inbound packet for which
2456  * there is active tcp state in the system.
2457  *
2458  * IPSEC NOTE : Try to send the reply with the same protection as it came
2459  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
2460  * That way the packet will go out at the same level of protection as it
2461  * came in with.
2462  */
2463 static void
2464 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
2465     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
2466 {
2467 	ipha_t		*ipha = NULL;
2468 	ip6_t		*ip6h = NULL;
2469 	ushort_t	len;
2470 	tcpha_t		*tcpha;
2471 	int		i;
2472 	ipaddr_t	v4addr;
2473 	in6_addr_t	v6addr;
2474 	netstack_t	*ns = ipst->ips_netstack;
2475 	tcp_stack_t	*tcps = ns->netstack_tcp;
2476 	ip_xmit_attr_t	ixas, *ixa;
2477 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
2478 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
2479 	ushort_t	port;
2480 
2481 	if (!tcp_send_rst_chk(tcps)) {
2482 		TCP_STAT(tcps, tcp_rst_unsent);
2483 		freemsg(mp);
2484 		return;
2485 	}
2486 
2487 	/*
2488 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
2489 	 * options from the listener. In that case the caller must ensure that
2490 	 * we are running on the listener = connp squeue.
2491 	 *
2492 	 * We get a safe copy of conn_ixa so we don't need to restore anything
2493 	 * we or ip_output_simple might change in the ixa.
2494 	 */
2495 	if (connp != NULL) {
2496 		ASSERT(connp->conn_on_sqp);
2497 
2498 		ixa = conn_get_ixa_exclusive(connp);
2499 		if (ixa == NULL) {
2500 			TCP_STAT(tcps, tcp_rst_unsent);
2501 			freemsg(mp);
2502 			return;
2503 		}
2504 		need_refrele = B_TRUE;
2505 	} else {
2506 		bzero(&ixas, sizeof (ixas));
2507 		ixa = &ixas;
2508 		/*
2509 		 * IXAF_VERIFY_SOURCE is overkill since we know the
2510 		 * packet was for us.
2511 		 */
2512 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
2513 		ixa->ixa_protocol = IPPROTO_TCP;
2514 		ixa->ixa_zoneid = ira->ira_zoneid;
2515 		ixa->ixa_ifindex = 0;
2516 		ixa->ixa_ipst = ipst;
2517 		ixa->ixa_cred = kcred;
2518 		ixa->ixa_cpid = NOPID;
2519 	}
2520 
2521 	if (str && tcps->tcps_dbg) {
2522 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
2523 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
2524 		    "flags 0x%x",
2525 		    str, seq, ack, ctl);
2526 	}
2527 	if (mp->b_datap->db_ref != 1) {
2528 		mblk_t *mp1 = copyb(mp);
2529 		freemsg(mp);
2530 		mp = mp1;
2531 		if (mp == NULL)
2532 			goto done;
2533 	} else if (mp->b_cont) {
2534 		freemsg(mp->b_cont);
2535 		mp->b_cont = NULL;
2536 		DB_CKSUMFLAGS(mp) = 0;
2537 	}
2538 	/*
2539 	 * We skip reversing source route here.
2540 	 * (for now we replace all IP options with EOL)
2541 	 */
2542 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
2543 		ipha = (ipha_t *)mp->b_rptr;
2544 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
2545 			mp->b_rptr[i] = IPOPT_EOL;
2546 		/*
2547 		 * Make sure that src address isn't flagrantly invalid.
2548 		 * Not all broadcast address checking for the src address
2549 		 * is possible, since we don't know the netmask of the src
2550 		 * addr.  No check for destination address is done, since
2551 		 * IP will not pass up a packet with a broadcast dest
2552 		 * address to TCP.  Similar checks are done below for IPv6.
2553 		 */
2554 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
2555 		    CLASSD(ipha->ipha_src)) {
2556 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2557 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
2558 			freemsg(mp);
2559 			goto done;
2560 		}
2561 	} else {
2562 		ip6h = (ip6_t *)mp->b_rptr;
2563 
2564 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
2565 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
2566 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
2567 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
2568 			freemsg(mp);
2569 			goto done;
2570 		}
2571 
2572 		/* Remove any extension headers assuming partial overlay */
2573 		if (ip_hdr_len > IPV6_HDR_LEN) {
2574 			uint8_t *to;
2575 
2576 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
2577 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
2578 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
2579 			ip_hdr_len = IPV6_HDR_LEN;
2580 			ip6h = (ip6_t *)mp->b_rptr;
2581 			ip6h->ip6_nxt = IPPROTO_TCP;
2582 		}
2583 	}
2584 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
2585 	if (tcpha->tha_flags & TH_RST) {
2586 		freemsg(mp);
2587 		goto done;
2588 	}
2589 	tcpha->tha_offset_and_reserved = (5 << 4);
2590 	len = ip_hdr_len + sizeof (tcpha_t);
2591 	mp->b_wptr = &mp->b_rptr[len];
2592 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
2593 		ipha->ipha_length = htons(len);
2594 		/* Swap addresses */
2595 		v4addr = ipha->ipha_src;
2596 		ipha->ipha_src = ipha->ipha_dst;
2597 		ipha->ipha_dst = v4addr;
2598 		ipha->ipha_ident = 0;
2599 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
2600 		ixa->ixa_flags |= IXAF_IS_IPV4;
2601 		ixa->ixa_ip_hdr_length = ip_hdr_len;
2602 	} else {
2603 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
2604 		/* Swap addresses */
2605 		v6addr = ip6h->ip6_src;
2606 		ip6h->ip6_src = ip6h->ip6_dst;
2607 		ip6h->ip6_dst = v6addr;
2608 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
2609 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
2610 
2611 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
2612 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
2613 			ixa->ixa_scopeid = ira->ira_ruifindex;
2614 		}
2615 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
2616 	}
2617 	ixa->ixa_pktlen = len;
2618 
2619 	/* Swap the ports */
2620 	port = tcpha->tha_fport;
2621 	tcpha->tha_fport = tcpha->tha_lport;
2622 	tcpha->tha_lport = port;
2623 
2624 	tcpha->tha_ack = htonl(ack);
2625 	tcpha->tha_seq = htonl(seq);
2626 	tcpha->tha_win = 0;
2627 	tcpha->tha_sum = htons(sizeof (tcpha_t));
2628 	tcpha->tha_flags = (uint8_t)ctl;
2629 	if (ctl & TH_RST) {
2630 		if (ctl & TH_ACK) {
2631 			/*
2632 			 * Probe connection rejection here.
2633 			 * tcp_xmit_listeners_reset() drops non-SYN segments
2634 			 * that do not specify TH_ACK in their flags without
2635 			 * calling this function.  As a consequence, if this
2636 			 * function is called with a TH_RST|TH_ACK ctl argument,
2637 			 * it is being called in response to a SYN segment
2638 			 * and thus the tcp:::accept-refused probe point
2639 			 * is valid here.
2640 			 */
2641 			DTRACE_TCP5(accept__refused, mblk_t *, NULL,
2642 			    void, NULL, void_ip_t *, mp->b_rptr, tcp_t *, NULL,
2643 			    tcph_t *, tcpha);
2644 		}
2645 		TCPS_BUMP_MIB(tcps, tcpOutRsts);
2646 		TCPS_BUMP_MIB(tcps, tcpOutControl);
2647 	}
2648 
2649 	/* Discard any old label */
2650 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
2651 		ASSERT(ixa->ixa_tsl != NULL);
2652 		label_rele(ixa->ixa_tsl);
2653 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
2654 	}
2655 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2656 
2657 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2658 		/*
2659 		 * Apply IPsec based on how IPsec was applied to
2660 		 * the packet that caused the RST.
2661 		 */
2662 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
2663 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2664 			/* Note: mp already consumed and ip_drop_packet done */
2665 			goto done;
2666 		}
2667 	} else {
2668 		/*
2669 		 * This is in clear. The RST message we are building
2670 		 * here should go out in clear, independent of our policy.
2671 		 */
2672 		ixa->ixa_flags |= IXAF_NO_IPSEC;
2673 	}
2674 
2675 	DTRACE_TCP5(send, mblk_t *, NULL, ip_xmit_attr_t *, ixa,
2676 	    __dtrace_tcp_void_ip_t *, mp->b_rptr, tcp_t *, NULL,
2677 	    __dtrace_tcp_tcph_t *, tcpha);
2678 
2679 	/*
2680 	 * NOTE:  one might consider tracing a TCP packet here, but
2681 	 * this function has no active TCP state and no tcp structure
2682 	 * that has a trace buffer.  If we traced here, we would have
2683 	 * to keep a local trace buffer in tcp_record_trace().
2684 	 */
2685 
2686 	(void) ip_output_simple(mp, ixa);
2687 done:
2688 	ixa_cleanup(ixa);
2689 	if (need_refrele) {
2690 		ASSERT(ixa != &ixas);
2691 		ixa_refrele(ixa);
2692 	}
2693 }
2694 
2695 /*
2696  * Generate a "no listener here" RST in response to an "unknown" segment.
2697  * connp is set by caller when RST is in response to an unexpected
2698  * inbound packet for which there is active tcp state in the system.
2699  * Note that we are reusing the incoming mp to construct the outgoing RST.
2700  */
2701 void
2702 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
2703     conn_t *connp)
2704 {
2705 	uchar_t		*rptr;
2706 	uint32_t	seg_len;
2707 	tcpha_t		*tcpha;
2708 	uint32_t	seg_seq;
2709 	uint32_t	seg_ack;
2710 	uint_t		flags;
2711 	ipha_t		*ipha;
2712 	ip6_t		*ip6h;
2713 	boolean_t	policy_present;
2714 	netstack_t	*ns = ipst->ips_netstack;
2715 	tcp_stack_t	*tcps = ns->netstack_tcp;
2716 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
2717 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
2718 
2719 	TCP_STAT(tcps, tcp_no_listener);
2720 
2721 	/*
2722 	 * DTrace this "unknown" segment as a tcp:::receive, as we did
2723 	 * just receive something that was TCP.
2724 	 */
2725 	DTRACE_TCP5(receive, mblk_t *, NULL, ip_xmit_attr_t *, NULL,
2726 	    __dtrace_tcp_void_ip_t *, mp->b_rptr, tcp_t *, NULL,
2727 	    __dtrace_tcp_tcph_t *, &mp->b_rptr[ip_hdr_len]);
2728 
2729 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
2730 		policy_present = ipss->ipsec_inbound_v4_policy_present;
2731 		ipha = (ipha_t *)mp->b_rptr;
2732 		ip6h = NULL;
2733 	} else {
2734 		policy_present = ipss->ipsec_inbound_v6_policy_present;
2735 		ipha = NULL;
2736 		ip6h = (ip6_t *)mp->b_rptr;
2737 	}
2738 
2739 	if (policy_present) {
2740 		/*
2741 		 * The conn_t parameter is NULL because we already know
2742 		 * nobody's home.
2743 		 */
2744 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
2745 		    ira, ns);
2746 		if (mp == NULL)
2747 			return;
2748 	}
2749 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
2750 		DTRACE_PROBE2(
2751 		    tx__ip__log__error__nolistener__tcp,
2752 		    char *, "Could not reply with RST to mp(1)",
2753 		    mblk_t *, mp);
2754 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
2755 		freemsg(mp);
2756 		return;
2757 	}
2758 
2759 	rptr = mp->b_rptr;
2760 
2761 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
2762 	seg_seq = ntohl(tcpha->tha_seq);
2763 	seg_ack = ntohl(tcpha->tha_ack);
2764 	flags = tcpha->tha_flags;
2765 
2766 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
2767 	if (flags & TH_RST) {
2768 		freemsg(mp);
2769 	} else if (flags & TH_ACK) {
2770 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
2771 		    ira, ipst, connp);
2772 	} else {
2773 		if (flags & TH_SYN) {
2774 			seg_len++;
2775 		} else {
2776 			/*
2777 			 * Here we violate the RFC.  Note that a normal
2778 			 * TCP will never send a segment without the ACK
2779 			 * flag, except for RST or SYN segment.  This
2780 			 * segment is neither.  Just drop it on the
2781 			 * floor.
2782 			 */
2783 			freemsg(mp);
2784 			TCP_STAT(tcps, tcp_rst_unsent);
2785 			return;
2786 		}
2787 
2788 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
2789 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
2790 	}
2791 }
2792 
2793 /*
2794  * Helper function for tcp_xmit_mp() in handling connection set up flag
2795  * options setting.
2796  */
2797 static void
2798 tcp_xmit_mp_aux_iss(tcp_t *tcp, conn_t *connp, tcpha_t *tcpha, mblk_t *mp,
2799     uint_t *flags)
2800 {
2801 	uint32_t u1;
2802 	uint8_t	*wptr = mp->b_wptr;
2803 	tcp_stack_t *tcps = tcp->tcp_tcps;
2804 	boolean_t add_sack = B_FALSE;
2805 
2806 	/*
2807 	 * If TCP_ISS_VALID and the seq number is tcp_iss,
2808 	 * TCP can only be in SYN-SENT, SYN-RCVD or
2809 	 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
2810 	 * our SYN is not ack'ed but the app closes this
2811 	 * TCP connection.
2812 	 */
2813 	ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
2814 	    tcp->tcp_state == TCPS_SYN_RCVD ||
2815 	    tcp->tcp_state == TCPS_FIN_WAIT_1);
2816 
2817 	/*
2818 	 * Tack on the MSS option.  It is always needed
2819 	 * for both active and passive open.
2820 	 *
2821 	 * MSS option value should be interface MTU - MIN
2822 	 * TCP/IP header according to RFC 793 as it means
2823 	 * the maximum segment size TCP can receive.  But
2824 	 * to get around some broken middle boxes/end hosts
2825 	 * out there, we allow the option value to be the
2826 	 * same as the MSS option size on the peer side.
2827 	 * In this way, the other side will not send
2828 	 * anything larger than they can receive.
2829 	 *
2830 	 * Note that for SYN_SENT state, the ndd param
2831 	 * tcp_use_smss_as_mss_opt has no effect as we
2832 	 * don't know the peer's MSS option value. So
2833 	 * the only case we need to take care of is in
2834 	 * SYN_RCVD state, which is done later.
2835 	 */
2836 	wptr[0] = TCPOPT_MAXSEG;
2837 	wptr[1] = TCPOPT_MAXSEG_LEN;
2838 	wptr += 2;
2839 	u1 = tcp->tcp_initial_pmtu - (connp->conn_ipversion == IPV4_VERSION ?
2840 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) - TCP_MIN_HEADER_LENGTH;
2841 	U16_TO_BE16(u1, wptr);
2842 	wptr += 2;
2843 
2844 	/* Update the offset to cover the additional word */
2845 	tcpha->tha_offset_and_reserved += (1 << 4);
2846 
2847 	switch (tcp->tcp_state) {
2848 	case TCPS_SYN_SENT:
2849 		*flags = TH_SYN;
2850 
2851 		if (tcp->tcp_snd_sack_ok)
2852 			add_sack = B_TRUE;
2853 
2854 		if (tcp->tcp_snd_ts_ok) {
2855 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
2856 
2857 			if (add_sack) {
2858 				wptr[0] = TCPOPT_SACK_PERMITTED;
2859 				wptr[1] = TCPOPT_SACK_OK_LEN;
2860 				add_sack = B_FALSE;
2861 			} else {
2862 				wptr[0] = TCPOPT_NOP;
2863 				wptr[1] = TCPOPT_NOP;
2864 			}
2865 			wptr[2] = TCPOPT_TSTAMP;
2866 			wptr[3] = TCPOPT_TSTAMP_LEN;
2867 			wptr += 4;
2868 			U32_TO_BE32(llbolt, wptr);
2869 			wptr += 4;
2870 			ASSERT(tcp->tcp_ts_recent == 0);
2871 			U32_TO_BE32(0L, wptr);
2872 			wptr += 4;
2873 			tcpha->tha_offset_and_reserved += (3 << 4);
2874 		}
2875 
2876 		/*
2877 		 * Set up all the bits to tell other side
2878 		 * we are ECN capable.
2879 		 */
2880 		if (tcp->tcp_ecn_ok)
2881 			*flags |= (TH_ECE | TH_CWR);
2882 
2883 		break;
2884 
2885 	case TCPS_SYN_RCVD:
2886 		*flags |= TH_SYN;
2887 
2888 		/*
2889 		 * Reset the MSS option value to be SMSS
2890 		 * We should probably add back the bytes
2891 		 * for timestamp option and IPsec.  We
2892 		 * don't do that as this is a workaround
2893 		 * for broken middle boxes/end hosts, it
2894 		 * is better for us to be more cautious.
2895 		 * They may not take these things into
2896 		 * account in their SMSS calculation.  Thus
2897 		 * the peer's calculated SMSS may be smaller
2898 		 * than what it can be.  This should be OK.
2899 		 */
2900 		if (tcps->tcps_use_smss_as_mss_opt) {
2901 			u1 = tcp->tcp_mss;
2902 			/*
2903 			 * Note that wptr points just past the MSS
2904 			 * option value.
2905 			 */
2906 			U16_TO_BE16(u1, wptr - 2);
2907 		}
2908 
2909 		/*
2910 		 * tcp_snd_ts_ok can only be set in TCPS_SYN_RCVD
2911 		 * when the peer also uses timestamps option.  And
2912 		 * the TCP header template must have already been
2913 		 * updated to include the timestamps option.
2914 		 */
2915 		if (tcp->tcp_snd_sack_ok) {
2916 			if (tcp->tcp_snd_ts_ok) {
2917 				uint8_t *tmp_wptr;
2918 
2919 				/*
2920 				 * Use the NOP in the header just
2921 				 * before timestamps opton.
2922 				 */
2923 				tmp_wptr = (uint8_t *)tcpha +
2924 				    TCP_MIN_HEADER_LENGTH;
2925 				ASSERT(tmp_wptr[0] == TCPOPT_NOP &&
2926 				    tmp_wptr[1] == TCPOPT_NOP);
2927 				tmp_wptr[0] = TCPOPT_SACK_PERMITTED;
2928 				tmp_wptr[1] = TCPOPT_SACK_OK_LEN;
2929 			} else {
2930 				add_sack = B_TRUE;
2931 			}
2932 		}
2933 
2934 
2935 		/*
2936 		 * If the other side is ECN capable, reply
2937 		 * that we are also ECN capable.
2938 		 */
2939 		if (tcp->tcp_ecn_ok)
2940 			*flags |= TH_ECE;
2941 		break;
2942 
2943 	default:
2944 		/*
2945 		 * The above ASSERT() makes sure that this
2946 		 * must be FIN-WAIT-1 state.  Our SYN has
2947 		 * not been ack'ed so retransmit it.
2948 		 */
2949 		*flags |= TH_SYN;
2950 		break;
2951 	}
2952 
2953 	if (add_sack) {
2954 		wptr[0] = TCPOPT_NOP;
2955 		wptr[1] = TCPOPT_NOP;
2956 		wptr[2] = TCPOPT_SACK_PERMITTED;
2957 		wptr[3] = TCPOPT_SACK_OK_LEN;
2958 		wptr += TCPOPT_REAL_SACK_OK_LEN;
2959 		tcpha->tha_offset_and_reserved += (1 << 4);
2960 	}
2961 
2962 	if (tcp->tcp_snd_ws_ok) {
2963 		wptr[0] =  TCPOPT_NOP;
2964 		wptr[1] =  TCPOPT_WSCALE;
2965 		wptr[2] =  TCPOPT_WS_LEN;
2966 		wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
2967 		wptr += TCPOPT_REAL_WS_LEN;
2968 		tcpha->tha_offset_and_reserved += (1 << 4);
2969 	}
2970 
2971 	mp->b_wptr = wptr;
2972 	u1 = (int)(mp->b_wptr - mp->b_rptr);
2973 	/*
2974 	 * Get IP set to checksum on our behalf
2975 	 * Include the adjustment for a source route if any.
2976 	 */
2977 	u1 += connp->conn_sum;
2978 	u1 = (u1 >> 16) + (u1 & 0xFFFF);
2979 	tcpha->tha_sum = htons(u1);
2980 	TCPS_BUMP_MIB(tcps, tcpOutControl);
2981 }
2982 
2983 /*
2984  * Helper function for tcp_xmit_mp() in handling connection tear down
2985  * flag setting and state changes.
2986  */
2987 static void
2988 tcp_xmit_mp_aux_fss(tcp_t *tcp, ip_xmit_attr_t *ixa, uint_t *flags)
2989 {
2990 	if (!tcp->tcp_fin_acked) {
2991 		*flags |= TH_FIN;
2992 		TCPS_BUMP_MIB(tcp->tcp_tcps, tcpOutControl);
2993 	}
2994 	if (!tcp->tcp_fin_sent) {
2995 		tcp->tcp_fin_sent = B_TRUE;
2996 		switch (tcp->tcp_state) {
2997 		case TCPS_SYN_RCVD:
2998 			tcp->tcp_state = TCPS_FIN_WAIT_1;
2999 			DTRACE_TCP6(state__change, void, NULL,
3000 			    ip_xmit_attr_t *, ixa, void, NULL,
3001 			    tcp_t *, tcp, void, NULL,
3002 			    int32_t, TCPS_SYN_RCVD);
3003 			break;
3004 		case TCPS_ESTABLISHED:
3005 			tcp->tcp_state = TCPS_FIN_WAIT_1;
3006 			DTRACE_TCP6(state__change, void, NULL,
3007 			    ip_xmit_attr_t *, ixa, void, NULL,
3008 			    tcp_t *, tcp, void, NULL,
3009 			    int32_t, TCPS_ESTABLISHED);
3010 			break;
3011 		case TCPS_CLOSE_WAIT:
3012 			tcp->tcp_state = TCPS_LAST_ACK;
3013 			DTRACE_TCP6(state__change, void, NULL,
3014 			    ip_xmit_attr_t *, ixa, void, NULL,
3015 			    tcp_t *, tcp, void, NULL,
3016 			    int32_t, TCPS_CLOSE_WAIT);
3017 			break;
3018 		}
3019 		if (tcp->tcp_suna == tcp->tcp_snxt)
3020 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
3021 		tcp->tcp_snxt = tcp->tcp_fss + 1;
3022 	}
3023 }
3024 
3025 /*
3026  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
3027  * ip and tcp header ready to pass down to IP.  If the mp passed in is
3028  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
3029  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
3030  * otherwise it will dup partial mblks.)
3031  * Otherwise, an appropriate ACK packet will be generated.  This
3032  * routine is not usually called to send new data for the first time.  It
3033  * is mostly called out of the timer for retransmits, and to generate ACKs.
3034  *
3035  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
3036  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
3037  * of the original mblk chain will be returned in *offset and *end_mp.
3038  */
3039 mblk_t *
3040 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
3041     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
3042     boolean_t rexmit)
3043 {
3044 	int	data_length;
3045 	int32_t	off = 0;
3046 	uint_t	flags;
3047 	mblk_t	*mp1;
3048 	mblk_t	*mp2;
3049 	uchar_t	*rptr;
3050 	tcpha_t	*tcpha;
3051 	int32_t	num_sack_blk = 0;
3052 	int32_t	sack_opt_len = 0;
3053 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3054 	conn_t		*connp = tcp->tcp_connp;
3055 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
3056 
3057 	/* Allocate for our maximum TCP header + link-level */
3058 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
3059 	    BPRI_MED);
3060 	if (mp1 == NULL)
3061 		return (NULL);
3062 	data_length = 0;
3063 
3064 	/*
3065 	 * Note that tcp_mss has been adjusted to take into account the
3066 	 * timestamp option if applicable.  Because SACK options do not
3067 	 * appear in every TCP segments and they are of variable lengths,
3068 	 * they cannot be included in tcp_mss.  Thus we need to calculate
3069 	 * the actual segment length when we need to send a segment which
3070 	 * includes SACK options.
3071 	 */
3072 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
3073 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
3074 		    tcp->tcp_num_sack_blk);
3075 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
3076 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
3077 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
3078 			max_to_send -= sack_opt_len;
3079 	}
3080 
3081 	if (offset != NULL) {
3082 		off = *offset;
3083 		/* We use offset as an indicator that end_mp is not NULL. */
3084 		*end_mp = NULL;
3085 	}
3086 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
3087 		/* This could be faster with cooperation from downstream */
3088 		if (mp2 != mp1 && !sendall &&
3089 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
3090 		    max_to_send)
3091 			/*
3092 			 * Don't send the next mblk since the whole mblk
3093 			 * does not fit.
3094 			 */
3095 			break;
3096 		mp2->b_cont = dupb(mp);
3097 		mp2 = mp2->b_cont;
3098 		if (!mp2) {
3099 			freemsg(mp1);
3100 			return (NULL);
3101 		}
3102 		mp2->b_rptr += off;
3103 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
3104 		    (uintptr_t)INT_MAX);
3105 
3106 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
3107 		if (data_length > max_to_send) {
3108 			mp2->b_wptr -= data_length - max_to_send;
3109 			data_length = max_to_send;
3110 			off = mp2->b_wptr - mp->b_rptr;
3111 			break;
3112 		} else {
3113 			off = 0;
3114 		}
3115 	}
3116 	if (offset != NULL) {
3117 		*offset = off;
3118 		*end_mp = mp;
3119 	}
3120 	if (seg_len != NULL) {
3121 		*seg_len = data_length;
3122 	}
3123 
3124 	/* Update the latest receive window size in TCP header. */
3125 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
3126 
3127 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
3128 	mp1->b_rptr = rptr;
3129 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
3130 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
3131 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
3132 	tcpha->tha_seq = htonl(seq);
3133 
3134 	/*
3135 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
3136 	 * that this function was called from tcp_wput_data. Thus, when called
3137 	 * to retransmit data the setting of the PUSH bit may appear some
3138 	 * what random in that it might get set when it should not. This
3139 	 * should not pose any performance issues.
3140 	 */
3141 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
3142 	    tcp->tcp_unsent == data_length)) {
3143 		flags = TH_ACK | TH_PUSH;
3144 	} else {
3145 		flags = TH_ACK;
3146 	}
3147 
3148 	if (tcp->tcp_ecn_ok) {
3149 		if (tcp->tcp_ecn_echo_on)
3150 			flags |= TH_ECE;
3151 
3152 		/*
3153 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
3154 		 * There is no TCP flow control for non-data segments, and
3155 		 * only data segment is transmitted reliably.
3156 		 */
3157 		if (data_length > 0 && !rexmit) {
3158 			TCP_SET_ECT(tcp, rptr);
3159 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
3160 				flags |= TH_CWR;
3161 				tcp->tcp_ecn_cwr_sent = B_TRUE;
3162 			}
3163 		}
3164 	}
3165 
3166 	/* Check if there is any special processing needs to be done. */
3167 	if (tcp->tcp_valid_bits) {
3168 		uint32_t u1;
3169 
3170 		/* We don't allow having SYN and FIN in the same segment... */
3171 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
3172 		    seq == tcp->tcp_iss) {
3173 			/* Need to do connection set up processing. */
3174 			tcp_xmit_mp_aux_iss(tcp, connp, tcpha, mp1, &flags);
3175 		} else if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
3176 		    (seq + data_length) == tcp->tcp_fss) {
3177 			/* Need to do connection tear down processing. */
3178 			tcp_xmit_mp_aux_fss(tcp, ixa, &flags);
3179 		}
3180 
3181 		/*
3182 		 * Need to do urgent pointer processing.
3183 		 *
3184 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
3185 		 * is smaller than seq, u1 will become a very huge value.
3186 		 * So the comparison will fail.  Also note that tcp_urp
3187 		 * should be positive, see RFC 793 page 17.
3188 		 */
3189 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
3190 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
3191 		    u1 < (uint32_t)(64 * 1024)) {
3192 			flags |= TH_URG;
3193 			TCPS_BUMP_MIB(tcps, tcpOutUrg);
3194 			tcpha->tha_urp = htons(u1);
3195 		}
3196 	}
3197 	tcpha->tha_flags = (uchar_t)flags;
3198 	tcp->tcp_rack = tcp->tcp_rnxt;
3199 	tcp->tcp_rack_cnt = 0;
3200 
3201 	/* Fill in the current value of timestamps option. */
3202 	if (tcp->tcp_snd_ts_ok) {
3203 		if (tcp->tcp_state != TCPS_SYN_SENT) {
3204 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
3205 
3206 			U32_TO_BE32(llbolt,
3207 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
3208 			U32_TO_BE32(tcp->tcp_ts_recent,
3209 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
3210 		}
3211 	}
3212 
3213 	/* Fill in the SACK blocks. */
3214 	if (num_sack_blk > 0) {
3215 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
3216 		sack_blk_t *tmp;
3217 		int32_t	i;
3218 
3219 		wptr[0] = TCPOPT_NOP;
3220 		wptr[1] = TCPOPT_NOP;
3221 		wptr[2] = TCPOPT_SACK;
3222 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
3223 		    sizeof (sack_blk_t);
3224 		wptr += TCPOPT_REAL_SACK_LEN;
3225 
3226 		tmp = tcp->tcp_sack_list;
3227 		for (i = 0; i < num_sack_blk; i++) {
3228 			U32_TO_BE32(tmp[i].begin, wptr);
3229 			wptr += sizeof (tcp_seq);
3230 			U32_TO_BE32(tmp[i].end, wptr);
3231 			wptr += sizeof (tcp_seq);
3232 		}
3233 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
3234 	}
3235 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
3236 	data_length += (int)(mp1->b_wptr - rptr);
3237 
3238 	ixa->ixa_pktlen = data_length;
3239 
3240 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
3241 		((ipha_t *)rptr)->ipha_length = htons(data_length);
3242 	} else {
3243 		ip6_t *ip6 = (ip6_t *)rptr;
3244 
3245 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
3246 	}
3247 
3248 	/*
3249 	 * Prime pump for IP
3250 	 * Include the adjustment for a source route if any.
3251 	 */
3252 	data_length -= ixa->ixa_ip_hdr_length;
3253 	data_length += connp->conn_sum;
3254 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
3255 	tcpha->tha_sum = htons(data_length);
3256 	if (tcp->tcp_ip_forward_progress) {
3257 		tcp->tcp_ip_forward_progress = B_FALSE;
3258 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
3259 	} else {
3260 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
3261 	}
3262 	return (mp1);
3263 }
3264 
3265 /*
3266  * If this routine returns B_TRUE, TCP can generate a RST in response
3267  * to a segment.  If it returns B_FALSE, TCP should not respond.
3268  */
3269 static boolean_t
3270 tcp_send_rst_chk(tcp_stack_t *tcps)
3271 {
3272 	int64_t	now;
3273 
3274 	/*
3275 	 * TCP needs to protect itself from generating too many RSTs.
3276 	 * This can be a DoS attack by sending us random segments
3277 	 * soliciting RSTs.
3278 	 *
3279 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
3280 	 * in each 1 second interval.  In this way, TCP still generate
3281 	 * RSTs in normal cases but when under attack, the impact is
3282 	 * limited.
3283 	 */
3284 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
3285 		now = ddi_get_lbolt64();
3286 		if (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
3287 		    1*SECONDS) {
3288 			tcps->tcps_last_rst_intrvl = now;
3289 			tcps->tcps_rst_cnt = 1;
3290 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
3291 			return (B_FALSE);
3292 		}
3293 	}
3294 	return (B_TRUE);
3295 }
3296 
3297 /*
3298  * This function handles all retransmissions if SACK is enabled for this
3299  * connection.  First it calculates how many segments can be retransmitted
3300  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
3301  * segments.  A segment is eligible if sack_cnt for that segment is greater
3302  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
3303  * all eligible segments, it checks to see if TCP can send some new segments
3304  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
3305  *
3306  * Parameters:
3307  *	tcp_t *tcp: the tcp structure of the connection.
3308  *	uint_t *flags: in return, appropriate value will be set for
3309  *	tcp_input_data().
3310  */
3311 void
3312 tcp_sack_rexmit(tcp_t *tcp, uint_t *flags)
3313 {
3314 	notsack_blk_t	*notsack_blk;
3315 	int32_t		usable_swnd;
3316 	int32_t		mss;
3317 	uint32_t	seg_len;
3318 	mblk_t		*xmit_mp;
3319 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3320 
3321 	ASSERT(tcp->tcp_notsack_list != NULL);
3322 	ASSERT(tcp->tcp_rexmit == B_FALSE);
3323 
3324 	/* Defensive coding in case there is a bug... */
3325 	if (tcp->tcp_notsack_list == NULL) {
3326 		return;
3327 	}
3328 	notsack_blk = tcp->tcp_notsack_list;
3329 	mss = tcp->tcp_mss;
3330 
3331 	/*
3332 	 * Limit the num of outstanding data in the network to be
3333 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
3334 	 */
3335 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
3336 
3337 	/* At least retransmit 1 MSS of data. */
3338 	if (usable_swnd <= 0) {
3339 		usable_swnd = mss;
3340 	}
3341 
3342 	/* Make sure no new RTT samples will be taken. */
3343 	tcp->tcp_csuna = tcp->tcp_snxt;
3344 
3345 	notsack_blk = tcp->tcp_notsack_list;
3346 	while (usable_swnd > 0) {
3347 		mblk_t		*snxt_mp, *tmp_mp;
3348 		tcp_seq		begin = tcp->tcp_sack_snxt;
3349 		tcp_seq		end;
3350 		int32_t		off;
3351 
3352 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
3353 			if (SEQ_GT(notsack_blk->end, begin) &&
3354 			    (notsack_blk->sack_cnt >=
3355 			    tcps->tcps_dupack_fast_retransmit)) {
3356 				end = notsack_blk->end;
3357 				if (SEQ_LT(begin, notsack_blk->begin)) {
3358 					begin = notsack_blk->begin;
3359 				}
3360 				break;
3361 			}
3362 		}
3363 		/*
3364 		 * All holes are filled.  Manipulate tcp_cwnd to send more
3365 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
3366 		 * set to tcp_cwnd_ssthresh.
3367 		 */
3368 		if (notsack_blk == NULL) {
3369 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
3370 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
3371 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
3372 				ASSERT(tcp->tcp_cwnd > 0);
3373 				return;
3374 			} else {
3375 				usable_swnd = usable_swnd / mss;
3376 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
3377 				    MAX(usable_swnd * mss, mss);
3378 				*flags |= TH_XMIT_NEEDED;
3379 				return;
3380 			}
3381 		}
3382 
3383 		/*
3384 		 * Note that we may send more than usable_swnd allows here
3385 		 * because of round off, but no more than 1 MSS of data.
3386 		 */
3387 		seg_len = end - begin;
3388 		if (seg_len > mss)
3389 			seg_len = mss;
3390 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
3391 		ASSERT(snxt_mp != NULL);
3392 		/* This should not happen.  Defensive coding again... */
3393 		if (snxt_mp == NULL) {
3394 			return;
3395 		}
3396 
3397 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
3398 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
3399 		if (xmit_mp == NULL)
3400 			return;
3401 
3402 		usable_swnd -= seg_len;
3403 		tcp->tcp_pipe += seg_len;
3404 		tcp->tcp_sack_snxt = begin + seg_len;
3405 
3406 		tcp_send_data(tcp, xmit_mp);
3407 
3408 		/*
3409 		 * Update the send timestamp to avoid false retransmission.
3410 		 */
3411 		snxt_mp->b_prev = (mblk_t *)(intptr_t)gethrtime();
3412 
3413 		TCPS_BUMP_MIB(tcps, tcpRetransSegs);
3414 		TCPS_UPDATE_MIB(tcps, tcpRetransBytes, seg_len);
3415 		TCPS_BUMP_MIB(tcps, tcpOutSackRetransSegs);
3416 		tcp->tcp_cs.tcp_out_retrans_segs++;
3417 		tcp->tcp_cs.tcp_out_retrans_bytes += seg_len;
3418 		/*
3419 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
3420 		 * This happens when new data sent during fast recovery is
3421 		 * also lost.  If TCP retransmits those new data, it needs
3422 		 * to extend SACK recover phase to avoid starting another
3423 		 * fast retransmit/recovery unnecessarily.
3424 		 */
3425 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
3426 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
3427 		}
3428 	}
3429 }
3430 
3431 /*
3432  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
3433  * or ICMP errors.
3434  */
3435 void
3436 tcp_ss_rexmit(tcp_t *tcp)
3437 {
3438 	uint32_t	snxt;
3439 	uint32_t	smax;
3440 	int32_t		win;
3441 	int32_t		mss;
3442 	int32_t		off;
3443 	mblk_t		*snxt_mp;
3444 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3445 
3446 	/*
3447 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
3448 	 * all unack'ed segments.
3449 	 */
3450 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
3451 		smax = tcp->tcp_rexmit_max;
3452 		snxt = tcp->tcp_rexmit_nxt;
3453 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
3454 			snxt = tcp->tcp_suna;
3455 		}
3456 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
3457 		win -= snxt - tcp->tcp_suna;
3458 		mss = tcp->tcp_mss;
3459 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
3460 
3461 		while (SEQ_LT(snxt, smax) && (win > 0) && (snxt_mp != NULL)) {
3462 			mblk_t	*xmit_mp;
3463 			mblk_t	*old_snxt_mp = snxt_mp;
3464 			uint32_t cnt = mss;
3465 
3466 			if (win < cnt) {
3467 				cnt = win;
3468 			}
3469 			if (SEQ_GT(snxt + cnt, smax)) {
3470 				cnt = smax - snxt;
3471 			}
3472 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
3473 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
3474 			if (xmit_mp == NULL)
3475 				return;
3476 
3477 			tcp_send_data(tcp, xmit_mp);
3478 
3479 			snxt += cnt;
3480 			win -= cnt;
3481 			/*
3482 			 * Update the send timestamp to avoid false
3483 			 * retransmission.
3484 			 */
3485 			old_snxt_mp->b_prev = (mblk_t *)(intptr_t)gethrtime();
3486 			TCPS_BUMP_MIB(tcps, tcpRetransSegs);
3487 			TCPS_UPDATE_MIB(tcps, tcpRetransBytes, cnt);
3488 			tcp->tcp_cs.tcp_out_retrans_segs++;
3489 			tcp->tcp_cs.tcp_out_retrans_bytes += cnt;
3490 
3491 			tcp->tcp_rexmit_nxt = snxt;
3492 		}
3493 		/*
3494 		 * If we have transmitted all we have at the time
3495 		 * we started the retranmission, we can leave
3496 		 * the rest of the job to tcp_wput_data().  But we
3497 		 * need to check the send window first.  If the
3498 		 * win is not 0, go on with tcp_wput_data().
3499 		 */
3500 		if (SEQ_LT(snxt, smax) || win == 0) {
3501 			return;
3502 		}
3503 	}
3504 	/* Only call tcp_wput_data() if there is data to be sent. */
3505 	if (tcp->tcp_unsent) {
3506 		tcp_wput_data(tcp, NULL, B_FALSE);
3507 	}
3508 }
3509 
3510 /*
3511  * Do slow start retransmission after ICMP errors of PMTU changes.
3512  */
3513 void
3514 tcp_rexmit_after_error(tcp_t *tcp)
3515 {
3516 	/*
3517 	 * All sent data has been acknowledged or no data left to send, just
3518 	 * to return.
3519 	 */
3520 	if (!SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) ||
3521 	    (tcp->tcp_xmit_head == NULL))
3522 		return;
3523 
3524 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0))
3525 		tcp->tcp_rexmit_max = tcp->tcp_fss;
3526 	else
3527 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
3528 
3529 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
3530 	tcp->tcp_rexmit = B_TRUE;
3531 	tcp->tcp_dupack_cnt = 0;
3532 	tcp_ss_rexmit(tcp);
3533 }
3534 
3535 /*
3536  * tcp_get_seg_mp() is called to get the pointer to a segment in the
3537  * send queue which starts at the given sequence number. If the given
3538  * sequence number is equal to last valid sequence number (tcp_snxt), the
3539  * returned mblk is the last valid mblk, and off is set to the length of
3540  * that mblk.
3541  *
3542  * send queue which starts at the given seq. no.
3543  *
3544  * Parameters:
3545  *	tcp_t *tcp: the tcp instance pointer.
3546  *	uint32_t seq: the starting seq. no of the requested segment.
3547  *	int32_t *off: after the execution, *off will be the offset to
3548  *		the returned mblk which points to the requested seq no.
3549  *		It is the caller's responsibility to send in a non-null off.
3550  *
3551  * Return:
3552  *	A mblk_t pointer pointing to the requested segment in send queue.
3553  */
3554 static mblk_t *
3555 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
3556 {
3557 	int32_t	cnt;
3558 	mblk_t	*mp;
3559 
3560 	/* Defensive coding.  Make sure we don't send incorrect data. */
3561 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
3562 		return (NULL);
3563 
3564 	cnt = seq - tcp->tcp_suna;
3565 	mp = tcp->tcp_xmit_head;
3566 	while (cnt > 0 && mp != NULL) {
3567 		cnt -= mp->b_wptr - mp->b_rptr;
3568 		if (cnt <= 0) {
3569 			cnt += mp->b_wptr - mp->b_rptr;
3570 			break;
3571 		}
3572 		mp = mp->b_cont;
3573 	}
3574 	ASSERT(mp != NULL);
3575 	*off = cnt;
3576 	return (mp);
3577 }
3578 
3579 /*
3580  * This routine adjusts next-to-send sequence number variables, in the
3581  * case where the reciever has shrunk it's window.
3582  */
3583 void
3584 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
3585 {
3586 	mblk_t *xmit_tail;
3587 	int32_t offset;
3588 
3589 	tcp->tcp_snxt = snxt;
3590 
3591 	/* Get the mblk, and the offset in it, as per the shrunk window */
3592 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
3593 	ASSERT(xmit_tail != NULL);
3594 	tcp->tcp_xmit_tail = xmit_tail;
3595 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
3596 	    xmit_tail->b_rptr - offset;
3597 }
3598 
3599 /*
3600  * This handles the case when the receiver has shrunk its win. Per RFC 1122
3601  * if the receiver shrinks the window, i.e. moves the right window to the
3602  * left, the we should not send new data, but should retransmit normally the
3603  * old unacked data between suna and suna + swnd. We might has sent data
3604  * that is now outside the new window, pretend that we didn't send  it.
3605  */
3606 static void
3607 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
3608 {
3609 	uint32_t	snxt = tcp->tcp_snxt;
3610 
3611 	ASSERT(shrunk_count > 0);
3612 
3613 	if (!tcp->tcp_is_wnd_shrnk) {
3614 		tcp->tcp_snxt_shrunk = snxt;
3615 		tcp->tcp_is_wnd_shrnk = B_TRUE;
3616 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
3617 		tcp->tcp_snxt_shrunk = snxt;
3618 	}
3619 
3620 	/* Pretend we didn't send the data outside the window */
3621 	snxt -= shrunk_count;
3622 
3623 	/* Reset all the values per the now shrunk window */
3624 	tcp_update_xmit_tail(tcp, snxt);
3625 	tcp->tcp_unsent += shrunk_count;
3626 
3627 	/*
3628 	 * If the SACK option is set, delete the entire list of
3629 	 * notsack'ed blocks.
3630 	 */
3631 	TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
3632 
3633 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
3634 		/*
3635 		 * Make sure the timer is running so that we will probe a zero
3636 		 * window.
3637 		 */
3638 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
3639 }
3640 
3641 /*
3642  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
3643  * with the template header, as well as other options such as time-stamp,
3644  * ECN and/or SACK.
3645  */
3646 static void
3647 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, int num_sack_blk)
3648 {
3649 	tcpha_t *tcp_tmpl, *tcpha;
3650 	uint32_t *dst, *src;
3651 	int hdrlen;
3652 	conn_t *connp = tcp->tcp_connp;
3653 
3654 	ASSERT(OK_32PTR(rptr));
3655 
3656 	/* Template header */
3657 	tcp_tmpl = tcp->tcp_tcpha;
3658 
3659 	/* Header of outgoing packet */
3660 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
3661 
3662 	/* dst and src are opaque 32-bit fields, used for copying */
3663 	dst = (uint32_t *)rptr;
3664 	src = (uint32_t *)connp->conn_ht_iphc;
3665 	hdrlen = connp->conn_ht_iphc_len;
3666 
3667 	/* Fill time-stamp option if needed */
3668 	if (tcp->tcp_snd_ts_ok) {
3669 		U32_TO_BE32(LBOLT_FASTPATH,
3670 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
3671 		U32_TO_BE32(tcp->tcp_ts_recent,
3672 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
3673 	} else {
3674 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
3675 	}
3676 
3677 	/*
3678 	 * Copy the template header; is this really more efficient than
3679 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
3680 	 * but perhaps not for other scenarios.
3681 	 */
3682 	dst[0] = src[0];
3683 	dst[1] = src[1];
3684 	dst[2] = src[2];
3685 	dst[3] = src[3];
3686 	dst[4] = src[4];
3687 	dst[5] = src[5];
3688 	dst[6] = src[6];
3689 	dst[7] = src[7];
3690 	dst[8] = src[8];
3691 	dst[9] = src[9];
3692 	if (hdrlen -= 40) {
3693 		hdrlen >>= 2;
3694 		dst += 10;
3695 		src += 10;
3696 		do {
3697 			*dst++ = *src++;
3698 		} while (--hdrlen);
3699 	}
3700 
3701 	/*
3702 	 * Set the ECN info in the TCP header if it is not a zero
3703 	 * window probe.  Zero window probe is only sent in
3704 	 * tcp_wput_data() and tcp_timer().
3705 	 */
3706 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
3707 		TCP_SET_ECT(tcp, rptr);
3708 
3709 		if (tcp->tcp_ecn_echo_on)
3710 			tcpha->tha_flags |= TH_ECE;
3711 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
3712 			tcpha->tha_flags |= TH_CWR;
3713 			tcp->tcp_ecn_cwr_sent = B_TRUE;
3714 		}
3715 	}
3716 
3717 	/* Fill in SACK options */
3718 	if (num_sack_blk > 0) {
3719 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
3720 		sack_blk_t *tmp;
3721 		int32_t	i;
3722 
3723 		wptr[0] = TCPOPT_NOP;
3724 		wptr[1] = TCPOPT_NOP;
3725 		wptr[2] = TCPOPT_SACK;
3726 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
3727 		    sizeof (sack_blk_t);
3728 		wptr += TCPOPT_REAL_SACK_LEN;
3729 
3730 		tmp = tcp->tcp_sack_list;
3731 		for (i = 0; i < num_sack_blk; i++) {
3732 			U32_TO_BE32(tmp[i].begin, wptr);
3733 			wptr += sizeof (tcp_seq);
3734 			U32_TO_BE32(tmp[i].end, wptr);
3735 			wptr += sizeof (tcp_seq);
3736 		}
3737 		tcpha->tha_offset_and_reserved +=
3738 		    ((num_sack_blk * 2 + 1) << 4);
3739 	}
3740 }
3741