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