1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 #include "opt_inet.h" 34 #include "opt_inet6.h" 35 #include "opt_ipsec.h" 36 #include "opt_kern_tls.h" 37 38 #include <sys/param.h> 39 #include <sys/systm.h> 40 #include <sys/arb.h> 41 #include <sys/domain.h> 42 #ifdef TCP_HHOOK 43 #include <sys/hhook.h> 44 #endif 45 #include <sys/kernel.h> 46 #ifdef KERN_TLS 47 #include <sys/ktls.h> 48 #endif 49 #include <sys/lock.h> 50 #include <sys/mbuf.h> 51 #include <sys/mutex.h> 52 #include <sys/protosw.h> 53 #include <sys/qmath.h> 54 #include <sys/sdt.h> 55 #include <sys/socket.h> 56 #include <sys/socketvar.h> 57 #include <sys/sysctl.h> 58 #include <sys/stats.h> 59 60 #include <net/if.h> 61 #include <net/route.h> 62 #include <net/route/nhop.h> 63 #include <net/vnet.h> 64 65 #include <netinet/in.h> 66 #include <netinet/in_kdtrace.h> 67 #include <netinet/in_systm.h> 68 #include <netinet/ip.h> 69 #include <netinet/in_pcb.h> 70 #include <netinet/ip_var.h> 71 #include <netinet/ip_options.h> 72 #ifdef INET6 73 #include <netinet6/in6_pcb.h> 74 #include <netinet/ip6.h> 75 #include <netinet6/ip6_var.h> 76 #endif 77 #include <netinet/tcp.h> 78 #define TCPOUTFLAGS 79 #include <netinet/tcp_fsm.h> 80 #include <netinet/tcp_seq.h> 81 #include <netinet/tcp_var.h> 82 #include <netinet/tcp_log_buf.h> 83 #include <netinet/tcp_syncache.h> 84 #include <netinet/tcp_timer.h> 85 #include <netinet/tcpip.h> 86 #include <netinet/cc/cc.h> 87 #include <netinet/tcp_fastopen.h> 88 #ifdef TCPPCAP 89 #include <netinet/tcp_pcap.h> 90 #endif 91 #ifdef TCP_OFFLOAD 92 #include <netinet/tcp_offload.h> 93 #endif 94 #include <netinet/tcp_ecn.h> 95 96 #include <netipsec/ipsec_support.h> 97 98 #include <netinet/udp.h> 99 #include <netinet/udp_var.h> 100 #include <machine/in_cksum.h> 101 102 #include <security/mac/mac_framework.h> 103 104 VNET_DEFINE(int, path_mtu_discovery) = 1; 105 SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_VNET | CTLFLAG_RW, 106 &VNET_NAME(path_mtu_discovery), 1, 107 "Enable Path MTU Discovery"); 108 109 VNET_DEFINE(int, tcp_do_tso) = 1; 110 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tso, CTLFLAG_VNET | CTLFLAG_RW, 111 &VNET_NAME(tcp_do_tso), 0, 112 "Enable TCP Segmentation Offload"); 113 114 VNET_DEFINE(int, tcp_sendspace) = 1024*32; 115 #define V_tcp_sendspace VNET(tcp_sendspace) 116 SYSCTL_INT(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_VNET | CTLFLAG_RW, 117 &VNET_NAME(tcp_sendspace), 0, "Initial send socket buffer size"); 118 119 VNET_DEFINE(int, tcp_do_autosndbuf) = 1; 120 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto, CTLFLAG_VNET | CTLFLAG_RW, 121 &VNET_NAME(tcp_do_autosndbuf), 0, 122 "Enable automatic send buffer sizing"); 123 124 VNET_DEFINE(int, tcp_autosndbuf_inc) = 8*1024; 125 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_inc, CTLFLAG_VNET | CTLFLAG_RW, 126 &VNET_NAME(tcp_autosndbuf_inc), 0, 127 "Incrementor step size of automatic send buffer"); 128 129 VNET_DEFINE(int, tcp_autosndbuf_max) = 2*1024*1024; 130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_max, CTLFLAG_VNET | CTLFLAG_RW, 131 &VNET_NAME(tcp_autosndbuf_max), 0, 132 "Max size of automatic send buffer"); 133 134 VNET_DEFINE(int, tcp_sendbuf_auto_lowat) = 0; 135 #define V_tcp_sendbuf_auto_lowat VNET(tcp_sendbuf_auto_lowat) 136 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto_lowat, CTLFLAG_VNET | CTLFLAG_RW, 137 &VNET_NAME(tcp_sendbuf_auto_lowat), 0, 138 "Modify threshold for auto send buffer growth to account for SO_SNDLOWAT"); 139 140 /* 141 * Make sure that either retransmit or persist timer is set for SYN, FIN and 142 * non-ACK. 143 */ 144 #define TCP_XMIT_TIMER_ASSERT(tp, len, th_flags) \ 145 KASSERT(((len) == 0 && ((th_flags) & (TH_SYN | TH_FIN)) == 0) ||\ 146 tcp_timer_active((tp), TT_REXMT) || \ 147 tcp_timer_active((tp), TT_PERSIST), \ 148 ("neither rexmt nor persist timer is set")) 149 150 #ifdef TCP_HHOOK 151 /* 152 * Wrapper for the TCP established output helper hook. 153 */ 154 void 155 hhook_run_tcp_est_out(struct tcpcb *tp, struct tcphdr *th, 156 struct tcpopt *to, uint32_t len, int tso) 157 { 158 struct tcp_hhook_data hhook_data; 159 160 if (V_tcp_hhh[HHOOK_TCP_EST_OUT]->hhh_nhooks > 0) { 161 hhook_data.tp = tp; 162 hhook_data.th = th; 163 hhook_data.to = to; 164 hhook_data.len = len; 165 hhook_data.tso = tso; 166 167 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_OUT], &hhook_data, 168 &tp->t_osd); 169 } 170 } 171 #endif 172 173 /* 174 * CC wrapper hook functions 175 */ 176 void 177 cc_after_idle(struct tcpcb *tp) 178 { 179 INP_WLOCK_ASSERT(tptoinpcb(tp)); 180 181 if (CC_ALGO(tp)->after_idle != NULL) 182 CC_ALGO(tp)->after_idle(&tp->t_ccv); 183 } 184 185 /* 186 * Tcp output routine: figure out what should be sent and send it. 187 */ 188 int 189 tcp_default_output(struct tcpcb *tp) 190 { 191 struct socket *so = tptosocket(tp); 192 struct inpcb *inp = tptoinpcb(tp); 193 int32_t len; 194 uint32_t recwin, sendwin; 195 uint16_t flags; 196 int off, error = 0; /* Keep compiler happy */ 197 u_int if_hw_tsomaxsegcount = 0; 198 u_int if_hw_tsomaxsegsize = 0; 199 struct mbuf *m; 200 struct ip *ip = NULL; 201 struct tcphdr *th; 202 u_char opt[TCP_MAXOLEN]; 203 unsigned ipoptlen, optlen, hdrlen, ulen; 204 unsigned ipsec_optlen = 0; 205 int idle, sendalot, curticks; 206 int sack_rxmit, sack_bytes_rxmt; 207 struct sackhole *p; 208 int tso, mtu; 209 struct tcpopt to; 210 struct udphdr *udp = NULL; 211 struct tcp_log_buffer *lgb; 212 unsigned int wanted_cookie = 0; 213 unsigned int dont_sendalot = 0; 214 #ifdef INET6 215 struct ip6_hdr *ip6 = NULL; 216 const bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 217 #endif 218 #ifdef KERN_TLS 219 const bool hw_tls = tp->t_nic_ktls_xmit != 0; 220 #else 221 const bool hw_tls = false; 222 #endif 223 224 NET_EPOCH_ASSERT(); 225 INP_WLOCK_ASSERT(inp); 226 227 #ifdef TCP_OFFLOAD 228 if (tp->t_flags & TF_TOE) 229 return (tcp_offload_output(tp)); 230 #endif 231 232 /* 233 * For TFO connections in SYN_SENT or SYN_RECEIVED, 234 * only allow the initial SYN or SYN|ACK and those sent 235 * by the retransmit timer. 236 */ 237 if ((tp->t_flags & TF_FASTOPEN) && 238 ((tp->t_state == TCPS_SYN_SENT) || 239 (tp->t_state == TCPS_SYN_RECEIVED)) && 240 SEQ_GT(tp->snd_max, tp->snd_una) && /* SYN or SYN|ACK sent */ 241 (tp->snd_nxt != tp->snd_una)) /* not a retransmit */ 242 return (0); 243 244 /* 245 * Determine length of data that should be transmitted, 246 * and flags that will be used. 247 * If there is some data or critical controls (SYN, RST) 248 * to send, then transmit; otherwise, investigate further. 249 */ 250 idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una); 251 if (idle && (((ticks - tp->t_rcvtime) >= tp->t_rxtcur) || 252 (tp->t_sndtime && ((ticks - tp->t_sndtime) >= tp->t_rxtcur)))) 253 cc_after_idle(tp); 254 tp->t_flags &= ~TF_LASTIDLE; 255 if (idle) { 256 if (tp->t_flags & TF_MORETOCOME) { 257 tp->t_flags |= TF_LASTIDLE; 258 idle = 0; 259 } 260 } 261 again: 262 sendwin = 0; 263 /* 264 * If we've recently taken a timeout, snd_max will be greater than 265 * snd_nxt. There may be SACK information that allows us to avoid 266 * resending already delivered data. Adjust snd_nxt accordingly. 267 */ 268 if ((tp->t_flags & TF_SACK_PERMIT) && 269 SEQ_LT(tp->snd_nxt, tp->snd_max)) 270 sendwin = tcp_sack_adjust(tp); 271 sendalot = 0; 272 tso = 0; 273 mtu = 0; 274 off = tp->snd_nxt - tp->snd_una; 275 sendwin = min(tp->snd_wnd, tp->snd_cwnd + sendwin); 276 277 flags = tcp_outflags[tp->t_state]; 278 /* 279 * Send any SACK-generated retransmissions. If we're explicitly trying 280 * to send out new data (when sendalot is 1), bypass this function. 281 * If we retransmit in fast recovery mode, decrement snd_cwnd, since 282 * we're replacing a (future) new transmission with a retransmission 283 * now, and we previously incremented snd_cwnd in tcp_input(). 284 */ 285 /* 286 * Still in sack recovery , reset rxmit flag to zero. 287 */ 288 sack_rxmit = 0; 289 sack_bytes_rxmt = 0; 290 len = 0; 291 p = NULL; 292 if ((tp->t_flags & TF_SACK_PERMIT) && 293 (IN_FASTRECOVERY(tp->t_flags) || SEQ_LT(tp->snd_nxt, tp->snd_max)) && 294 (p = tcp_sack_output(tp, &sack_bytes_rxmt))) { 295 uint32_t cwin; 296 297 cwin = 298 imax(min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt, 0); 299 /* Do not retransmit SACK segments beyond snd_recover */ 300 if (SEQ_GT(p->end, tp->snd_recover)) { 301 /* 302 * (At least) part of sack hole extends beyond 303 * snd_recover. Check to see if we can rexmit data 304 * for this hole. 305 */ 306 if (SEQ_GEQ(p->rxmit, tp->snd_recover)) { 307 /* 308 * Can't rexmit any more data for this hole. 309 * That data will be rexmitted in the next 310 * sack recovery episode, when snd_recover 311 * moves past p->rxmit. 312 */ 313 p = NULL; 314 goto after_sack_rexmit; 315 } else { 316 /* Can rexmit part of the current hole */ 317 len = ((int32_t)ulmin(cwin, 318 SEQ_SUB(tp->snd_recover, p->rxmit))); 319 } 320 } else { 321 len = ((int32_t)ulmin(cwin, 322 SEQ_SUB(p->end, p->rxmit))); 323 } 324 if (len > 0) { 325 off = SEQ_SUB(p->rxmit, tp->snd_una); 326 KASSERT(off >= 0,("%s: sack block to the left of una : %d", 327 __func__, off)); 328 sack_rxmit = 1; 329 sendalot = 1; 330 } 331 } 332 after_sack_rexmit: 333 /* 334 * Get standard flags, and add SYN or FIN if requested by 'hidden' 335 * state flags. 336 */ 337 if (tp->t_flags & TF_NEEDFIN) 338 flags |= TH_FIN; 339 if (tp->t_flags & TF_NEEDSYN) 340 flags |= TH_SYN; 341 342 SOCKBUF_LOCK(&so->so_snd); 343 /* 344 * If in persist timeout with window of 0, send 1 byte. 345 * Otherwise, if window is small but nonzero 346 * and timer expired, we will send what we can 347 * and go to transmit state. 348 */ 349 if (tp->t_flags & TF_FORCEDATA) { 350 if (sendwin == 0) { 351 /* 352 * If we still have some data to send, then 353 * clear the FIN bit. Usually this would 354 * happen below when it realizes that we 355 * aren't sending all the data. However, 356 * if we have exactly 1 byte of unsent data, 357 * then it won't clear the FIN bit below, 358 * and if we are in persist state, we wind 359 * up sending the packet without recording 360 * that we sent the FIN bit. 361 * 362 * We can't just blindly clear the FIN bit, 363 * because if we don't have any more data 364 * to send then the probe will be the FIN 365 * itself. 366 */ 367 if (off < sbused(&so->so_snd)) 368 flags &= ~TH_FIN; 369 sendwin = 1; 370 } else { 371 tcp_timer_activate(tp, TT_PERSIST, 0); 372 tp->t_rxtshift = 0; 373 } 374 } 375 376 /* 377 * If snd_nxt == snd_max and we have transmitted a FIN, the 378 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in 379 * a negative length. This can also occur when TCP opens up 380 * its congestion window while receiving additional duplicate 381 * acks after fast-retransmit because TCP will reset snd_nxt 382 * to snd_max after the fast-retransmit. 383 * 384 * In the normal retransmit-FIN-only case, however, snd_nxt will 385 * be set to snd_una, the offset will be 0, and the length may 386 * wind up 0. 387 * 388 * If sack_rxmit is true we are retransmitting from the scoreboard 389 * in which case len is already set. 390 */ 391 if (sack_rxmit == 0) { 392 if ((sack_bytes_rxmt == 0) || SEQ_LT(tp->snd_nxt, tp->snd_max)) { 393 len = ((int32_t)min(sbavail(&so->so_snd), sendwin) - 394 off); 395 } else { 396 int32_t cwin; 397 398 /* 399 * We are inside of a SACK recovery episode and are 400 * sending new data, having retransmitted all the 401 * data possible in the scoreboard. 402 */ 403 len = ((int32_t)min(sbavail(&so->so_snd), tp->snd_wnd) - 404 off); 405 /* 406 * Don't remove this (len > 0) check ! 407 * We explicitly check for len > 0 here (although it 408 * isn't really necessary), to work around a gcc 409 * optimization issue - to force gcc to compute 410 * len above. Without this check, the computation 411 * of len is bungled by the optimizer. 412 */ 413 if (len > 0) { 414 cwin = tp->snd_cwnd - imax(0, (int32_t) 415 (tp->snd_nxt - tp->snd_recover)) - 416 sack_bytes_rxmt; 417 if (cwin < 0) 418 cwin = 0; 419 len = imin(len, cwin); 420 } 421 } 422 } 423 424 /* 425 * Lop off SYN bit if it has already been sent. However, if this 426 * is SYN-SENT state and if segment contains data and if we don't 427 * know that foreign host supports TAO, suppress sending segment. 428 */ 429 if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) { 430 if (tp->t_state != TCPS_SYN_RECEIVED) 431 flags &= ~TH_SYN; 432 /* 433 * When sending additional segments following a TFO SYN|ACK, 434 * do not include the SYN bit. 435 */ 436 if ((tp->t_flags & TF_FASTOPEN) && 437 (tp->t_state == TCPS_SYN_RECEIVED)) 438 flags &= ~TH_SYN; 439 off--, len++; 440 } 441 442 /* 443 * Be careful not to send data and/or FIN on SYN segments. 444 * This measure is needed to prevent interoperability problems 445 * with not fully conformant TCP implementations. 446 */ 447 if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) { 448 len = 0; 449 flags &= ~TH_FIN; 450 } 451 452 /* 453 * On TFO sockets, ensure no data is sent in the following cases: 454 * 455 * - When retransmitting SYN|ACK on a passively-created socket 456 * 457 * - When retransmitting SYN on an actively created socket 458 * 459 * - When sending a zero-length cookie (cookie request) on an 460 * actively created socket 461 * 462 * - When the socket is in the CLOSED state (RST is being sent) 463 */ 464 if ((tp->t_flags & TF_FASTOPEN) && 465 (((flags & TH_SYN) && (tp->t_rxtshift > 0)) || 466 ((tp->t_state == TCPS_SYN_SENT) && 467 (tp->t_tfo_client_cookie_len == 0)) || 468 (flags & TH_RST))) 469 len = 0; 470 471 /* Without fast-open there should never be data sent on a SYN. */ 472 if ((flags & TH_SYN) && !(tp->t_flags & TF_FASTOPEN)) { 473 len = 0; 474 } 475 476 if (len <= 0) { 477 /* 478 * If FIN has been sent but not acked, 479 * but we haven't been called to retransmit, 480 * len will be < 0. Otherwise, window shrank 481 * after we sent into it. If window shrank to 0, 482 * cancel pending retransmit, pull snd_nxt back 483 * to (closed) window, and set the persist timer 484 * if it isn't already going. If the window didn't 485 * close completely, just wait for an ACK. 486 * 487 * We also do a general check here to ensure that 488 * we will set the persist timer when we have data 489 * to send, but a 0-byte window. This makes sure 490 * the persist timer is set even if the packet 491 * hits one of the "goto send" lines below. 492 */ 493 len = 0; 494 if ((sendwin == 0) && (TCPS_HAVEESTABLISHED(tp->t_state)) && 495 (off < (int) sbavail(&so->so_snd)) && 496 !tcp_timer_active(tp, TT_PERSIST)) { 497 tcp_timer_activate(tp, TT_REXMT, 0); 498 tp->t_rxtshift = 0; 499 tp->snd_nxt = tp->snd_una; 500 if (!tcp_timer_active(tp, TT_PERSIST)) 501 tcp_setpersist(tp); 502 } 503 } 504 505 /* len will be >= 0 after this point. */ 506 KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__)); 507 508 tcp_sndbuf_autoscale(tp, so, sendwin); 509 510 /* 511 * Decide if we can use TCP Segmentation Offloading (if supported by 512 * hardware). 513 * 514 * TSO may only be used if we are in a pure bulk sending state. The 515 * presence of TCP-MD5, SACK retransmits, SACK advertizements and 516 * IP options prevent using TSO. With TSO the TCP header is the same 517 * (except for the sequence number) for all generated packets. This 518 * makes it impossible to transmit any options which vary per generated 519 * segment or packet. 520 * 521 * IPv4 handling has a clear separation of ip options and ip header 522 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does 523 * the right thing below to provide length of just ip options and thus 524 * checking for ipoptlen is enough to decide if ip options are present. 525 */ 526 #if defined(IPSEC) || defined(IPSEC_SUPPORT) 527 /* 528 * Pre-calculate here as we save another lookup into the darknesses 529 * of IPsec that way and can actually decide if TSO is ok. 530 */ 531 #ifdef INET6 532 if (isipv6 && IPSEC_ENABLED(ipv6)) 533 ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp); 534 #ifdef INET 535 else 536 #endif 537 #endif /* INET6 */ 538 #ifdef INET 539 if (IPSEC_ENABLED(ipv4)) 540 ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp); 541 #endif /* INET */ 542 #endif /* IPSEC */ 543 #ifdef INET6 544 if (isipv6) 545 ipoptlen = ip6_optlen(inp); 546 else 547 #endif 548 if (inp->inp_options) 549 ipoptlen = inp->inp_options->m_len - 550 offsetof(struct ipoption, ipopt_list); 551 else 552 ipoptlen = 0; 553 ipoptlen += ipsec_optlen; 554 555 if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > tp->t_maxseg && 556 (tp->t_port == 0) && 557 ((tp->t_flags & TF_SIGNATURE) == 0) && 558 tp->rcv_numsacks == 0 && ((sack_rxmit == 0) || V_tcp_sack_tso) && 559 (ipoptlen == 0 || (ipoptlen == ipsec_optlen && 560 (tp->t_flags2 & TF2_IPSEC_TSO) != 0)) && 561 !(flags & TH_SYN)) 562 tso = 1; 563 564 if (SEQ_LT((sack_rxmit ? p->rxmit : tp->snd_nxt) + len, 565 tp->snd_una + sbused(&so->so_snd))) { 566 flags &= ~TH_FIN; 567 } 568 569 recwin = lmin(lmax(sbspace(&so->so_rcv), 0), 570 (long)TCP_MAXWIN << tp->rcv_scale); 571 572 /* 573 * Sender silly window avoidance. We transmit under the following 574 * conditions when len is non-zero: 575 * 576 * - We have a full segment (or more with TSO) 577 * - This is the last buffer in a write()/send() and we are 578 * either idle or running NODELAY 579 * - we've timed out (e.g. persist timer) 580 * - we have more then 1/2 the maximum send window's worth of 581 * data (receiver may be limited the window size) 582 * - we need to retransmit 583 */ 584 if (len) { 585 if (len >= tp->t_maxseg) 586 goto send; 587 /* 588 * As the TCP header options are now 589 * considered when setting up the initial 590 * window, we would not send the last segment 591 * if we skip considering the option length here. 592 * Note: this may not work when tcp headers change 593 * very dynamically in the future. 594 */ 595 if ((((tp->t_flags & TF_SIGNATURE) ? 596 PADTCPOLEN(TCPOLEN_SIGNATURE) : 0) + 597 ((tp->t_flags & TF_RCVD_TSTMP) ? 598 PADTCPOLEN(TCPOLEN_TIMESTAMP) : 0) + 599 len) >= tp->t_maxseg) 600 goto send; 601 /* 602 * NOTE! on localhost connections an 'ack' from the remote 603 * end may occur synchronously with the output and cause 604 * us to flush a buffer queued with moretocome. XXX 605 * 606 * note: the len + off check is almost certainly unnecessary. 607 */ 608 if (!(tp->t_flags & TF_MORETOCOME) && /* normal case */ 609 (idle || (tp->t_flags & TF_NODELAY)) && 610 (uint32_t)len + (uint32_t)off >= sbavail(&so->so_snd) && 611 (tp->t_flags & TF_NOPUSH) == 0) { 612 goto send; 613 } 614 if (tp->t_flags & TF_FORCEDATA) /* typ. timeout case */ 615 goto send; 616 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) 617 goto send; 618 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) /* retransmit case */ 619 goto send; 620 if (sack_rxmit) 621 goto send; 622 } 623 624 /* 625 * Sending of standalone window updates. 626 * 627 * Window updates are important when we close our window due to a 628 * full socket buffer and are opening it again after the application 629 * reads data from it. Once the window has opened again and the 630 * remote end starts to send again the ACK clock takes over and 631 * provides the most current window information. 632 * 633 * We must avoid the silly window syndrome whereas every read 634 * from the receive buffer, no matter how small, causes a window 635 * update to be sent. We also should avoid sending a flurry of 636 * window updates when the socket buffer had queued a lot of data 637 * and the application is doing small reads. 638 * 639 * Prevent a flurry of pointless window updates by only sending 640 * an update when we can increase the advertized window by more 641 * than 1/4th of the socket buffer capacity. When the buffer is 642 * getting full or is very small be more aggressive and send an 643 * update whenever we can increase by two mss sized segments. 644 * In all other situations the ACK's to new incoming data will 645 * carry further window increases. 646 * 647 * Don't send an independent window update if a delayed 648 * ACK is pending (it will get piggy-backed on it) or the 649 * remote side already has done a half-close and won't send 650 * more data. 651 */ 652 if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) && 653 !(tp->t_flags & TF_DELACK) && 654 !TCPS_HAVERCVDFIN(tp->t_state)) { 655 /* 656 * "adv" is the amount we could increase the window, 657 * taking into account that we are limited by 658 * TCP_MAXWIN << tp->rcv_scale. 659 */ 660 int32_t adv; 661 int oldwin; 662 663 adv = recwin; 664 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) { 665 oldwin = (tp->rcv_adv - tp->rcv_nxt); 666 if (adv > oldwin) 667 adv -= oldwin; 668 else 669 adv = 0; 670 } else 671 oldwin = 0; 672 673 /* 674 * If the new window size ends up being the same as or less 675 * than the old size when it is scaled, then don't force 676 * a window update. 677 */ 678 if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale) 679 goto dontupdate; 680 681 if (adv >= (int32_t)(2 * tp->t_maxseg) && 682 (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) || 683 recwin <= (so->so_rcv.sb_hiwat / 8) || 684 so->so_rcv.sb_hiwat <= 8 * tp->t_maxseg || 685 adv >= TCP_MAXWIN << tp->rcv_scale)) 686 goto send; 687 if (2 * adv >= (int32_t)so->so_rcv.sb_hiwat) 688 goto send; 689 } 690 dontupdate: 691 692 /* 693 * Send if we owe the peer an ACK, RST, SYN, or urgent data. ACKNOW 694 * is also a catch-all for the retransmit timer timeout case. 695 */ 696 if (tp->t_flags & TF_ACKNOW) 697 goto send; 698 if ((flags & TH_RST) || 699 ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) 700 goto send; 701 if (SEQ_GT(tp->snd_up, tp->snd_una)) 702 goto send; 703 /* 704 * If our state indicates that FIN should be sent 705 * and we have not yet done so, then we need to send. 706 */ 707 if (flags & TH_FIN && 708 ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una)) 709 goto send; 710 /* 711 * In SACK, it is possible for tcp_output to fail to send a segment 712 * after the retransmission timer has been turned off. Make sure 713 * that the retransmission timer is set. 714 */ 715 if ((tp->t_flags & TF_SACK_PERMIT) && 716 SEQ_GT(tp->snd_max, tp->snd_una) && 717 !tcp_timer_active(tp, TT_REXMT) && 718 !tcp_timer_active(tp, TT_PERSIST)) { 719 tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp)); 720 goto just_return; 721 } 722 /* 723 * TCP window updates are not reliable, rather a polling protocol 724 * using ``persist'' packets is used to insure receipt of window 725 * updates. The three ``states'' for the output side are: 726 * idle not doing retransmits or persists 727 * persisting to move a small or zero window 728 * (re)transmitting and thereby not persisting 729 * 730 * tcp_timer_active(tp, TT_PERSIST) 731 * is true when we are in persist state. 732 * (tp->t_flags & TF_FORCEDATA) 733 * is set when we are called to send a persist packet. 734 * tcp_timer_active(tp, TT_REXMT) 735 * is set when we are retransmitting 736 * The output side is idle when both timers are zero. 737 * 738 * If send window is too small, there is data to transmit, and no 739 * retransmit or persist is pending, then go to persist state. 740 * If nothing happens soon, send when timer expires: 741 * if window is nonzero, transmit what we can, 742 * otherwise force out a byte. 743 */ 744 if (sbavail(&so->so_snd) && !tcp_timer_active(tp, TT_REXMT) && 745 !tcp_timer_active(tp, TT_PERSIST)) { 746 tp->t_rxtshift = 0; 747 tcp_setpersist(tp); 748 } 749 750 /* 751 * No reason to send a segment, just return. 752 */ 753 just_return: 754 SOCKBUF_UNLOCK(&so->so_snd); 755 return (0); 756 757 send: 758 SOCKBUF_LOCK_ASSERT(&so->so_snd); 759 if (len > 0) { 760 if (len >= tp->t_maxseg) 761 tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT; 762 else 763 tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT; 764 } 765 /* 766 * Before ESTABLISHED, force sending of initial options 767 * unless TCP set not to do any options. 768 * NOTE: we assume that the IP/TCP header plus TCP options 769 * always fit in a single mbuf, leaving room for a maximum 770 * link header, i.e. 771 * max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES 772 */ 773 optlen = 0; 774 #ifdef INET6 775 if (isipv6) 776 hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr); 777 else 778 #endif 779 hdrlen = sizeof (struct tcpiphdr); 780 781 if (flags & TH_SYN) { 782 tp->snd_nxt = tp->iss; 783 } 784 785 /* 786 * Compute options for segment. 787 * We only have to care about SYN and established connection 788 * segments. Options for SYN-ACK segments are handled in TCP 789 * syncache. 790 */ 791 to.to_flags = 0; 792 if ((tp->t_flags & TF_NOOPT) == 0) { 793 /* Maximum segment size. */ 794 if (flags & TH_SYN) { 795 to.to_mss = tcp_mssopt(&inp->inp_inc); 796 if (tp->t_port) 797 to.to_mss -= V_tcp_udp_tunneling_overhead; 798 to.to_flags |= TOF_MSS; 799 800 /* 801 * On SYN or SYN|ACK transmits on TFO connections, 802 * only include the TFO option if it is not a 803 * retransmit, as the presence of the TFO option may 804 * have caused the original SYN or SYN|ACK to have 805 * been dropped by a middlebox. 806 */ 807 if ((tp->t_flags & TF_FASTOPEN) && 808 (tp->t_rxtshift == 0)) { 809 if (tp->t_state == TCPS_SYN_RECEIVED) { 810 to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN; 811 to.to_tfo_cookie = 812 (u_int8_t *)&tp->t_tfo_cookie.server; 813 to.to_flags |= TOF_FASTOPEN; 814 wanted_cookie = 1; 815 } else if (tp->t_state == TCPS_SYN_SENT) { 816 to.to_tfo_len = 817 tp->t_tfo_client_cookie_len; 818 to.to_tfo_cookie = 819 tp->t_tfo_cookie.client; 820 to.to_flags |= TOF_FASTOPEN; 821 wanted_cookie = 1; 822 /* 823 * If we wind up having more data to 824 * send with the SYN than can fit in 825 * one segment, don't send any more 826 * until the SYN|ACK comes back from 827 * the other end. 828 */ 829 dont_sendalot = 1; 830 } 831 } 832 } 833 /* Window scaling. */ 834 if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) { 835 to.to_wscale = tp->request_r_scale; 836 to.to_flags |= TOF_SCALE; 837 } 838 /* Timestamps. */ 839 if ((tp->t_flags & TF_RCVD_TSTMP) || 840 ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) { 841 curticks = tcp_ts_getticks(); 842 to.to_tsval = curticks + tp->ts_offset; 843 to.to_tsecr = tp->ts_recent; 844 to.to_flags |= TOF_TS; 845 if (tp->t_rxtshift == 1) 846 tp->t_badrxtwin = curticks; 847 } 848 849 /* Set receive buffer autosizing timestamp. */ 850 if (tp->rfbuf_ts == 0 && 851 (so->so_rcv.sb_flags & SB_AUTOSIZE)) 852 tp->rfbuf_ts = tcp_ts_getticks(); 853 854 /* Selective ACK's. */ 855 if (tp->t_flags & TF_SACK_PERMIT) { 856 if (flags & TH_SYN) 857 to.to_flags |= TOF_SACKPERM; 858 else if (TCPS_HAVEESTABLISHED(tp->t_state) && 859 tp->rcv_numsacks > 0) { 860 to.to_flags |= TOF_SACK; 861 to.to_nsacks = tp->rcv_numsacks; 862 to.to_sacks = (u_char *)tp->sackblks; 863 } 864 } 865 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 866 /* TCP-MD5 (RFC2385). */ 867 /* 868 * Check that TCP_MD5SIG is enabled in tcpcb to 869 * account the size needed to set this TCP option. 870 */ 871 if (tp->t_flags & TF_SIGNATURE) 872 to.to_flags |= TOF_SIGNATURE; 873 #endif /* TCP_SIGNATURE */ 874 875 /* Processing the options. */ 876 hdrlen += optlen = tcp_addoptions(&to, opt); 877 /* 878 * If we wanted a TFO option to be added, but it was unable 879 * to fit, ensure no data is sent. 880 */ 881 if ((tp->t_flags & TF_FASTOPEN) && wanted_cookie && 882 !(to.to_flags & TOF_FASTOPEN)) 883 len = 0; 884 } 885 if (tp->t_port) { 886 if (V_tcp_udp_tunneling_port == 0) { 887 /* The port was removed?? */ 888 SOCKBUF_UNLOCK(&so->so_snd); 889 return (EHOSTUNREACH); 890 } 891 hdrlen += sizeof(struct udphdr); 892 } 893 /* 894 * Adjust data length if insertion of options will 895 * bump the packet length beyond the t_maxseg length. 896 * Clear the FIN bit because we cut off the tail of 897 * the segment. 898 */ 899 if (len + optlen + ipoptlen > tp->t_maxseg) { 900 flags &= ~TH_FIN; 901 902 if (tso) { 903 u_int if_hw_tsomax; 904 u_int moff; 905 int max_len; 906 907 /* extract TSO information */ 908 if_hw_tsomax = tp->t_tsomax; 909 if_hw_tsomaxsegcount = tp->t_tsomaxsegcount; 910 if_hw_tsomaxsegsize = tp->t_tsomaxsegsize; 911 912 /* 913 * Limit a TSO burst to prevent it from 914 * overflowing or exceeding the maximum length 915 * allowed by the network interface: 916 */ 917 KASSERT(ipoptlen == ipsec_optlen, 918 ("%s: TSO can't do IP options", __func__)); 919 920 /* 921 * Check if we should limit by maximum payload 922 * length: 923 */ 924 if (if_hw_tsomax != 0) { 925 /* compute maximum TSO length */ 926 max_len = if_hw_tsomax - hdrlen - 927 ipsec_optlen - max_linkhdr; 928 if (max_len <= 0) { 929 len = 0; 930 } else if (len > max_len) { 931 sendalot = 1; 932 len = max_len; 933 } 934 } 935 936 /* 937 * Prevent the last segment from being 938 * fractional unless the send sockbuf can be 939 * emptied: 940 */ 941 max_len = tp->t_maxseg - optlen - ipsec_optlen; 942 if (((uint32_t)off + (uint32_t)len) < 943 sbavail(&so->so_snd)) { 944 moff = len % max_len; 945 if (moff != 0) { 946 len -= moff; 947 sendalot = 1; 948 } 949 } 950 951 /* 952 * In case there are too many small fragments 953 * don't use TSO: 954 */ 955 if (len <= max_len) { 956 len = max_len; 957 sendalot = 1; 958 tso = 0; 959 } 960 961 /* 962 * Send the FIN in a separate segment 963 * after the bulk sending is done. 964 * We don't trust the TSO implementations 965 * to clear the FIN flag on all but the 966 * last segment. 967 */ 968 if (tp->t_flags & TF_NEEDFIN) 969 sendalot = 1; 970 } else { 971 if (optlen + ipoptlen >= tp->t_maxseg) { 972 /* 973 * Since we don't have enough space to put 974 * the IP header chain and the TCP header in 975 * one packet as required by RFC 7112, don't 976 * send it. Also ensure that at least one 977 * byte of the payload can be put into the 978 * TCP segment. 979 */ 980 SOCKBUF_UNLOCK(&so->so_snd); 981 error = EMSGSIZE; 982 sack_rxmit = 0; 983 goto out; 984 } 985 len = tp->t_maxseg - optlen - ipoptlen; 986 sendalot = 1; 987 if (dont_sendalot) 988 sendalot = 0; 989 } 990 } else 991 tso = 0; 992 993 KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET, 994 ("%s: len > IP_MAXPACKET", __func__)); 995 996 /*#ifdef DIAGNOSTIC*/ 997 #ifdef INET6 998 if (max_linkhdr + hdrlen > MCLBYTES) 999 #else 1000 if (max_linkhdr + hdrlen > MHLEN) 1001 #endif 1002 panic("tcphdr too big"); 1003 /*#endif*/ 1004 1005 /* 1006 * This KASSERT is here to catch edge cases at a well defined place. 1007 * Before, those had triggered (random) panic conditions further down. 1008 */ 1009 KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__)); 1010 1011 /* 1012 * Grab a header mbuf, attaching a copy of data to 1013 * be transmitted, and initialize the header from 1014 * the template for sends on this connection. 1015 */ 1016 if (len) { 1017 struct mbuf *mb; 1018 struct sockbuf *msb; 1019 u_int moff; 1020 1021 if ((tp->t_flags & TF_FORCEDATA) && len == 1) { 1022 TCPSTAT_INC(tcps_sndprobe); 1023 #ifdef STATS 1024 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) 1025 stats_voi_update_abs_u32(tp->t_stats, 1026 VOI_TCP_RETXPB, len); 1027 else 1028 stats_voi_update_abs_u64(tp->t_stats, 1029 VOI_TCP_TXPB, len); 1030 #endif /* STATS */ 1031 } else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) { 1032 tp->t_sndrexmitpack++; 1033 TCPSTAT_INC(tcps_sndrexmitpack); 1034 TCPSTAT_ADD(tcps_sndrexmitbyte, len); 1035 if (sack_rxmit) { 1036 TCPSTAT_INC(tcps_sack_rexmits); 1037 if (tso) { 1038 TCPSTAT_INC(tcps_sack_rexmits_tso); 1039 } 1040 TCPSTAT_ADD(tcps_sack_rexmit_bytes, len); 1041 } 1042 #ifdef STATS 1043 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB, 1044 len); 1045 #endif /* STATS */ 1046 } else { 1047 TCPSTAT_INC(tcps_sndpack); 1048 TCPSTAT_ADD(tcps_sndbyte, len); 1049 #ifdef STATS 1050 stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB, 1051 len); 1052 #endif /* STATS */ 1053 } 1054 #ifdef INET6 1055 if (MHLEN < hdrlen + max_linkhdr) 1056 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); 1057 else 1058 #endif 1059 m = m_gethdr(M_NOWAIT, MT_DATA); 1060 1061 if (m == NULL) { 1062 SOCKBUF_UNLOCK(&so->so_snd); 1063 error = ENOBUFS; 1064 sack_rxmit = 0; 1065 goto out; 1066 } 1067 1068 m->m_data += max_linkhdr; 1069 m->m_len = hdrlen; 1070 1071 /* 1072 * Start the m_copy functions from the closest mbuf 1073 * to the offset in the socket buffer chain. 1074 */ 1075 mb = sbsndptr_noadv(&so->so_snd, off, &moff); 1076 if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) { 1077 m_copydata(mb, moff, len, 1078 mtod(m, caddr_t) + hdrlen); 1079 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) 1080 sbsndptr_adv(&so->so_snd, mb, len); 1081 m->m_len += len; 1082 } else { 1083 int32_t old_len; 1084 1085 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) 1086 msb = NULL; 1087 else 1088 msb = &so->so_snd; 1089 old_len = len; 1090 m->m_next = tcp_m_copym(mb, moff, 1091 &len, if_hw_tsomaxsegcount, 1092 if_hw_tsomaxsegsize, msb, hw_tls); 1093 if (old_len != len) 1094 flags &= ~TH_FIN; 1095 if (len <= (tp->t_maxseg - optlen)) { 1096 /* 1097 * Must have ran out of mbufs for the copy 1098 * shorten it to no longer need tso. Lets 1099 * not put on sendalot since we are low on 1100 * mbufs. 1101 */ 1102 tso = 0; 1103 } 1104 if (m->m_next == NULL) { 1105 SOCKBUF_UNLOCK(&so->so_snd); 1106 (void) m_free(m); 1107 error = ENOBUFS; 1108 sack_rxmit = 0; 1109 goto out; 1110 } 1111 } 1112 1113 /* 1114 * If we're sending everything we've got, set PUSH. 1115 * (This will keep happy those implementations which only 1116 * give data to the user when a buffer fills or 1117 * a PUSH comes in.) 1118 */ 1119 if (((uint32_t)off + (uint32_t)len == sbused(&so->so_snd)) && 1120 !(flags & TH_SYN)) 1121 flags |= TH_PUSH; 1122 SOCKBUF_UNLOCK(&so->so_snd); 1123 } else { 1124 SOCKBUF_UNLOCK(&so->so_snd); 1125 if (tp->t_flags & TF_ACKNOW) 1126 TCPSTAT_INC(tcps_sndacks); 1127 else if (flags & (TH_SYN|TH_FIN|TH_RST)) 1128 TCPSTAT_INC(tcps_sndctrl); 1129 else if (SEQ_GT(tp->snd_up, tp->snd_una)) 1130 TCPSTAT_INC(tcps_sndurg); 1131 else 1132 TCPSTAT_INC(tcps_sndwinup); 1133 1134 m = m_gethdr(M_NOWAIT, MT_DATA); 1135 if (m == NULL) { 1136 error = ENOBUFS; 1137 sack_rxmit = 0; 1138 goto out; 1139 } 1140 #ifdef INET6 1141 if (isipv6 && (MHLEN < hdrlen + max_linkhdr) && 1142 MHLEN >= hdrlen) { 1143 M_ALIGN(m, hdrlen); 1144 } else 1145 #endif 1146 m->m_data += max_linkhdr; 1147 m->m_len = hdrlen; 1148 } 1149 SOCKBUF_UNLOCK_ASSERT(&so->so_snd); 1150 m->m_pkthdr.rcvif = (struct ifnet *)0; 1151 #ifdef MAC 1152 mac_inpcb_create_mbuf(inp, m); 1153 #endif 1154 #ifdef INET6 1155 if (isipv6) { 1156 ip6 = mtod(m, struct ip6_hdr *); 1157 if (tp->t_port) { 1158 udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr)); 1159 udp->uh_sport = htons(V_tcp_udp_tunneling_port); 1160 udp->uh_dport = tp->t_port; 1161 ulen = hdrlen + len - sizeof(struct ip6_hdr); 1162 udp->uh_ulen = htons(ulen); 1163 th = (struct tcphdr *)(udp + 1); 1164 } else { 1165 th = (struct tcphdr *)(ip6 + 1); 1166 } 1167 tcpip_fillheaders(inp, tp->t_port, ip6, th); 1168 } else 1169 #endif /* INET6 */ 1170 { 1171 ip = mtod(m, struct ip *); 1172 if (tp->t_port) { 1173 udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip)); 1174 udp->uh_sport = htons(V_tcp_udp_tunneling_port); 1175 udp->uh_dport = tp->t_port; 1176 ulen = hdrlen + len - sizeof(struct ip); 1177 udp->uh_ulen = htons(ulen); 1178 th = (struct tcphdr *)(udp + 1); 1179 } else 1180 th = (struct tcphdr *)(ip + 1); 1181 tcpip_fillheaders(inp, tp->t_port, ip, th); 1182 } 1183 1184 /* 1185 * Fill in fields, remembering maximum advertised 1186 * window for use in delaying messages about window sizes. 1187 * If resending a FIN, be sure not to use a new sequence number. 1188 */ 1189 if (flags & TH_FIN && tp->t_flags & TF_SENTFIN && 1190 tp->snd_nxt == tp->snd_max) 1191 tp->snd_nxt--; 1192 /* 1193 * If we are starting a connection, send ECN setup 1194 * SYN packet. If we are on a retransmit, we may 1195 * resend those bits a number of times as per 1196 * RFC 3168. 1197 */ 1198 if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn) { 1199 flags |= tcp_ecn_output_syn_sent(tp); 1200 } 1201 /* Also handle parallel SYN for ECN */ 1202 if ((TCPS_HAVERCVDSYN(tp->t_state)) && 1203 (tp->t_flags2 & (TF2_ECN_PERMIT | TF2_ACE_PERMIT))) { 1204 int ect = tcp_ecn_output_established(tp, &flags, len, sack_rxmit); 1205 if ((tp->t_state == TCPS_SYN_RECEIVED) && 1206 (tp->t_flags2 & TF2_ECN_SND_ECE)) 1207 tp->t_flags2 &= ~TF2_ECN_SND_ECE; 1208 #ifdef INET6 1209 if (isipv6) { 1210 ip6->ip6_flow &= ~htonl(IPTOS_ECN_MASK << IPV6_FLOWLABEL_LEN); 1211 ip6->ip6_flow |= htonl(ect << IPV6_FLOWLABEL_LEN); 1212 } 1213 else 1214 #endif 1215 { 1216 ip->ip_tos &= ~IPTOS_ECN_MASK; 1217 ip->ip_tos |= ect; 1218 } 1219 } 1220 1221 /* 1222 * If we are doing retransmissions, then snd_nxt will 1223 * not reflect the first unsent octet. For ACK only 1224 * packets, we do not want the sequence number of the 1225 * retransmitted packet, we want the sequence number 1226 * of the next unsent octet. So, if there is no data 1227 * (and no SYN or FIN), use snd_max instead of snd_nxt 1228 * when filling in ti_seq. But if we are in persist 1229 * state, snd_max might reflect one byte beyond the 1230 * right edge of the window, so use snd_nxt in that 1231 * case, since we know we aren't doing a retransmission. 1232 * (retransmit and persist are mutually exclusive...) 1233 */ 1234 if (sack_rxmit == 0) { 1235 if (len || (flags & (TH_SYN|TH_FIN)) || 1236 tcp_timer_active(tp, TT_PERSIST)) 1237 th->th_seq = htonl(tp->snd_nxt); 1238 else 1239 th->th_seq = htonl(tp->snd_max); 1240 } else { 1241 th->th_seq = htonl(p->rxmit); 1242 p->rxmit += len; 1243 /* 1244 * Lost Retransmission Detection 1245 * trigger resending of a (then 1246 * still existing) hole, when 1247 * fack acks recoverypoint. 1248 */ 1249 if ((tp->t_flags & TF_LRD) && SEQ_GEQ(p->rxmit, p->end)) 1250 p->rxmit = tp->snd_recover; 1251 tp->sackhint.sack_bytes_rexmit += len; 1252 } 1253 if (IN_RECOVERY(tp->t_flags)) { 1254 /* 1255 * Account all bytes transmitted while 1256 * IN_RECOVERY, simplifying PRR and 1257 * Lost Retransmit Detection 1258 */ 1259 tp->sackhint.prr_out += len; 1260 } 1261 th->th_ack = htonl(tp->rcv_nxt); 1262 if (optlen) { 1263 bcopy(opt, th + 1, optlen); 1264 th->th_off = (sizeof (struct tcphdr) + optlen) >> 2; 1265 } 1266 tcp_set_flags(th, flags); 1267 /* 1268 * Calculate receive window. Don't shrink window, 1269 * but avoid silly window syndrome. 1270 * If a RST segment is sent, advertise a window of zero. 1271 */ 1272 if (flags & TH_RST) { 1273 recwin = 0; 1274 } else { 1275 if (recwin < (so->so_rcv.sb_hiwat / 4) && 1276 recwin < tp->t_maxseg) 1277 recwin = 0; 1278 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) && 1279 recwin < (tp->rcv_adv - tp->rcv_nxt)) 1280 recwin = (tp->rcv_adv - tp->rcv_nxt); 1281 } 1282 /* 1283 * According to RFC1323 the window field in a SYN (i.e., a <SYN> 1284 * or <SYN,ACK>) segment itself is never scaled. The <SYN,ACK> 1285 * case is handled in syncache. 1286 */ 1287 if (flags & TH_SYN) 1288 th->th_win = htons((u_short) 1289 (min(sbspace(&so->so_rcv), TCP_MAXWIN))); 1290 else { 1291 /* Avoid shrinking window with window scaling. */ 1292 recwin = roundup2(recwin, 1 << tp->rcv_scale); 1293 th->th_win = htons((u_short)(recwin >> tp->rcv_scale)); 1294 } 1295 1296 /* 1297 * Adjust the RXWIN0SENT flag - indicate that we have advertised 1298 * a 0 window. This may cause the remote transmitter to stall. This 1299 * flag tells soreceive() to disable delayed acknowledgements when 1300 * draining the buffer. This can occur if the receiver is attempting 1301 * to read more data than can be buffered prior to transmitting on 1302 * the connection. 1303 */ 1304 if (th->th_win == 0) { 1305 tp->t_sndzerowin++; 1306 tp->t_flags |= TF_RXWIN0SENT; 1307 } else 1308 tp->t_flags &= ~TF_RXWIN0SENT; 1309 if (SEQ_GT(tp->snd_up, tp->snd_nxt)) { 1310 th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt)); 1311 th->th_flags |= TH_URG; 1312 } else 1313 /* 1314 * If no urgent pointer to send, then we pull 1315 * the urgent pointer to the left edge of the send window 1316 * so that it doesn't drift into the send window on sequence 1317 * number wraparound. 1318 */ 1319 tp->snd_up = tp->snd_una; /* drag it along */ 1320 1321 /* 1322 * Put TCP length in extended header, and then 1323 * checksum extended header and data. 1324 */ 1325 m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */ 1326 1327 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1328 if (to.to_flags & TOF_SIGNATURE) { 1329 /* 1330 * Calculate MD5 signature and put it into the place 1331 * determined before. 1332 * NOTE: since TCP options buffer doesn't point into 1333 * mbuf's data, calculate offset and use it. 1334 */ 1335 if (!TCPMD5_ENABLED() || (error = TCPMD5_OUTPUT(m, th, 1336 (u_char *)(th + 1) + (to.to_signature - opt))) != 0) { 1337 /* 1338 * Do not send segment if the calculation of MD5 1339 * digest has failed. 1340 */ 1341 m_freem(m); 1342 goto out; 1343 } 1344 } 1345 #endif 1346 #ifdef INET6 1347 if (isipv6) { 1348 /* 1349 * There is no need to fill in ip6_plen right now. 1350 * It will be filled later by ip6_output. 1351 */ 1352 if (tp->t_port) { 1353 m->m_pkthdr.csum_flags = CSUM_UDP_IPV6; 1354 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum); 1355 udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0); 1356 th->th_sum = htons(0); 1357 UDPSTAT_INC(udps_opackets); 1358 } else { 1359 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6; 1360 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 1361 th->th_sum = in6_cksum_pseudo(ip6, 1362 sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP, 1363 0); 1364 } 1365 } 1366 #endif 1367 #if defined(INET6) && defined(INET) 1368 else 1369 #endif 1370 #ifdef INET 1371 { 1372 if (tp->t_port) { 1373 m->m_pkthdr.csum_flags = CSUM_UDP; 1374 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum); 1375 udp->uh_sum = in_pseudo(ip->ip_src.s_addr, 1376 ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP)); 1377 th->th_sum = htons(0); 1378 UDPSTAT_INC(udps_opackets); 1379 } else { 1380 m->m_pkthdr.csum_flags = CSUM_TCP; 1381 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 1382 th->th_sum = in_pseudo(ip->ip_src.s_addr, 1383 ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) + 1384 IPPROTO_TCP + len + optlen)); 1385 } 1386 1387 /* IP version must be set here for ipv4/ipv6 checking later */ 1388 KASSERT(ip->ip_v == IPVERSION, 1389 ("%s: IP version incorrect: %d", __func__, ip->ip_v)); 1390 } 1391 #endif 1392 1393 /* 1394 * Enable TSO and specify the size of the segments. 1395 * The TCP pseudo header checksum is always provided. 1396 */ 1397 if (tso) { 1398 KASSERT(len > tp->t_maxseg - optlen - ipsec_optlen, 1399 ("%s: len <= tso_segsz", __func__)); 1400 m->m_pkthdr.csum_flags |= CSUM_TSO; 1401 m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen - ipsec_optlen; 1402 } 1403 1404 KASSERT(len + hdrlen == m_length(m, NULL), 1405 ("%s: mbuf chain shorter than expected: %d + %u != %u", 1406 __func__, len, hdrlen, m_length(m, NULL))); 1407 1408 #ifdef TCP_HHOOK 1409 /* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */ 1410 hhook_run_tcp_est_out(tp, th, &to, len, tso); 1411 #endif 1412 1413 TCP_PROBE3(debug__output, tp, th, m); 1414 1415 /* We're getting ready to send; log now. */ 1416 /* XXXMT: We are not honoring verbose logging. */ 1417 1418 if (tcp_bblogging_on(tp)) 1419 lgb = tcp_log_event(tp, th, &so->so_rcv, &so->so_snd, 1420 TCP_LOG_OUT, ERRNO_UNK, len, NULL, false, NULL, NULL, 0, 1421 NULL); 1422 else 1423 lgb = NULL; 1424 1425 /* 1426 * Fill in IP length and desired time to live and 1427 * send to IP level. There should be a better way 1428 * to handle ttl and tos; we could keep them in 1429 * the template, but need a way to checksum without them. 1430 */ 1431 /* 1432 * m->m_pkthdr.len should have been set before checksum calculation, 1433 * because in6_cksum() need it. 1434 */ 1435 #ifdef INET6 1436 if (isipv6) { 1437 /* 1438 * we separately set hoplimit for every segment, since the 1439 * user might want to change the value via setsockopt. 1440 * Also, desired default hop limit might be changed via 1441 * Neighbor Discovery. 1442 */ 1443 ip6->ip6_hlim = in6_selecthlim(inp, NULL); 1444 1445 /* 1446 * Set the packet size here for the benefit of DTrace probes. 1447 * ip6_output() will set it properly; it's supposed to include 1448 * the option header lengths as well. 1449 */ 1450 ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6)); 1451 1452 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) 1453 tp->t_flags2 |= TF2_PLPMTU_PMTUD; 1454 else 1455 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD; 1456 1457 if (tp->t_state == TCPS_SYN_SENT) 1458 TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th); 1459 1460 TCP_PROBE5(send, NULL, tp, ip6, tp, th); 1461 1462 #ifdef TCPPCAP 1463 /* Save packet, if requested. */ 1464 tcp_pcap_add(th, m, &(tp->t_outpkts)); 1465 #endif 1466 1467 /* TODO: IPv6 IP6TOS_ECT bit on */ 1468 error = ip6_output(m, inp->in6p_outputopts, &inp->inp_route6, 1469 ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 1470 NULL, NULL, inp); 1471 1472 if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL) 1473 mtu = inp->inp_route6.ro_nh->nh_mtu; 1474 } 1475 #endif /* INET6 */ 1476 #if defined(INET) && defined(INET6) 1477 else 1478 #endif 1479 #ifdef INET 1480 { 1481 ip->ip_len = htons(m->m_pkthdr.len); 1482 #ifdef INET6 1483 if (inp->inp_vflag & INP_IPV6PROTO) 1484 ip->ip_ttl = in6_selecthlim(inp, NULL); 1485 #endif /* INET6 */ 1486 /* 1487 * If we do path MTU discovery, then we set DF on every packet. 1488 * This might not be the best thing to do according to RFC3390 1489 * Section 2. However the tcp hostcache migitates the problem 1490 * so it affects only the first tcp connection with a host. 1491 * 1492 * NB: Don't set DF on small MTU/MSS to have a safe fallback. 1493 */ 1494 if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) { 1495 tp->t_flags2 |= TF2_PLPMTU_PMTUD; 1496 if (tp->t_port == 0 || len < V_tcp_minmss) { 1497 ip->ip_off |= htons(IP_DF); 1498 } 1499 } else { 1500 tp->t_flags2 &= ~TF2_PLPMTU_PMTUD; 1501 } 1502 1503 if (tp->t_state == TCPS_SYN_SENT) 1504 TCP_PROBE5(connect__request, NULL, tp, ip, tp, th); 1505 1506 TCP_PROBE5(send, NULL, tp, ip, tp, th); 1507 1508 #ifdef TCPPCAP 1509 /* Save packet, if requested. */ 1510 tcp_pcap_add(th, m, &(tp->t_outpkts)); 1511 #endif 1512 1513 error = ip_output(m, inp->inp_options, &inp->inp_route, 1514 ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0, inp); 1515 1516 if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL) 1517 mtu = inp->inp_route.ro_nh->nh_mtu; 1518 } 1519 #endif /* INET */ 1520 1521 if (lgb != NULL) { 1522 lgb->tlb_errno = error; 1523 lgb = NULL; 1524 } 1525 out: 1526 if (error == 0) 1527 tcp_account_for_send(tp, len, (tp->snd_nxt != tp->snd_max), 0, hw_tls); 1528 /* 1529 * In transmit state, time the transmission and arrange for 1530 * the retransmit. In persist state, just set snd_max. In a closed 1531 * state just return. 1532 */ 1533 if (flags & TH_RST) { 1534 TCPSTAT_INC(tcps_sndtotal); 1535 return (0); 1536 } else if ((tp->t_flags & TF_FORCEDATA) == 0 || 1537 !tcp_timer_active(tp, TT_PERSIST)) { 1538 tcp_seq startseq = tp->snd_nxt; 1539 1540 /* 1541 * Advance snd_nxt over sequence space of this segment. 1542 */ 1543 if (flags & (TH_SYN|TH_FIN)) { 1544 if (flags & TH_SYN) 1545 tp->snd_nxt++; 1546 if (flags & TH_FIN) { 1547 tp->snd_nxt++; 1548 tp->t_flags |= TF_SENTFIN; 1549 } 1550 } 1551 if (sack_rxmit) 1552 goto timer; 1553 tp->snd_nxt += len; 1554 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) { 1555 /* 1556 * Update "made progress" indication if we just 1557 * added new data to an empty socket buffer. 1558 */ 1559 if (tp->snd_una == tp->snd_max) 1560 tp->t_acktime = ticks; 1561 tp->snd_max = tp->snd_nxt; 1562 /* 1563 * Time this transmission if not a retransmission and 1564 * not currently timing anything. 1565 */ 1566 tp->t_sndtime = ticks; 1567 if (tp->t_rtttime == 0) { 1568 tp->t_rtttime = ticks; 1569 tp->t_rtseq = startseq; 1570 TCPSTAT_INC(tcps_segstimed); 1571 } 1572 #ifdef STATS 1573 if (!(tp->t_flags & TF_GPUTINPROG) && len) { 1574 tp->t_flags |= TF_GPUTINPROG; 1575 tp->gput_seq = startseq; 1576 tp->gput_ack = startseq + 1577 ulmin(sbavail(&so->so_snd) - off, sendwin); 1578 tp->gput_ts = tcp_ts_getticks(); 1579 } 1580 #endif /* STATS */ 1581 } 1582 1583 /* 1584 * Set retransmit timer if not currently set, 1585 * and not doing a pure ack or a keep-alive probe. 1586 * Initial value for retransmit timer is smoothed 1587 * round-trip time + 2 * round-trip time variance. 1588 * Initialize shift counter which is used for backoff 1589 * of retransmit time. 1590 */ 1591 timer: 1592 if (!tcp_timer_active(tp, TT_REXMT) && 1593 ((sack_rxmit && tp->snd_nxt != tp->snd_max) || 1594 (tp->snd_nxt != tp->snd_una))) { 1595 if (tcp_timer_active(tp, TT_PERSIST)) { 1596 tcp_timer_activate(tp, TT_PERSIST, 0); 1597 tp->t_rxtshift = 0; 1598 } 1599 tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp)); 1600 } else if (len == 0 && sbavail(&so->so_snd) && 1601 !tcp_timer_active(tp, TT_REXMT) && 1602 !tcp_timer_active(tp, TT_PERSIST)) { 1603 /* 1604 * Avoid a situation where we do not set persist timer 1605 * after a zero window condition. For example: 1606 * 1) A -> B: packet with enough data to fill the window 1607 * 2) B -> A: ACK for #1 + new data (0 window 1608 * advertisement) 1609 * 3) A -> B: ACK for #2, 0 len packet 1610 * 1611 * In this case, A will not activate the persist timer, 1612 * because it chose to send a packet. Unless tcp_output 1613 * is called for some other reason (delayed ack timer, 1614 * another input packet from B, socket syscall), A will 1615 * not send zero window probes. 1616 * 1617 * So, if you send a 0-length packet, but there is data 1618 * in the socket buffer, and neither the rexmt or 1619 * persist timer is already set, then activate the 1620 * persist timer. 1621 */ 1622 tp->t_rxtshift = 0; 1623 tcp_setpersist(tp); 1624 } 1625 } else { 1626 /* 1627 * Persist case, update snd_max but since we are in 1628 * persist mode (no window) we do not update snd_nxt. 1629 */ 1630 int xlen = len; 1631 if (flags & TH_SYN) 1632 ++xlen; 1633 if (flags & TH_FIN) { 1634 ++xlen; 1635 tp->t_flags |= TF_SENTFIN; 1636 } 1637 if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max)) 1638 tp->snd_max = tp->snd_nxt + xlen; 1639 } 1640 if ((error == 0) && 1641 (tp->rcv_numsacks > 0) && 1642 TCPS_HAVEESTABLISHED(tp->t_state) && 1643 (tp->t_flags & TF_SACK_PERMIT)) { 1644 /* Clean up any DSACK's sent */ 1645 tcp_clean_dsack_blocks(tp); 1646 } 1647 if ((error == 0) && 1648 sack_rxmit && 1649 SEQ_LT(tp->snd_nxt, SEQ_MIN(p->rxmit, p->end))) { 1650 tp->snd_nxt = SEQ_MIN(p->rxmit, p->end); 1651 } 1652 if (error) { 1653 /* 1654 * We know that the packet was lost, so back out the 1655 * sequence number advance, if any. 1656 * 1657 * If the error is EPERM the packet got blocked by the 1658 * local firewall. Normally we should terminate the 1659 * connection but the blocking may have been spurious 1660 * due to a firewall reconfiguration cycle. So we treat 1661 * it like a packet loss and let the retransmit timer and 1662 * timeouts do their work over time. 1663 * XXX: It is a POLA question whether calling tcp_drop right 1664 * away would be the really correct behavior instead. 1665 */ 1666 if (((tp->t_flags & TF_FORCEDATA) == 0 || 1667 !tcp_timer_active(tp, TT_PERSIST)) && 1668 ((flags & TH_SYN) == 0) && 1669 (error != EPERM)) { 1670 if (sack_rxmit) { 1671 p->rxmit = SEQ_MIN(p->end, p->rxmit) - len; 1672 tp->sackhint.sack_bytes_rexmit -= len; 1673 KASSERT(tp->sackhint.sack_bytes_rexmit >= 0, 1674 ("sackhint bytes rtx >= 0")); 1675 KASSERT((flags & TH_FIN) == 0, 1676 ("error while FIN with SACK rxmit")); 1677 } else { 1678 tp->snd_nxt -= len; 1679 if (flags & TH_FIN) 1680 tp->snd_nxt--; 1681 } 1682 if (IN_RECOVERY(tp->t_flags)) 1683 tp->sackhint.prr_out -= len; 1684 } 1685 SOCKBUF_UNLOCK_ASSERT(&so->so_snd); /* Check gotos. */ 1686 switch (error) { 1687 case EACCES: 1688 case EPERM: 1689 tp->t_softerror = error; 1690 return (error); 1691 case ENOBUFS: 1692 TCP_XMIT_TIMER_ASSERT(tp, len, flags); 1693 tp->snd_cwnd = tp->t_maxseg; 1694 return (0); 1695 case EMSGSIZE: 1696 /* 1697 * For some reason the interface we used initially 1698 * to send segments changed to another or lowered 1699 * its MTU. 1700 * If TSO was active we either got an interface 1701 * without TSO capabilits or TSO was turned off. 1702 * If we obtained mtu from ip_output() then update 1703 * it and try again. 1704 */ 1705 if (tso) 1706 tp->t_flags &= ~TF_TSO; 1707 if (mtu != 0) { 1708 tcp_mss_update(tp, -1, mtu, NULL, NULL); 1709 goto again; 1710 } 1711 return (error); 1712 case EHOSTDOWN: 1713 case EHOSTUNREACH: 1714 case ENETDOWN: 1715 case ENETUNREACH: 1716 if (TCPS_HAVERCVDSYN(tp->t_state)) { 1717 tp->t_softerror = error; 1718 return (0); 1719 } 1720 /* FALLTHROUGH */ 1721 default: 1722 return (error); 1723 } 1724 } 1725 TCPSTAT_INC(tcps_sndtotal); 1726 1727 /* 1728 * Data sent (as far as we can tell). 1729 * If this advertises a larger window than any other segment, 1730 * then remember the size of the advertised window. 1731 * Any pending ACK has now been sent. 1732 */ 1733 if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv)) 1734 tp->rcv_adv = tp->rcv_nxt + recwin; 1735 tp->last_ack_sent = tp->rcv_nxt; 1736 tp->t_flags &= ~(TF_ACKNOW | TF_DELACK); 1737 if (tcp_timer_active(tp, TT_DELACK)) 1738 tcp_timer_activate(tp, TT_DELACK, 0); 1739 if (sendalot) 1740 goto again; 1741 return (0); 1742 } 1743 1744 void 1745 tcp_setpersist(struct tcpcb *tp) 1746 { 1747 int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1; 1748 int tt; 1749 int maxunacktime; 1750 1751 tp->t_flags &= ~TF_PREVVALID; 1752 if (tcp_timer_active(tp, TT_REXMT)) 1753 panic("tcp_setpersist: retransmit pending"); 1754 /* 1755 * If the state is already closed, don't bother. 1756 */ 1757 if (tp->t_state == TCPS_CLOSED) 1758 return; 1759 1760 /* 1761 * Start/restart persistence timer. 1762 */ 1763 TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift], 1764 tcp_persmin, tcp_persmax); 1765 if (TP_MAXUNACKTIME(tp) && tp->t_acktime) { 1766 maxunacktime = tp->t_acktime + TP_MAXUNACKTIME(tp) - ticks; 1767 if (maxunacktime < 1) 1768 maxunacktime = 1; 1769 if (maxunacktime < tt) 1770 tt = maxunacktime; 1771 } 1772 tcp_timer_activate(tp, TT_PERSIST, tt); 1773 if (tp->t_rxtshift < V_tcp_retries) 1774 tp->t_rxtshift++; 1775 } 1776 1777 /* 1778 * Insert TCP options according to the supplied parameters to the place 1779 * optp in a consistent way. Can handle unaligned destinations. 1780 * 1781 * The order of the option processing is crucial for optimal packing and 1782 * alignment for the scarce option space. 1783 * 1784 * The optimal order for a SYN/SYN-ACK segment is: 1785 * MSS (4) + NOP (1) + Window scale (3) + SACK permitted (2) + 1786 * Timestamp (10) + Signature (18) = 38 bytes out of a maximum of 40. 1787 * 1788 * The SACK options should be last. SACK blocks consume 8*n+2 bytes. 1789 * So a full size SACK blocks option is 34 bytes (with 4 SACK blocks). 1790 * At minimum we need 10 bytes (to generate 1 SACK block). If both 1791 * TCP Timestamps (12 bytes) and TCP Signatures (18 bytes) are present, 1792 * we only have 10 bytes for SACK options (40 - (12 + 18)). 1793 */ 1794 int 1795 tcp_addoptions(struct tcpopt *to, u_char *optp) 1796 { 1797 u_int32_t mask, optlen = 0; 1798 1799 for (mask = 1; mask < TOF_MAXOPT; mask <<= 1) { 1800 if ((to->to_flags & mask) != mask) 1801 continue; 1802 if (optlen == TCP_MAXOLEN) 1803 break; 1804 switch (to->to_flags & mask) { 1805 case TOF_MSS: 1806 while (optlen % 4) { 1807 optlen += TCPOLEN_NOP; 1808 *optp++ = TCPOPT_NOP; 1809 } 1810 if (TCP_MAXOLEN - optlen < TCPOLEN_MAXSEG) 1811 continue; 1812 optlen += TCPOLEN_MAXSEG; 1813 *optp++ = TCPOPT_MAXSEG; 1814 *optp++ = TCPOLEN_MAXSEG; 1815 to->to_mss = htons(to->to_mss); 1816 bcopy((u_char *)&to->to_mss, optp, sizeof(to->to_mss)); 1817 optp += sizeof(to->to_mss); 1818 break; 1819 case TOF_SCALE: 1820 while (!optlen || optlen % 2 != 1) { 1821 optlen += TCPOLEN_NOP; 1822 *optp++ = TCPOPT_NOP; 1823 } 1824 if (TCP_MAXOLEN - optlen < TCPOLEN_WINDOW) 1825 continue; 1826 optlen += TCPOLEN_WINDOW; 1827 *optp++ = TCPOPT_WINDOW; 1828 *optp++ = TCPOLEN_WINDOW; 1829 *optp++ = to->to_wscale; 1830 break; 1831 case TOF_SACKPERM: 1832 while (optlen % 2) { 1833 optlen += TCPOLEN_NOP; 1834 *optp++ = TCPOPT_NOP; 1835 } 1836 if (TCP_MAXOLEN - optlen < TCPOLEN_SACK_PERMITTED) 1837 continue; 1838 optlen += TCPOLEN_SACK_PERMITTED; 1839 *optp++ = TCPOPT_SACK_PERMITTED; 1840 *optp++ = TCPOLEN_SACK_PERMITTED; 1841 break; 1842 case TOF_TS: 1843 while (!optlen || optlen % 4 != 2) { 1844 optlen += TCPOLEN_NOP; 1845 *optp++ = TCPOPT_NOP; 1846 } 1847 if (TCP_MAXOLEN - optlen < TCPOLEN_TIMESTAMP) 1848 continue; 1849 optlen += TCPOLEN_TIMESTAMP; 1850 *optp++ = TCPOPT_TIMESTAMP; 1851 *optp++ = TCPOLEN_TIMESTAMP; 1852 to->to_tsval = htonl(to->to_tsval); 1853 to->to_tsecr = htonl(to->to_tsecr); 1854 bcopy((u_char *)&to->to_tsval, optp, sizeof(to->to_tsval)); 1855 optp += sizeof(to->to_tsval); 1856 bcopy((u_char *)&to->to_tsecr, optp, sizeof(to->to_tsecr)); 1857 optp += sizeof(to->to_tsecr); 1858 break; 1859 case TOF_SIGNATURE: 1860 { 1861 int siglen = TCPOLEN_SIGNATURE - 2; 1862 1863 while (!optlen || optlen % 4 != 2) { 1864 optlen += TCPOLEN_NOP; 1865 *optp++ = TCPOPT_NOP; 1866 } 1867 if (TCP_MAXOLEN - optlen < TCPOLEN_SIGNATURE) { 1868 to->to_flags &= ~TOF_SIGNATURE; 1869 continue; 1870 } 1871 optlen += TCPOLEN_SIGNATURE; 1872 *optp++ = TCPOPT_SIGNATURE; 1873 *optp++ = TCPOLEN_SIGNATURE; 1874 to->to_signature = optp; 1875 while (siglen--) 1876 *optp++ = 0; 1877 break; 1878 } 1879 case TOF_SACK: 1880 { 1881 int sackblks = 0; 1882 struct sackblk *sack = (struct sackblk *)to->to_sacks; 1883 tcp_seq sack_seq; 1884 1885 while (!optlen || optlen % 4 != 2) { 1886 optlen += TCPOLEN_NOP; 1887 *optp++ = TCPOPT_NOP; 1888 } 1889 if (TCP_MAXOLEN - optlen < TCPOLEN_SACKHDR + TCPOLEN_SACK) 1890 continue; 1891 optlen += TCPOLEN_SACKHDR; 1892 *optp++ = TCPOPT_SACK; 1893 sackblks = min(to->to_nsacks, 1894 (TCP_MAXOLEN - optlen) / TCPOLEN_SACK); 1895 *optp++ = TCPOLEN_SACKHDR + sackblks * TCPOLEN_SACK; 1896 while (sackblks--) { 1897 sack_seq = htonl(sack->start); 1898 bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq)); 1899 optp += sizeof(sack_seq); 1900 sack_seq = htonl(sack->end); 1901 bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq)); 1902 optp += sizeof(sack_seq); 1903 optlen += TCPOLEN_SACK; 1904 sack++; 1905 } 1906 TCPSTAT_INC(tcps_sack_send_blocks); 1907 break; 1908 } 1909 case TOF_FASTOPEN: 1910 { 1911 int total_len; 1912 1913 /* XXX is there any point to aligning this option? */ 1914 total_len = TCPOLEN_FAST_OPEN_EMPTY + to->to_tfo_len; 1915 if (TCP_MAXOLEN - optlen < total_len) { 1916 to->to_flags &= ~TOF_FASTOPEN; 1917 continue; 1918 } 1919 *optp++ = TCPOPT_FAST_OPEN; 1920 *optp++ = total_len; 1921 if (to->to_tfo_len > 0) { 1922 bcopy(to->to_tfo_cookie, optp, to->to_tfo_len); 1923 optp += to->to_tfo_len; 1924 } 1925 optlen += total_len; 1926 break; 1927 } 1928 default: 1929 panic("%s: unknown TCP option type", __func__); 1930 break; 1931 } 1932 } 1933 1934 /* Terminate and pad TCP options to a 4 byte boundary. */ 1935 if (optlen % 4) { 1936 optlen += TCPOLEN_EOL; 1937 *optp++ = TCPOPT_EOL; 1938 } 1939 /* 1940 * According to RFC 793 (STD0007): 1941 * "The content of the header beyond the End-of-Option option 1942 * must be header padding (i.e., zero)." 1943 * and later: "The padding is composed of zeros." 1944 */ 1945 while (optlen % 4) { 1946 optlen += TCPOLEN_PAD; 1947 *optp++ = TCPOPT_PAD; 1948 } 1949 1950 KASSERT(optlen <= TCP_MAXOLEN, ("%s: TCP options too long", __func__)); 1951 return (optlen); 1952 } 1953 1954 /* 1955 * This is a copy of m_copym(), taking the TSO segment size/limit 1956 * constraints into account, and advancing the sndptr as it goes. 1957 */ 1958 struct mbuf * 1959 tcp_m_copym(struct mbuf *m, int32_t off0, int32_t *plen, 1960 int32_t seglimit, int32_t segsize, struct sockbuf *sb, bool hw_tls) 1961 { 1962 #ifdef KERN_TLS 1963 struct ktls_session *tls, *ntls; 1964 struct mbuf *start __diagused; 1965 #endif 1966 struct mbuf *n, **np; 1967 struct mbuf *top; 1968 int32_t off = off0; 1969 int32_t len = *plen; 1970 int32_t fragsize; 1971 int32_t len_cp = 0; 1972 int32_t *pkthdrlen; 1973 uint32_t mlen, frags; 1974 bool copyhdr; 1975 1976 KASSERT(off >= 0, ("tcp_m_copym, negative off %d", off)); 1977 KASSERT(len >= 0, ("tcp_m_copym, negative len %d", len)); 1978 if (off == 0 && m->m_flags & M_PKTHDR) 1979 copyhdr = true; 1980 else 1981 copyhdr = false; 1982 while (off > 0) { 1983 KASSERT(m != NULL, ("tcp_m_copym, offset > size of mbuf chain")); 1984 if (off < m->m_len) 1985 break; 1986 off -= m->m_len; 1987 if ((sb) && (m == sb->sb_sndptr)) { 1988 sb->sb_sndptroff += m->m_len; 1989 sb->sb_sndptr = m->m_next; 1990 } 1991 m = m->m_next; 1992 } 1993 np = ⊤ 1994 top = NULL; 1995 pkthdrlen = NULL; 1996 #ifdef KERN_TLS 1997 if (hw_tls && (m->m_flags & M_EXTPG)) 1998 tls = m->m_epg_tls; 1999 else 2000 tls = NULL; 2001 start = m; 2002 #endif 2003 while (len > 0) { 2004 if (m == NULL) { 2005 KASSERT(len == M_COPYALL, 2006 ("tcp_m_copym, length > size of mbuf chain")); 2007 *plen = len_cp; 2008 if (pkthdrlen != NULL) 2009 *pkthdrlen = len_cp; 2010 break; 2011 } 2012 #ifdef KERN_TLS 2013 if (hw_tls) { 2014 if (m->m_flags & M_EXTPG) 2015 ntls = m->m_epg_tls; 2016 else 2017 ntls = NULL; 2018 2019 /* 2020 * Avoid mixing TLS records with handshake 2021 * data or TLS records from different 2022 * sessions. 2023 */ 2024 if (tls != ntls) { 2025 MPASS(m != start); 2026 *plen = len_cp; 2027 if (pkthdrlen != NULL) 2028 *pkthdrlen = len_cp; 2029 break; 2030 } 2031 } 2032 #endif 2033 mlen = min(len, m->m_len - off); 2034 if (seglimit) { 2035 /* 2036 * For M_EXTPG mbufs, add 3 segments 2037 * + 1 in case we are crossing page boundaries 2038 * + 2 in case the TLS hdr/trailer are used 2039 * It is cheaper to just add the segments 2040 * than it is to take the cache miss to look 2041 * at the mbuf ext_pgs state in detail. 2042 */ 2043 if (m->m_flags & M_EXTPG) { 2044 fragsize = min(segsize, PAGE_SIZE); 2045 frags = 3; 2046 } else { 2047 fragsize = segsize; 2048 frags = 0; 2049 } 2050 2051 /* Break if we really can't fit anymore. */ 2052 if ((frags + 1) >= seglimit) { 2053 *plen = len_cp; 2054 if (pkthdrlen != NULL) 2055 *pkthdrlen = len_cp; 2056 break; 2057 } 2058 2059 /* 2060 * Reduce size if you can't copy the whole 2061 * mbuf. If we can't copy the whole mbuf, also 2062 * adjust len so the loop will end after this 2063 * mbuf. 2064 */ 2065 if ((frags + howmany(mlen, fragsize)) >= seglimit) { 2066 mlen = (seglimit - frags - 1) * fragsize; 2067 len = mlen; 2068 *plen = len_cp + len; 2069 if (pkthdrlen != NULL) 2070 *pkthdrlen = *plen; 2071 } 2072 frags += howmany(mlen, fragsize); 2073 if (frags == 0) 2074 frags++; 2075 seglimit -= frags; 2076 KASSERT(seglimit > 0, 2077 ("%s: seglimit went too low", __func__)); 2078 } 2079 if (copyhdr) 2080 n = m_gethdr(M_NOWAIT, m->m_type); 2081 else 2082 n = m_get(M_NOWAIT, m->m_type); 2083 *np = n; 2084 if (n == NULL) 2085 goto nospace; 2086 if (copyhdr) { 2087 if (!m_dup_pkthdr(n, m, M_NOWAIT)) 2088 goto nospace; 2089 if (len == M_COPYALL) 2090 n->m_pkthdr.len -= off0; 2091 else 2092 n->m_pkthdr.len = len; 2093 pkthdrlen = &n->m_pkthdr.len; 2094 copyhdr = false; 2095 } 2096 n->m_len = mlen; 2097 len_cp += n->m_len; 2098 if (m->m_flags & (M_EXT | M_EXTPG)) { 2099 n->m_data = m->m_data + off; 2100 mb_dupcl(n, m); 2101 } else 2102 bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t), 2103 (u_int)n->m_len); 2104 2105 if (sb && (sb->sb_sndptr == m) && 2106 ((n->m_len + off) >= m->m_len) && m->m_next) { 2107 sb->sb_sndptroff += m->m_len; 2108 sb->sb_sndptr = m->m_next; 2109 } 2110 off = 0; 2111 if (len != M_COPYALL) { 2112 len -= n->m_len; 2113 } 2114 m = m->m_next; 2115 np = &n->m_next; 2116 } 2117 return (top); 2118 nospace: 2119 m_freem(top); 2120 return (NULL); 2121 } 2122 2123 void 2124 tcp_sndbuf_autoscale(struct tcpcb *tp, struct socket *so, uint32_t sendwin) 2125 { 2126 2127 /* 2128 * Automatic sizing of send socket buffer. Often the send buffer 2129 * size is not optimally adjusted to the actual network conditions 2130 * at hand (delay bandwidth product). Setting the buffer size too 2131 * small limits throughput on links with high bandwidth and high 2132 * delay (eg. trans-continental/oceanic links). Setting the 2133 * buffer size too big consumes too much real kernel memory, 2134 * especially with many connections on busy servers. 2135 * 2136 * The criteria to step up the send buffer one notch are: 2137 * 1. receive window of remote host is larger than send buffer 2138 * (with a fudge factor of 5/4th); 2139 * 2. send buffer is filled to 7/8th with data (so we actually 2140 * have data to make use of it); 2141 * 3. send buffer fill has not hit maximal automatic size; 2142 * 4. our send window (slow start and cogestion controlled) is 2143 * larger than sent but unacknowledged data in send buffer. 2144 * 2145 * The remote host receive window scaling factor may limit the 2146 * growing of the send buffer before it reaches its allowed 2147 * maximum. 2148 * 2149 * It scales directly with slow start or congestion window 2150 * and does at most one step per received ACK. This fast 2151 * scaling has the drawback of growing the send buffer beyond 2152 * what is strictly necessary to make full use of a given 2153 * delay*bandwidth product. However testing has shown this not 2154 * to be much of an problem. At worst we are trading wasting 2155 * of available bandwidth (the non-use of it) for wasting some 2156 * socket buffer memory. 2157 * 2158 * TODO: Shrink send buffer during idle periods together 2159 * with congestion window. Requires another timer. Has to 2160 * wait for upcoming tcp timer rewrite. 2161 * 2162 * XXXGL: should there be used sbused() or sbavail()? 2163 */ 2164 if (V_tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) { 2165 int lowat; 2166 2167 lowat = V_tcp_sendbuf_auto_lowat ? so->so_snd.sb_lowat : 0; 2168 if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat - lowat && 2169 sbused(&so->so_snd) >= 2170 (so->so_snd.sb_hiwat / 8 * 7) - lowat && 2171 sbused(&so->so_snd) < V_tcp_autosndbuf_max && 2172 sendwin >= (sbused(&so->so_snd) - 2173 (tp->snd_nxt - tp->snd_una))) { 2174 if (!sbreserve_locked(so, SO_SND, 2175 min(so->so_snd.sb_hiwat + V_tcp_autosndbuf_inc, 2176 V_tcp_autosndbuf_max), curthread)) 2177 so->so_snd.sb_flags &= ~SB_AUTOSIZE; 2178 } 2179 } 2180 } 2181