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