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