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