tcp: Don't prematurely drop receiving-only connections.
[dragonfly.git] / sys / netinet / tcp_output.c
blob52bcf0bb5c0450f903d2019ffcd041bb3c5dd36b
1 /*
2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
6 * by Jeffrey M. Hsu.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
62 * @(#)tcp_output.c 8.4 (Berkeley) 5/24/95
63 * $FreeBSD: src/sys/netinet/tcp_output.c,v 1.39.2.20 2003/01/29 22:45:36 hsu Exp $
66 #include "opt_inet.h"
67 #include "opt_inet6.h"
68 #include "opt_ipsec.h"
69 #include "opt_tcpdebug.h"
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/sysctl.h>
75 #include <sys/mbuf.h>
76 #include <sys/domain.h>
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/in_cksum.h>
81 #include <sys/thread.h>
82 #include <sys/globaldata.h>
84 #include <net/if_var.h>
85 #include <net/route.h>
86 #include <net/netmsg2.h>
87 #include <net/netisr2.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/in_pcb.h>
93 #include <netinet/ip_var.h>
94 #include <netinet6/in6_pcb.h>
95 #include <netinet/ip6.h>
96 #include <netinet6/ip6_var.h>
97 #include <netinet/tcp.h>
98 #define TCPOUTFLAGS
99 #include <netinet/tcp_fsm.h>
100 #include <netinet/tcp_seq.h>
101 #include <netinet/tcp_timer.h>
102 #include <netinet/tcp_timer2.h>
103 #include <netinet/tcp_var.h>
104 #include <netinet/tcpip.h>
105 #ifdef TCPDEBUG
106 #include <netinet/tcp_debug.h>
107 #endif
109 #ifdef IPSEC
110 #include <netinet6/ipsec.h>
111 #endif /*IPSEC*/
113 #ifdef FAST_IPSEC
114 #include <netproto/ipsec/ipsec.h>
115 #define IPSEC
116 #endif /*FAST_IPSEC*/
118 #ifdef notyet
119 extern struct mbuf *m_copypack();
120 #endif
122 int path_mtu_discovery = 1;
123 SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_RW,
124 &path_mtu_discovery, 1, "Enable Path MTU Discovery");
126 static int avoid_pure_win_update = 1;
127 SYSCTL_INT(_net_inet_tcp, OID_AUTO, avoid_pure_win_update, CTLFLAG_RW,
128 &avoid_pure_win_update, 1, "Avoid pure window updates when possible");
131 * 1 - enabled for increasing and decreasing the buffer size
132 * 2 - enabled only for increasing the buffer size
134 int tcp_do_autosndbuf = 1;
135 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto, CTLFLAG_RW,
136 &tcp_do_autosndbuf, 0, "Enable automatic send buffer sizing");
138 int tcp_autosndbuf_inc = 8*1024;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_inc, CTLFLAG_RW,
140 &tcp_autosndbuf_inc, 0, "Incrementor step size of automatic send buffer");
142 int tcp_autosndbuf_min = 32768;
143 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_min, CTLFLAG_RW,
144 &tcp_autosndbuf_min, 0, "Min size of automatic send buffer");
146 int tcp_autosndbuf_max = 2*1024*1024;
147 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_max, CTLFLAG_RW,
148 &tcp_autosndbuf_max, 0, "Max size of automatic send buffer");
150 int tcp_prio_synack = 1;
151 SYSCTL_INT(_net_inet_tcp, OID_AUTO, prio_synack, CTLFLAG_RW,
152 &tcp_prio_synack, 0, "Prioritize SYN, SYN|ACK and pure ACK");
154 static int tcp_idle_cwv = 1;
155 SYSCTL_INT(_net_inet_tcp, OID_AUTO, idle_cwv, CTLFLAG_RW,
156 &tcp_idle_cwv, 0,
157 "Congestion window validation after idle period (part of RFC2861)");
159 static int tcp_idle_restart = 1;
160 SYSCTL_INT(_net_inet_tcp, OID_AUTO, idle_restart, CTLFLAG_RW,
161 &tcp_idle_restart, 0, "Reset congestion window after idle period");
163 static int tcp_do_tso = 1;
164 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tso, CTLFLAG_RW,
165 &tcp_do_tso, 0, "Enable TCP Segmentation Offload (TSO)");
167 static int tcp_fairsend = 4;
168 SYSCTL_INT(_net_inet_tcp, OID_AUTO, fairsend, CTLFLAG_RW,
169 &tcp_fairsend, 0,
170 "Amount of segments sent before yield to other senders or receivers");
172 static void tcp_idle_cwnd_validate(struct tcpcb *);
174 static int tcp_tso_getsize(struct tcpcb *tp, u_int *segsz, u_int *hlen);
175 static void tcp_output_sched(struct tcpcb *tp);
178 * Tcp output routine: figure out what should be sent and send it.
181 tcp_output(struct tcpcb *tp)
183 struct inpcb * const inp = tp->t_inpcb;
184 struct socket *so = inp->inp_socket;
185 long len, recvwin, sendwin;
186 int nsacked = 0;
187 int off, flags, error = 0;
188 #ifdef TCP_SIGNATURE
189 int sigoff = 0;
190 #endif
191 struct mbuf *m;
192 struct ip *ip;
193 struct tcphdr *th;
194 u_char opt[TCP_MAXOLEN];
195 unsigned int ipoptlen, optlen, hdrlen;
196 int idle;
197 boolean_t sendalot;
198 struct ip6_hdr *ip6;
199 #ifdef INET6
200 const boolean_t isipv6 = INP_ISIPV6(inp);
201 #else
202 const boolean_t isipv6 = FALSE;
203 #endif
204 boolean_t can_tso = FALSE, use_tso;
205 boolean_t report_sack, idle_cwv = FALSE;
206 u_int segsz, tso_hlen, tso_lenmax = 0;
207 int segcnt = 0;
208 boolean_t need_sched = FALSE;
210 KKASSERT(so->so_port == &curthread->td_msgport);
213 * Determine length of data that should be transmitted,
214 * and flags that will be used.
215 * If there is some data or critical controls (SYN, RST)
216 * to send, then transmit; otherwise, investigate further.
220 * If we have been idle for a while, the send congestion window
221 * could be no longer representative of the current state of the
222 * link; need to validate congestion window. However, we should
223 * not perform congestion window validation here, since we could
224 * be asked to send pure ACK.
226 if (tp->snd_max == tp->snd_una &&
227 (ticks - tp->snd_last) >= tp->t_rxtcur && tcp_idle_restart)
228 idle_cwv = TRUE;
231 * Calculate whether the transmit stream was previously idle
232 * and adjust TF_LASTIDLE for the next time.
234 idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
235 if (idle && (tp->t_flags & TF_MORETOCOME))
236 tp->t_flags |= TF_LASTIDLE;
237 else
238 tp->t_flags &= ~TF_LASTIDLE;
240 if (TCP_DO_SACK(tp) && tp->snd_nxt != tp->snd_max &&
241 !IN_FASTRECOVERY(tp))
242 nsacked = tcp_sack_bytes_below(&tp->scb, tp->snd_nxt);
245 * Find out whether TSO could be used or not
247 * For TSO capable devices, the following assumptions apply to
248 * the processing of TCP flags:
249 * - If FIN is set on the large TCP segment, the device must set
250 * FIN on the last segment that it creates from the large TCP
251 * segment.
252 * - If PUSH is set on the large TCP segment, the device must set
253 * PUSH on the last segment that it creates from the large TCP
254 * segment.
256 #if !defined(IPSEC) && !defined(FAST_IPSEC)
257 if (tcp_do_tso
258 #ifdef TCP_SIGNATURE
259 && (tp->t_flags & TF_SIGNATURE) == 0
260 #endif
262 if (!isipv6) {
263 struct rtentry *rt = inp->inp_route.ro_rt;
265 if (rt != NULL && (rt->rt_flags & RTF_UP) &&
266 (rt->rt_ifp->if_hwassist & CSUM_TSO)) {
267 can_tso = TRUE;
268 tso_lenmax = rt->rt_ifp->if_tsolen;
272 #endif /* !IPSEC && !FAST_IPSEC */
274 again:
275 m = NULL;
276 ip = NULL;
277 th = NULL;
278 ip6 = NULL;
280 if ((tp->t_flags & (TF_SACK_PERMITTED | TF_NOOPT)) ==
281 TF_SACK_PERMITTED &&
282 (!TAILQ_EMPTY(&tp->t_segq) ||
283 tp->reportblk.rblk_start != tp->reportblk.rblk_end))
284 report_sack = TRUE;
285 else
286 report_sack = FALSE;
288 /* Make use of SACK information when slow-starting after a RTO. */
289 if (TCP_DO_SACK(tp) && tp->snd_nxt != tp->snd_max &&
290 !IN_FASTRECOVERY(tp)) {
291 tcp_seq old_snd_nxt = tp->snd_nxt;
293 tcp_sack_skip_sacked(&tp->scb, &tp->snd_nxt);
294 nsacked += tp->snd_nxt - old_snd_nxt;
297 sendalot = FALSE;
298 off = tp->snd_nxt - tp->snd_una;
299 sendwin = min(tp->snd_wnd, tp->snd_cwnd + nsacked);
300 sendwin = min(sendwin, tp->snd_bwnd);
302 flags = tcp_outflags[tp->t_state];
304 * Get standard flags, and add SYN or FIN if requested by 'hidden'
305 * state flags.
307 if (tp->t_flags & TF_NEEDFIN)
308 flags |= TH_FIN;
309 if (tp->t_flags & TF_NEEDSYN)
310 flags |= TH_SYN;
313 * If in persist timeout with window of 0, send 1 byte.
314 * Otherwise, if window is small but nonzero
315 * and timer expired, we will send what we can
316 * and go to transmit state.
318 if (tp->t_flags & TF_FORCE) {
319 if (sendwin == 0) {
321 * If we still have some data to send, then
322 * clear the FIN bit. Usually this would
323 * happen below when it realizes that we
324 * aren't sending all the data. However,
325 * if we have exactly 1 byte of unsent data,
326 * then it won't clear the FIN bit below,
327 * and if we are in persist state, we wind
328 * up sending the packet without recording
329 * that we sent the FIN bit.
331 * We can't just blindly clear the FIN bit,
332 * because if we don't have any more data
333 * to send then the probe will be the FIN
334 * itself.
336 if (off < so->so_snd.ssb_cc)
337 flags &= ~TH_FIN;
338 sendwin = 1;
339 } else {
340 tcp_callout_stop(tp, tp->tt_persist);
341 tp->t_rxtshift = 0;
346 * If snd_nxt == snd_max and we have transmitted a FIN, the
347 * offset will be > 0 even if so_snd.ssb_cc is 0, resulting in
348 * a negative length. This can also occur when TCP opens up
349 * its congestion window while receiving additional duplicate
350 * acks after fast-retransmit because TCP will reset snd_nxt
351 * to snd_max after the fast-retransmit.
353 * A negative length can also occur when we are in the
354 * TCPS_SYN_RECEIVED state due to a simultanious connect where
355 * our SYN has not been acked yet.
357 * In the normal retransmit-FIN-only case, however, snd_nxt will
358 * be set to snd_una, the offset will be 0, and the length may
359 * wind up 0.
361 len = (long)ulmin(so->so_snd.ssb_cc, sendwin) - off;
364 * Lop off SYN bit if it has already been sent. However, if this
365 * is SYN-SENT state and if segment contains data, suppress sending
366 * segment (sending the segment would be an option if we still
367 * did TAO and the remote host supported it).
369 if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
370 flags &= ~TH_SYN;
371 off--, len++;
372 if (len > 0 && tp->t_state == TCPS_SYN_SENT) {
373 tp->t_flags &= ~(TF_ACKNOW | TF_XMITNOW);
374 return 0;
379 * Be careful not to send data and/or FIN on SYN segments.
380 * This measure is needed to prevent interoperability problems
381 * with not fully conformant TCP implementations.
383 if (flags & TH_SYN) {
384 len = 0;
385 flags &= ~TH_FIN;
388 if (len < 0) {
390 * A negative len can occur if our FIN has been sent but not
391 * acked, or if we are in a simultanious connect in the
392 * TCPS_SYN_RECEIVED state with our SYN sent but not yet
393 * acked.
395 * If our window has contracted to 0 in the FIN case
396 * (which can only occur if we have NOT been called to
397 * retransmit as per code a few paragraphs up) then we
398 * want to shift the retransmit timer over to the
399 * persist timer.
401 * However, if we are in the TCPS_SYN_RECEIVED state
402 * (the SYN case) we will be in a simultanious connect and
403 * the window may be zero degeneratively. In this case we
404 * do not want to shift to the persist timer after the SYN
405 * or the SYN+ACK transmission.
407 len = 0;
408 if (sendwin == 0 && tp->t_state != TCPS_SYN_RECEIVED) {
409 tcp_callout_stop(tp, tp->tt_rexmt);
410 tp->t_rxtshift = 0;
411 tp->snd_nxt = tp->snd_una;
412 if (!tcp_callout_active(tp, tp->tt_persist))
413 tcp_setpersist(tp);
417 KASSERT(len >= 0, ("%s: len < 0", __func__));
419 * Automatic sizing of send socket buffer. Often the send buffer
420 * size is not optimally adjusted to the actual network conditions
421 * at hand (delay bandwidth product). Setting the buffer size too
422 * small limits throughput on links with high bandwidth and high
423 * delay (eg. trans-continental/oceanic links). Setting the
424 * buffer size too big consumes too much real kernel memory,
425 * especially with many connections on busy servers.
427 * The criteria to step up the send buffer one notch are:
428 * 1. receive window of remote host is larger than send buffer
429 * (with a fudge factor of 5/4th);
430 * 2. hiwat has not significantly exceeded bwnd (inflight)
431 * (bwnd is a maximal value if inflight is disabled).
432 * 3. send buffer is filled to 7/8th with data (so we actually
433 * have data to make use of it);
434 * 4. hiwat has not hit maximal automatic size;
435 * 5. our send window (slow start and cogestion controlled) is
436 * larger than sent but unacknowledged data in send buffer.
438 * The remote host receive window scaling factor may limit the
439 * growing of the send buffer before it reaches its allowed
440 * maximum.
442 * It scales directly with slow start or congestion window
443 * and does at most one step per received ACK. This fast
444 * scaling has the drawback of growing the send buffer beyond
445 * what is strictly necessary to make full use of a given
446 * delay*bandwith product. However testing has shown this not
447 * to be much of an problem. At worst we are trading wasting
448 * of available bandwith (the non-use of it) for wasting some
449 * socket buffer memory.
451 * The criteria for shrinking the buffer is based solely on
452 * the inflight code (snd_bwnd). If inflight is disabled,
453 * the buffer will not be shrinked. Note that snd_bwnd already
454 * has a fudge factor. Our test adds a little hysteresis.
456 if (tcp_do_autosndbuf && (so->so_snd.ssb_flags & SSB_AUTOSIZE)) {
457 const int asbinc = tcp_autosndbuf_inc;
458 const int hiwat = so->so_snd.ssb_hiwat;
459 const int lowat = so->so_snd.ssb_lowat;
460 u_long newsize;
462 if ((tp->snd_wnd / 4 * 5) >= hiwat &&
463 so->so_snd.ssb_cc >= (hiwat / 8 * 7) &&
464 hiwat < tp->snd_bwnd + hiwat / 10 &&
465 hiwat + asbinc < tcp_autosndbuf_max &&
466 hiwat < (TCP_MAXWIN << tp->snd_scale) &&
467 sendwin >= (so->so_snd.ssb_cc -
468 (tp->snd_nxt - tp->snd_una))) {
469 newsize = ulmin(hiwat + asbinc, tcp_autosndbuf_max);
470 if (!ssb_reserve(&so->so_snd, newsize, so, NULL))
471 atomic_clear_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE);
472 #if 0
473 if (newsize >= (TCP_MAXWIN << tp->snd_scale))
474 atomic_clear_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE);
475 #endif
476 } else if ((long)tp->snd_bwnd <
477 (long)(hiwat * 3 / 4 - lowat - asbinc) &&
478 hiwat > tp->t_maxseg * 2 + asbinc &&
479 hiwat + asbinc >= tcp_autosndbuf_min &&
480 tcp_do_autosndbuf == 1) {
481 newsize = ulmax(hiwat - asbinc, tp->t_maxseg * 2);
482 ssb_reserve(&so->so_snd, newsize, so, NULL);
487 * Don't use TSO, if:
488 * - Congestion window needs validation
489 * - There are SACK blocks to report
490 * - RST or SYN flags is set
491 * - URG will be set
493 * XXX
494 * Checking for SYN|RST looks overkill, just to be safe than sorry
496 use_tso = can_tso;
497 if (report_sack || idle_cwv || (flags & (TH_RST | TH_SYN)))
498 use_tso = FALSE;
499 if (use_tso) {
500 tcp_seq ugr_nxt = tp->snd_nxt;
502 if ((flags & TH_FIN) && (tp->t_flags & TF_SENTFIN) &&
503 tp->snd_nxt == tp->snd_max)
504 --ugr_nxt;
506 if (SEQ_GT(tp->snd_up, ugr_nxt))
507 use_tso = FALSE;
510 if (use_tso) {
512 * Find out segment size and header length for TSO
514 error = tcp_tso_getsize(tp, &segsz, &tso_hlen);
515 if (error)
516 use_tso = FALSE;
518 if (!use_tso) {
519 segsz = tp->t_maxseg;
520 tso_hlen = 0; /* not used */
524 * Truncate to the maximum segment length if not TSO, and ensure that
525 * FIN is removed if the length no longer contains the last data byte.
527 if (len > segsz) {
528 if (!use_tso) {
529 len = segsz;
530 ++segcnt;
531 } else {
532 int nsegs;
534 if (__predict_false(tso_lenmax < segsz))
535 tso_lenmax = segsz << 1;
538 * Truncate TSO transfers to (IP_MAXPACKET - iphlen -
539 * thoff), and make sure that we send equal size
540 * transfers down the stack (rather than big-small-
541 * big-small-...).
543 len = min(len, tso_lenmax);
544 nsegs = min(len, (IP_MAXPACKET - tso_hlen)) / segsz;
545 KKASSERT(nsegs > 0);
547 len = nsegs * segsz;
549 if (len <= segsz) {
550 use_tso = FALSE;
551 ++segcnt;
552 } else {
553 segcnt += nsegs;
556 sendalot = TRUE;
557 } else {
558 use_tso = FALSE;
559 if (len > 0)
560 ++segcnt;
562 if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.ssb_cc))
563 flags &= ~TH_FIN;
565 recvwin = ssb_space(&so->so_rcv);
568 * Sender silly window avoidance. We transmit under the following
569 * conditions when len is non-zero:
571 * - We have a full segment
572 * - This is the last buffer in a write()/send() and we are
573 * either idle or running NODELAY
574 * - we've timed out (e.g. persist timer)
575 * - we have more then 1/2 the maximum send window's worth of
576 * data (receiver may be limiting the window size)
577 * - we need to retransmit
579 if (len) {
580 if (len >= segsz)
581 goto send;
583 * NOTE! on localhost connections an 'ack' from the remote
584 * end may occur synchronously with the output and cause
585 * us to flush a buffer queued with moretocome. XXX
587 * note: the len + off check is almost certainly unnecessary.
589 if (!(tp->t_flags & TF_MORETOCOME) && /* normal case */
590 (idle || (tp->t_flags & TF_NODELAY)) &&
591 len + off >= so->so_snd.ssb_cc &&
592 !(tp->t_flags & TF_NOPUSH)) {
593 goto send;
595 if (tp->t_flags & TF_FORCE) /* typ. timeout case */
596 goto send;
597 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
598 goto send;
599 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) /* retransmit case */
600 goto send;
601 if (tp->t_flags & TF_XMITNOW)
602 goto send;
606 * Compare available window to amount of window
607 * known to peer (as advertised window less
608 * next expected input). If the difference is at least two
609 * max size segments, or at least 50% of the maximum possible
610 * window, then want to send a window update to peer.
612 if (recvwin > 0) {
614 * "adv" is the amount we can increase the window,
615 * taking into account that we are limited by
616 * TCP_MAXWIN << tp->rcv_scale.
618 long adv = min(recvwin, (long)TCP_MAXWIN << tp->rcv_scale) -
619 (tp->rcv_adv - tp->rcv_nxt);
620 long hiwat;
623 * This ack case typically occurs when the user has drained
624 * the TCP socket buffer sufficiently to warrent an ack
625 * containing a 'pure window update'... that is, an ack that
626 * ONLY updates the tcp window.
628 * It is unclear why we would need to do a pure window update
629 * past 2 segments if we are going to do one at 1/2 the high
630 * water mark anyway, especially since under normal conditions
631 * the user program will drain the socket buffer quickly.
632 * The 2-segment pure window update will often add a large
633 * number of extra, unnecessary acks to the stream.
635 * avoid_pure_win_update now defaults to 1.
637 if (avoid_pure_win_update == 0 ||
638 (tp->t_flags & TF_RXRESIZED)) {
639 if (adv >= (long) (2 * segsz)) {
640 goto send;
643 hiwat = (long)(TCP_MAXWIN << tp->rcv_scale);
644 if (hiwat > (long)so->so_rcv.ssb_hiwat)
645 hiwat = (long)so->so_rcv.ssb_hiwat;
646 if (adv >= hiwat / 2)
647 goto send;
651 * Send if we owe the peer an ACK, RST, SYN, or urgent data. ACKNOW
652 * is also a catch-all for the retransmit timer timeout case.
654 if (tp->t_flags & TF_ACKNOW)
655 goto send;
656 if ((flags & TH_RST) ||
657 ((flags & TH_SYN) && !(tp->t_flags & TF_NEEDSYN)))
658 goto send;
659 if (SEQ_GT(tp->snd_up, tp->snd_una))
660 goto send;
662 * If our state indicates that FIN should be sent
663 * and we have not yet done so, then we need to send.
665 if ((flags & TH_FIN) &&
666 (!(tp->t_flags & TF_SENTFIN) || tp->snd_nxt == tp->snd_una))
667 goto send;
670 * TCP window updates are not reliable, rather a polling protocol
671 * using ``persist'' packets is used to insure receipt of window
672 * updates. The three ``states'' for the output side are:
673 * idle not doing retransmits or persists
674 * persisting to move a small or zero window
675 * (re)transmitting and thereby not persisting
677 * tcp_callout_active(tp, tp->tt_persist)
678 * is true when we are in persist state.
679 * The TF_FORCE flag in tp->t_flags
680 * is set when we are called to send a persist packet.
681 * tcp_callout_active(tp, tp->tt_rexmt)
682 * is set when we are retransmitting
683 * The output side is idle when both timers are zero.
685 * If send window is too small, there is data to transmit, and no
686 * retransmit or persist is pending, then go to persist state.
688 * If nothing happens soon, send when timer expires:
689 * if window is nonzero, transmit what we can, otherwise force out
690 * a byte.
692 * Don't try to set the persist state if we are in TCPS_SYN_RECEIVED
693 * with data pending. This situation can occur during a
694 * simultanious connect.
696 if (so->so_snd.ssb_cc > 0 &&
697 tp->t_state != TCPS_SYN_RECEIVED &&
698 !tcp_callout_active(tp, tp->tt_rexmt) &&
699 !tcp_callout_active(tp, tp->tt_persist)) {
700 tp->t_rxtshift = 0;
701 tcp_setpersist(tp);
705 * No reason to send a segment, just return.
707 tp->t_flags &= ~TF_XMITNOW;
708 return (0);
710 send:
711 if (need_sched && len > 0) {
712 tcp_output_sched(tp);
713 return 0;
717 * Before ESTABLISHED, force sending of initial options
718 * unless TCP set not to do any options.
719 * NOTE: we assume that the IP/TCP header plus TCP options
720 * always fit in a single mbuf, leaving room for a maximum
721 * link header, i.e.
722 * max_linkhdr + sizeof(struct tcpiphdr) + optlen <= MCLBYTES
724 optlen = 0;
725 if (isipv6)
726 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
727 else
728 hdrlen = sizeof(struct tcpiphdr);
729 if (flags & TH_SYN) {
730 tp->snd_nxt = tp->iss;
731 if (!(tp->t_flags & TF_NOOPT)) {
732 u_short mss;
734 opt[0] = TCPOPT_MAXSEG;
735 opt[1] = TCPOLEN_MAXSEG;
736 mss = htons((u_short) tcp_mssopt(tp));
737 memcpy(opt + 2, &mss, sizeof mss);
738 optlen = TCPOLEN_MAXSEG;
740 if ((tp->t_flags & TF_REQ_SCALE) &&
741 (!(flags & TH_ACK) ||
742 (tp->t_flags & TF_RCVD_SCALE))) {
743 *((u_int32_t *)(opt + optlen)) = htonl(
744 TCPOPT_NOP << 24 |
745 TCPOPT_WINDOW << 16 |
746 TCPOLEN_WINDOW << 8 |
747 tp->request_r_scale);
748 optlen += 4;
751 if ((tcp_do_sack && !(flags & TH_ACK)) ||
752 tp->t_flags & TF_SACK_PERMITTED) {
753 uint32_t *lp = (uint32_t *)(opt + optlen);
755 *lp = htonl(TCPOPT_SACK_PERMITTED_ALIGNED);
756 optlen += TCPOLEN_SACK_PERMITTED_ALIGNED;
762 * Send a timestamp and echo-reply if this is a SYN and our side
763 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
764 * and our peer have sent timestamps in our SYN's.
766 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
767 !(flags & TH_RST) &&
768 (!(flags & TH_ACK) || (tp->t_flags & TF_RCVD_TSTMP))) {
769 u_int32_t *lp = (u_int32_t *)(opt + optlen);
771 /* Form timestamp option as shown in appendix A of RFC 1323. */
772 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
773 *lp++ = htonl(ticks);
774 *lp = htonl(tp->ts_recent);
775 optlen += TCPOLEN_TSTAMP_APPA;
778 /* Set receive buffer autosizing timestamp. */
779 if (tp->rfbuf_ts == 0 && (so->so_rcv.ssb_flags & SSB_AUTOSIZE))
780 tp->rfbuf_ts = ticks;
783 * If this is a SACK connection and we have a block to report,
784 * fill in the SACK blocks in the TCP options.
786 if (report_sack)
787 tcp_sack_fill_report(tp, opt, &optlen);
789 #ifdef TCP_SIGNATURE
790 if (tp->t_flags & TF_SIGNATURE) {
791 int i;
792 u_char *bp;
794 * Initialize TCP-MD5 option (RFC2385)
796 bp = (u_char *)opt + optlen;
797 *bp++ = TCPOPT_SIGNATURE;
798 *bp++ = TCPOLEN_SIGNATURE;
799 sigoff = optlen + 2;
800 for (i = 0; i < TCP_SIGLEN; i++)
801 *bp++ = 0;
802 optlen += TCPOLEN_SIGNATURE;
804 * Terminate options list and maintain 32-bit alignment.
806 *bp++ = TCPOPT_NOP;
807 *bp++ = TCPOPT_EOL;
808 optlen += 2;
810 #endif /* TCP_SIGNATURE */
811 KASSERT(optlen <= TCP_MAXOLEN, ("too many TCP options"));
812 hdrlen += optlen;
814 if (isipv6) {
815 ipoptlen = ip6_optlen(inp);
816 } else {
817 if (inp->inp_options) {
818 ipoptlen = inp->inp_options->m_len -
819 offsetof(struct ipoption, ipopt_list);
820 } else {
821 ipoptlen = 0;
824 #ifdef IPSEC
825 ipoptlen += ipsec_hdrsiz_tcp(tp);
826 #endif
828 if (use_tso) {
829 /* TSO segment length must be multiple of segment size */
830 KASSERT(len >= (2 * segsz) && (len % segsz == 0),
831 ("invalid TSO len %ld, segsz %u", len, segsz));
832 } else {
833 KASSERT(len <= segsz,
834 ("invalid len %ld, segsz %u", len, segsz));
837 * Adjust data length if insertion of options will bump
838 * the packet length beyond the t_maxopd length. Clear
839 * FIN to prevent premature closure since there is still
840 * more data to send after this (now truncated) packet.
842 * If just the options do not fit we are in a no-win
843 * situation and we treat it as an unreachable host.
845 if (len + optlen + ipoptlen > tp->t_maxopd) {
846 if (tp->t_maxopd <= optlen + ipoptlen) {
847 static time_t last_optlen_report;
849 if (last_optlen_report != time_uptime) {
850 last_optlen_report = time_uptime;
851 kprintf("tcpcb %p: MSS (%d) too "
852 "small to hold options!\n",
853 tp, tp->t_maxopd);
855 error = EHOSTUNREACH;
856 goto out;
857 } else {
858 flags &= ~TH_FIN;
859 len = tp->t_maxopd - optlen - ipoptlen;
860 sendalot = TRUE;
865 #ifdef INET6
866 KASSERT(max_linkhdr + hdrlen <= MCLBYTES, ("tcphdr too big"));
867 #else
868 KASSERT(max_linkhdr + hdrlen <= MHLEN, ("tcphdr too big"));
869 #endif
872 * Grab a header mbuf, attaching a copy of data to
873 * be transmitted, and initialize the header from
874 * the template for sends on this connection.
876 if (len) {
877 if ((tp->t_flags & TF_FORCE) && len == 1)
878 tcpstat.tcps_sndprobe++;
879 else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
880 if (tp->snd_nxt == tp->snd_una)
881 tp->snd_max_rexmt = tp->snd_max;
882 if (nsacked) {
883 tcpstat.tcps_sndsackrtopack++;
884 tcpstat.tcps_sndsackrtobyte += len;
886 tcpstat.tcps_sndrexmitpack++;
887 tcpstat.tcps_sndrexmitbyte += len;
888 } else {
889 tcpstat.tcps_sndpack++;
890 tcpstat.tcps_sndbyte += len;
892 if (idle_cwv) {
893 idle_cwv = FALSE;
894 tcp_idle_cwnd_validate(tp);
896 /* Update last send time after CWV */
897 tp->snd_last = ticks;
898 #ifdef notyet
899 if ((m = m_copypack(so->so_snd.ssb_mb, off, (int)len,
900 max_linkhdr + hdrlen)) == NULL) {
901 error = ENOBUFS;
902 goto after_th;
905 * m_copypack left space for our hdr; use it.
907 m->m_len += hdrlen;
908 m->m_data -= hdrlen;
909 #else
910 #ifndef INET6
911 m = m_gethdr(M_NOWAIT, MT_HEADER);
912 #else
913 m = m_getl(hdrlen + max_linkhdr, M_NOWAIT, MT_HEADER,
914 M_PKTHDR, NULL);
915 #endif
916 if (m == NULL) {
917 error = ENOBUFS;
918 goto after_th;
920 m->m_data += max_linkhdr;
921 m->m_len = hdrlen;
922 if (len <= MHLEN - hdrlen - max_linkhdr) {
923 m_copydata(so->so_snd.ssb_mb, off, (int) len,
924 mtod(m, caddr_t) + hdrlen);
925 m->m_len += len;
926 } else {
927 m->m_next = m_copy(so->so_snd.ssb_mb, off, (int) len);
928 if (m->m_next == NULL) {
929 m_free(m);
930 m = NULL;
931 error = ENOBUFS;
932 goto after_th;
935 #endif
937 * If we're sending everything we've got, set PUSH.
938 * (This will keep happy those implementations which only
939 * give data to the user when a buffer fills or
940 * a PUSH comes in.)
942 if (off + len == so->so_snd.ssb_cc)
943 flags |= TH_PUSH;
944 } else {
945 if (tp->t_flags & TF_ACKNOW)
946 tcpstat.tcps_sndacks++;
947 else if (flags & (TH_SYN | TH_FIN | TH_RST))
948 tcpstat.tcps_sndctrl++;
949 else if (SEQ_GT(tp->snd_up, tp->snd_una))
950 tcpstat.tcps_sndurg++;
951 else
952 tcpstat.tcps_sndwinup++;
954 MGETHDR(m, M_NOWAIT, MT_HEADER);
955 if (m == NULL) {
956 error = ENOBUFS;
957 goto after_th;
959 if (isipv6 &&
960 (hdrlen + max_linkhdr > MHLEN) && hdrlen <= MHLEN)
961 MH_ALIGN(m, hdrlen);
962 else
963 m->m_data += max_linkhdr;
964 m->m_len = hdrlen;
967 * Prioritize SYN, SYN|ACK and pure ACK.
968 * Leave FIN and RST as they are.
970 if (tcp_prio_synack && (flags & (TH_FIN | TH_RST)) == 0)
971 m->m_flags |= M_PRIO;
973 m->m_pkthdr.rcvif = NULL;
974 if (isipv6) {
975 ip6 = mtod(m, struct ip6_hdr *);
976 th = (struct tcphdr *)(ip6 + 1);
977 tcp_fillheaders(tp, ip6, th, use_tso);
978 } else {
979 ip = mtod(m, struct ip *);
980 th = (struct tcphdr *)(ip + 1);
981 /* this picks up the pseudo header (w/o the length) */
982 tcp_fillheaders(tp, ip, th, use_tso);
984 after_th:
986 * Fill in fields, remembering maximum advertised
987 * window for use in delaying messages about window sizes.
988 * If resending a FIN, be sure not to use a new sequence number.
990 if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
991 tp->snd_nxt == tp->snd_max)
992 tp->snd_nxt--;
994 if (th != NULL) {
996 * If we are doing retransmissions, then snd_nxt will
997 * not reflect the first unsent octet. For ACK only
998 * packets, we do not want the sequence number of the
999 * retransmitted packet, we want the sequence number
1000 * of the next unsent octet. So, if there is no data
1001 * (and no SYN or FIN), use snd_max instead of snd_nxt
1002 * when filling in ti_seq. But if we are in persist
1003 * state, snd_max might reflect one byte beyond the
1004 * right edge of the window, so use snd_nxt in that
1005 * case, since we know we aren't doing a retransmission.
1006 * (retransmit and persist are mutually exclusive...)
1008 if (len || (flags & (TH_SYN|TH_FIN)) ||
1009 tcp_callout_active(tp, tp->tt_persist))
1010 th->th_seq = htonl(tp->snd_nxt);
1011 else
1012 th->th_seq = htonl(tp->snd_max);
1013 th->th_ack = htonl(tp->rcv_nxt);
1014 if (optlen) {
1015 bcopy(opt, th + 1, optlen);
1016 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1018 th->th_flags = flags;
1022 * Calculate receive window. Don't shrink window, but avoid
1023 * silly window syndrome by sending a 0 window if the actual
1024 * window is less then one segment.
1026 if (recvwin < (long)(so->so_rcv.ssb_hiwat / 4) &&
1027 recvwin < (long)segsz)
1028 recvwin = 0;
1029 if (recvwin < (tcp_seq_diff_t)(tp->rcv_adv - tp->rcv_nxt))
1030 recvwin = (tcp_seq_diff_t)(tp->rcv_adv - tp->rcv_nxt);
1031 if (recvwin > (long)TCP_MAXWIN << tp->rcv_scale)
1032 recvwin = (long)TCP_MAXWIN << tp->rcv_scale;
1035 * Adjust the RXWIN0SENT flag - indicate that we have advertised
1036 * a 0 window. This may cause the remote transmitter to stall. This
1037 * flag tells soreceive() to disable delayed acknowledgements when
1038 * draining the buffer. This can occur if the receiver is attempting
1039 * to read more data then can be buffered prior to transmitting on
1040 * the connection.
1042 if (recvwin == 0)
1043 tp->t_flags |= TF_RXWIN0SENT;
1044 else
1045 tp->t_flags &= ~TF_RXWIN0SENT;
1047 if (th != NULL)
1048 th->th_win = htons((u_short) (recvwin>>tp->rcv_scale));
1050 if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1051 KASSERT(!use_tso, ("URG with TSO"));
1052 if (th != NULL) {
1053 th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
1054 th->th_flags |= TH_URG;
1056 } else {
1058 * If no urgent pointer to send, then we pull
1059 * the urgent pointer to the left edge of the send window
1060 * so that it doesn't drift into the send window on sequence
1061 * number wraparound.
1063 tp->snd_up = tp->snd_una; /* drag it along */
1066 if (th != NULL) {
1067 #ifdef TCP_SIGNATURE
1068 if (tp->t_flags & TF_SIGNATURE) {
1069 tcpsignature_compute(m, len, optlen,
1070 (u_char *)(th + 1) + sigoff, IPSEC_DIR_OUTBOUND);
1072 #endif /* TCP_SIGNATURE */
1075 * Put TCP length in extended header, and then
1076 * checksum extended header and data.
1078 m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
1079 if (isipv6) {
1081 * ip6_plen is not need to be filled now, and will be
1082 * filled in ip6_output().
1084 th->th_sum = in6_cksum(m, IPPROTO_TCP,
1085 sizeof(struct ip6_hdr),
1086 sizeof(struct tcphdr) + optlen + len);
1087 } else {
1088 m->m_pkthdr.csum_thlen = sizeof(struct tcphdr) + optlen;
1089 if (use_tso) {
1090 m->m_pkthdr.csum_flags = CSUM_TSO;
1091 m->m_pkthdr.tso_segsz = segsz;
1092 } else {
1093 m->m_pkthdr.csum_flags = CSUM_TCP;
1094 m->m_pkthdr.csum_data =
1095 offsetof(struct tcphdr, th_sum);
1096 if (len + optlen) {
1097 th->th_sum = in_addword(th->th_sum,
1098 htons((u_short)(optlen + len)));
1103 * IP version must be set here for ipv4/ipv6 checking
1104 * later
1106 KASSERT(ip->ip_v == IPVERSION,
1107 ("%s: IP version incorrect: %d",
1108 __func__, ip->ip_v));
1113 * In transmit state, time the transmission and arrange for
1114 * the retransmit. In persist state, just set snd_max.
1116 if (!(tp->t_flags & TF_FORCE) ||
1117 !tcp_callout_active(tp, tp->tt_persist)) {
1118 tcp_seq startseq = tp->snd_nxt;
1121 * Advance snd_nxt over sequence space of this segment.
1123 if (flags & (TH_SYN | TH_FIN)) {
1124 if (flags & TH_SYN)
1125 tp->snd_nxt++;
1126 if (flags & TH_FIN) {
1127 tp->snd_nxt++;
1128 tp->t_flags |= TF_SENTFIN;
1131 tp->snd_nxt += len;
1132 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
1133 tp->snd_max = tp->snd_nxt;
1135 * Time this transmission if not a retransmission and
1136 * not currently timing anything.
1138 if (tp->t_rtttime == 0) {
1139 tp->t_rtttime = ticks;
1140 tp->t_rtseq = startseq;
1141 tcpstat.tcps_segstimed++;
1146 * Set retransmit timer if not currently set,
1147 * and not doing a pure ack or a keep-alive probe.
1148 * Initial value for retransmit timer is smoothed
1149 * round-trip time + 2 * round-trip time variance.
1150 * Initialize shift counter which is used for backoff
1151 * of retransmit time.
1153 if (!tcp_callout_active(tp, tp->tt_rexmt) &&
1154 tp->snd_nxt != tp->snd_una) {
1155 if (tcp_callout_active(tp, tp->tt_persist)) {
1156 tcp_callout_stop(tp, tp->tt_persist);
1157 tp->t_rxtshift = 0;
1159 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
1160 tcp_timer_rexmt);
1161 } else if (len == 0 && so->so_snd.ssb_cc &&
1162 tp->t_state > TCPS_SYN_RECEIVED &&
1163 !tcp_callout_active(tp, tp->tt_rexmt) &&
1164 !tcp_callout_active(tp, tp->tt_persist)) {
1166 * Avoid a situation where we do not set persist timer
1167 * after a zero window condition. For example:
1168 * 1) A -> B: packet with enough data to fill the window
1169 * 2) B -> A: ACK for #1 + new data (0 window
1170 * advertisement)
1171 * 3) A -> B: ACK for #2, 0 len packet
1173 * In this case, A will not activate the persist timer,
1174 * because it chose to send a packet. Unless tcp_output
1175 * is called for some other reason (delayed ack timer,
1176 * another input packet from B, socket syscall), A will
1177 * not send zero window probes.
1179 * So, if you send a 0-length packet, but there is data
1180 * in the socket buffer, and neither the rexmt or
1181 * persist timer is already set, then activate the
1182 * persist timer.
1184 tp->t_rxtshift = 0;
1185 tcp_setpersist(tp);
1187 } else {
1189 * Persist case, update snd_max but since we are in
1190 * persist mode (no window) we do not update snd_nxt.
1192 int xlen = len;
1193 if (flags & TH_SYN)
1194 panic("tcp_output: persist timer to send SYN");
1195 if (flags & TH_FIN) {
1196 ++xlen;
1197 tp->t_flags |= TF_SENTFIN;
1199 if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
1200 tp->snd_max = tp->snd_nxt + xlen;
1203 if (th != NULL) {
1204 #ifdef TCPDEBUG
1205 /* Trace. */
1206 if (so->so_options & SO_DEBUG) {
1207 tcp_trace(TA_OUTPUT, tp->t_state, tp,
1208 mtod(m, void *), th, 0);
1210 #endif
1213 * Fill in IP length and desired time to live and
1214 * send to IP level. There should be a better way
1215 * to handle ttl and tos; we could keep them in
1216 * the template, but need a way to checksum without them.
1219 * m->m_pkthdr.len should have been set before cksum
1220 * calcuration, because in6_cksum() need it.
1222 if (isipv6) {
1224 * we separately set hoplimit for every segment,
1225 * since the user might want to change the value
1226 * via setsockopt. Also, desired default hop
1227 * limit might be changed via Neighbor Discovery.
1229 ip6->ip6_hlim = in6_selecthlim(inp,
1230 (inp->in6p_route.ro_rt ?
1231 inp->in6p_route.ro_rt->rt_ifp : NULL));
1233 /* TODO: IPv6 IP6TOS_ECT bit on */
1234 error = ip6_output(m, inp->in6p_outputopts,
1235 &inp->in6p_route, (so->so_options & SO_DONTROUTE),
1236 NULL, NULL, inp);
1237 } else {
1238 struct rtentry *rt;
1240 KASSERT(!INP_CHECK_SOCKAF(so, AF_INET6), ("inet6 pcb"));
1242 ip->ip_len = m->m_pkthdr.len;
1243 ip->ip_ttl = inp->inp_ip_ttl; /* XXX */
1244 ip->ip_tos = inp->inp_ip_tos; /* XXX */
1246 * See if we should do MTU discovery.
1247 * We do it only if the following are true:
1248 * 1) we have a valid route to the destination
1249 * 2) the MTU is not locked (if it is,
1250 * then discovery has been disabled)
1252 if (path_mtu_discovery &&
1253 (rt = inp->inp_route.ro_rt) &&
1254 (rt->rt_flags & RTF_UP) &&
1255 !(rt->rt_rmx.rmx_locks & RTV_MTU))
1256 ip->ip_off |= IP_DF;
1258 error = ip_output(m, inp->inp_options, &inp->inp_route,
1259 (so->so_options & SO_DONTROUTE) |
1260 IP_DEBUGROUTE, NULL, inp);
1262 } else {
1263 KASSERT(error != 0, ("no error, but th not set"));
1265 if (error) {
1266 tp->t_flags &= ~(TF_ACKNOW | TF_XMITNOW);
1269 * We know that the packet was lost, so back out the
1270 * sequence number advance, if any.
1272 if (!(tp->t_flags & TF_FORCE) ||
1273 !tcp_callout_active(tp, tp->tt_persist)) {
1275 * No need to check for TH_FIN here because
1276 * the TF_SENTFIN flag handles that case.
1278 if (!(flags & TH_SYN))
1279 tp->snd_nxt -= len;
1282 out:
1283 if (error == ENOBUFS) {
1284 KASSERT((len == 0 && (flags & (TH_SYN | TH_FIN)) == 0) ||
1285 tcp_callout_active(tp, tp->tt_rexmt) ||
1286 tcp_callout_active(tp, tp->tt_persist),
1287 ("neither rexmt nor persist timer is set"));
1288 return (0);
1290 if (error == EMSGSIZE) {
1292 * ip_output() will have already fixed the route
1293 * for us. tcp_mtudisc() will, as its last action,
1294 * initiate retransmission, so it is important to
1295 * not do so here.
1297 tcp_mtudisc(inp, 0);
1298 return 0;
1300 if ((error == EHOSTUNREACH || error == ENETDOWN) &&
1301 TCPS_HAVERCVDSYN(tp->t_state)) {
1302 tp->t_softerror = error;
1303 return (0);
1305 return (error);
1307 tcpstat.tcps_sndtotal++;
1310 * Data sent (as far as we can tell).
1312 * If this advertises a larger window than any other segment,
1313 * then remember the size of the advertised window.
1315 * Any pending ACK has now been sent.
1317 if (recvwin > 0 && SEQ_GT(tp->rcv_nxt + recvwin, tp->rcv_adv)) {
1318 tp->rcv_adv = tp->rcv_nxt + recvwin;
1319 tp->t_flags &= ~TF_RXRESIZED;
1321 tp->last_ack_sent = tp->rcv_nxt;
1322 tp->t_flags &= ~(TF_ACKNOW | TF_XMITNOW);
1323 if (tcp_delack_enabled)
1324 tcp_callout_stop(tp, tp->tt_delack);
1325 if (sendalot) {
1326 if (tcp_fairsend > 0 && (tp->t_flags & TF_FAIRSEND) &&
1327 segcnt >= tcp_fairsend)
1328 need_sched = TRUE;
1329 goto again;
1331 return (0);
1334 void
1335 tcp_setpersist(struct tcpcb *tp)
1337 int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
1338 int tt;
1340 if (tp->t_state == TCPS_SYN_SENT ||
1341 tp->t_state == TCPS_SYN_RECEIVED) {
1342 panic("tcp_setpersist: not established yet, current %s",
1343 tp->t_state == TCPS_SYN_SENT ?
1344 "SYN_SENT" : "SYN_RECEIVED");
1347 if (tcp_callout_active(tp, tp->tt_rexmt))
1348 panic("tcp_setpersist: retransmit pending");
1350 * Start/restart persistance timer.
1352 TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift], TCPTV_PERSMIN,
1353 TCPTV_PERSMAX);
1354 tcp_callout_reset(tp, tp->tt_persist, tt, tcp_timer_persist);
1355 if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1356 tp->t_rxtshift++;
1359 static void
1360 tcp_idle_cwnd_validate(struct tcpcb *tp)
1362 u_long initial_cwnd = tcp_initial_window(tp);
1363 u_long min_cwnd;
1365 tcpstat.tcps_sndidle++;
1367 /* According to RFC5681: RW=min(IW,cwnd) */
1368 min_cwnd = min(tp->snd_cwnd, initial_cwnd);
1370 if (tcp_idle_cwv) {
1371 u_long idle_time, decay_cwnd;
1374 * RFC2861, but only after idle period.
1378 * Before the congestion window is reduced, ssthresh
1379 * is set to the maximum of its current value and 3/4
1380 * cwnd. If the sender then has more data to send
1381 * than the decayed cwnd allows, the TCP will slow-
1382 * start (perform exponential increase) at least
1383 * half-way back up to the old value of cwnd.
1385 tp->snd_ssthresh = max(tp->snd_ssthresh,
1386 (3 * tp->snd_cwnd) / 4);
1389 * Decay the congestion window by half for every RTT
1390 * that the flow remains inactive.
1392 * The difference between our implementation and
1393 * RFC2861 is that we don't allow cwnd to go below
1394 * the value allowed by RFC5681 (min_cwnd).
1396 idle_time = ticks - tp->snd_last;
1397 decay_cwnd = tp->snd_cwnd;
1398 while (idle_time >= tp->t_rxtcur &&
1399 decay_cwnd > min_cwnd) {
1400 decay_cwnd >>= 1;
1401 idle_time -= tp->t_rxtcur;
1403 tp->snd_cwnd = max(decay_cwnd, min_cwnd);
1404 } else {
1406 * Slow-start from scratch to re-determine the send
1407 * congestion window.
1409 tp->snd_cwnd = min_cwnd;
1412 /* Restart ABC counting during congestion avoidance */
1413 tp->snd_wacked = 0;
1416 static int
1417 tcp_tso_getsize(struct tcpcb *tp, u_int *segsz, u_int *hlen0)
1419 struct inpcb * const inp = tp->t_inpcb;
1420 #ifdef INET6
1421 const boolean_t isipv6 = INP_ISIPV6(inp);
1422 #else
1423 const boolean_t isipv6 = FALSE;
1424 #endif
1425 unsigned int ipoptlen, optlen;
1426 u_int hlen;
1428 hlen = sizeof(struct ip) + sizeof(struct tcphdr);
1430 if (isipv6) {
1431 ipoptlen = ip6_optlen(inp);
1432 } else {
1433 if (inp->inp_options) {
1434 ipoptlen = inp->inp_options->m_len -
1435 offsetof(struct ipoption, ipopt_list);
1436 } else {
1437 ipoptlen = 0;
1440 #ifdef IPSEC
1441 ipoptlen += ipsec_hdrsiz_tcp(tp);
1442 #endif
1443 hlen += ipoptlen;
1445 optlen = 0;
1446 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
1447 (tp->t_flags & TF_RCVD_TSTMP))
1448 optlen += TCPOLEN_TSTAMP_APPA;
1449 hlen += optlen;
1451 if (tp->t_maxopd <= optlen + ipoptlen)
1452 return EHOSTUNREACH;
1454 *segsz = tp->t_maxopd - optlen - ipoptlen;
1455 *hlen0 = hlen;
1456 return 0;
1459 static void
1460 tcp_output_sched_handler(netmsg_t nmsg)
1462 struct tcpcb *tp = nmsg->lmsg.u.ms_resultp;
1464 /* Reply ASAP */
1465 crit_enter();
1466 lwkt_replymsg(&nmsg->lmsg, 0);
1467 crit_exit();
1469 tcp_output_fair(tp);
1472 void
1473 tcp_output_init(struct tcpcb *tp)
1475 netmsg_init(tp->tt_sndmore, NULL, &netisr_adone_rport, MSGF_DROPABLE,
1476 tcp_output_sched_handler);
1477 tp->tt_sndmore->lmsg.u.ms_resultp = tp;
1480 void
1481 tcp_output_cancel(struct tcpcb *tp)
1484 * This message is still pending to be processed;
1485 * drop it. Optimized.
1487 crit_enter();
1488 if ((tp->tt_sndmore->lmsg.ms_flags & MSGF_DONE) == 0) {
1489 lwkt_dropmsg(&tp->tt_sndmore->lmsg);
1491 crit_exit();
1494 boolean_t
1495 tcp_output_pending(struct tcpcb *tp)
1497 if ((tp->tt_sndmore->lmsg.ms_flags & MSGF_DONE) == 0)
1498 return TRUE;
1499 else
1500 return FALSE;
1503 static void
1504 tcp_output_sched(struct tcpcb *tp)
1506 crit_enter();
1507 if (tp->tt_sndmore->lmsg.ms_flags & MSGF_DONE)
1508 lwkt_sendmsg(netisr_cpuport(mycpuid), &tp->tt_sndmore->lmsg);
1509 crit_exit();
1513 * Fairsend
1515 * Yield to other senders or receivers on the same netisr if the current
1516 * TCP stream has sent tcp_fairsend segments and is going to burst more
1517 * segments. Bursting large amount of segements in a single TCP stream
1518 * could delay other senders' segments and receivers' ACKs quite a lot,
1519 * if others segments and ACKs are queued on to the same hardware transmit
1520 * queue; thus cause unfairness between senders and suppress receiving
1521 * performance.
1523 * Fairsend should be performed at the places that do not affect segment
1524 * sending during congestion control, e.g.
1525 * - User requested output
1526 * - ACK input triggered output
1528 * NOTE:
1529 * For devices that are TSO capable, their TSO aggregation size limit could
1530 * affect fairsend.
1533 tcp_output_fair(struct tcpcb *tp)
1535 int ret;
1537 tp->t_flags |= TF_FAIRSEND;
1538 ret = tcp_output(tp);
1539 tp->t_flags &= ~TF_FAIRSEND;
1541 return ret;