]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_output.c
This commit was generated by cvs2svn to compensate for changes in r153200,
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_output.c
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)tcp_output.c        8.4 (Berkeley) 5/24/95
30  * $FreeBSD$
31  */
32
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include "opt_ipsec.h"
36 #include "opt_mac.h"
37 #include "opt_tcpdebug.h"
38 #include "opt_tcp_sack.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/domain.h>
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/mac.h>
46 #include <sys/mbuf.h>
47 #include <sys/mutex.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52
53 #include <net/route.h>
54
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
58 #include <netinet/in_pcb.h>
59 #include <netinet/ip_var.h>
60 #include <netinet/ip_options.h>
61 #ifdef INET6
62 #include <netinet6/in6_pcb.h>
63 #include <netinet/ip6.h>
64 #include <netinet6/ip6_var.h>
65 #endif
66 #include <netinet/tcp.h>
67 #define TCPOUTFLAGS
68 #include <netinet/tcp_fsm.h>
69 #include <netinet/tcp_seq.h>
70 #include <netinet/tcp_timer.h>
71 #include <netinet/tcp_var.h>
72 #include <netinet/tcpip.h>
73 #ifdef TCPDEBUG
74 #include <netinet/tcp_debug.h>
75 #endif
76
77 #ifdef IPSEC
78 #include <netinet6/ipsec.h>
79 #endif /*IPSEC*/
80
81 #ifdef FAST_IPSEC
82 #include <netipsec/ipsec.h>
83 #define IPSEC
84 #endif /*FAST_IPSEC*/
85
86 #include <machine/in_cksum.h>
87
88 #ifdef notyet
89 extern struct mbuf *m_copypack();
90 #endif
91
92 int path_mtu_discovery = 1;
93 SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_RW,
94         &path_mtu_discovery, 1, "Enable Path MTU Discovery");
95
96 int ss_fltsz = 1;
97 SYSCTL_INT(_net_inet_tcp, OID_AUTO, slowstart_flightsize, CTLFLAG_RW,
98         &ss_fltsz, 1, "Slow start flight size");
99
100 int ss_fltsz_local = 4;
101 SYSCTL_INT(_net_inet_tcp, OID_AUTO, local_slowstart_flightsize, CTLFLAG_RW,
102         &ss_fltsz_local, 1, "Slow start flight size for local networks");
103
104 int     tcp_do_newreno = 1;
105 SYSCTL_INT(_net_inet_tcp, OID_AUTO, newreno, CTLFLAG_RW, &tcp_do_newreno,
106         0, "Enable NewReno Algorithms");
107
108 /*
109  * Tcp output routine: figure out what should be sent and send it.
110  */
111 int
112 tcp_output(struct tcpcb *tp)
113 {
114         struct socket *so = tp->t_inpcb->inp_socket;
115         long len, recwin, sendwin;
116         int off, flags, error;
117 #ifdef TCP_SIGNATURE
118         int sigoff = 0;
119 #endif
120         struct mbuf *m;
121         struct ip *ip = NULL;
122         struct ipovly *ipov = NULL;
123         struct tcphdr *th;
124         u_char opt[TCP_MAXOLEN];
125         unsigned ipoptlen, optlen, hdrlen;
126         int idle, sendalot;
127         int i, sack_rxmit;
128         int sack_bytes_rxmt;
129         struct sackhole *p;
130 #if 0
131         int maxburst = TCP_MAXBURST;
132 #endif
133 #ifdef INET6
134         struct ip6_hdr *ip6 = NULL;
135         int isipv6;
136
137         isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
138 #endif
139
140         INP_LOCK_ASSERT(tp->t_inpcb);
141
142         /*
143          * Determine length of data that should be transmitted,
144          * and flags that will be used.
145          * If there is some data or critical controls (SYN, RST)
146          * to send, then transmit; otherwise, investigate further.
147          */
148         idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
149         if (idle && (ticks - tp->t_rcvtime) >= tp->t_rxtcur) {
150                 /*
151                  * We have been idle for "a while" and no acks are
152                  * expected to clock out any data we send --
153                  * slow start to get ack "clock" running again.
154                  *
155                  * Set the slow-start flight size depending on whether
156                  * this is a local network or not.
157                  */
158                 int ss = ss_fltsz;
159 #ifdef INET6
160                 if (isipv6) {
161                         if (in6_localaddr(&tp->t_inpcb->in6p_faddr))
162                                 ss = ss_fltsz_local;
163                 } else
164 #endif /* INET6 */
165                 if (in_localaddr(tp->t_inpcb->inp_faddr))
166                         ss = ss_fltsz_local;
167                 tp->snd_cwnd = tp->t_maxseg * ss;
168         }
169         tp->t_flags &= ~TF_LASTIDLE;
170         if (idle) {
171                 if (tp->t_flags & TF_MORETOCOME) {
172                         tp->t_flags |= TF_LASTIDLE;
173                         idle = 0;
174                 }
175         }
176 again:
177         /*
178          * If we've recently taken a timeout, snd_max will be greater than
179          * snd_nxt.  There may be SACK information that allows us to avoid
180          * resending already delivered data.  Adjust snd_nxt accordingly.
181          */
182         if (tp->sack_enable && SEQ_LT(tp->snd_nxt, tp->snd_max))
183                 tcp_sack_adjust(tp);
184         sendalot = 0;
185         off = tp->snd_nxt - tp->snd_una;
186         sendwin = min(tp->snd_wnd, tp->snd_cwnd);
187         sendwin = min(sendwin, tp->snd_bwnd);
188
189         flags = tcp_outflags[tp->t_state];
190         /*
191          * Send any SACK-generated retransmissions.  If we're explicitly trying
192          * to send out new data (when sendalot is 1), bypass this function.
193          * If we retransmit in fast recovery mode, decrement snd_cwnd, since
194          * we're replacing a (future) new transmission with a retransmission
195          * now, and we previously incremented snd_cwnd in tcp_input().
196          */
197         /*
198          * Still in sack recovery , reset rxmit flag to zero.
199          */
200         sack_rxmit = 0;
201         sack_bytes_rxmt = 0;
202         len = 0;
203         p = NULL;
204         if (tp->sack_enable && IN_FASTRECOVERY(tp) &&
205             (p = tcp_sack_output(tp, &sack_bytes_rxmt))) {
206                 long cwin;
207                 
208                 cwin = min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt;
209                 if (cwin < 0)
210                         cwin = 0;
211                 /* Do not retransmit SACK segments beyond snd_recover */
212                 if (SEQ_GT(p->end, tp->snd_recover)) {
213                         /*
214                          * (At least) part of sack hole extends beyond
215                          * snd_recover. Check to see if we can rexmit data
216                          * for this hole.
217                          */
218                         if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
219                                 /*
220                                  * Can't rexmit any more data for this hole.
221                                  * That data will be rexmitted in the next
222                                  * sack recovery episode, when snd_recover
223                                  * moves past p->rxmit.
224                                  */
225                                 p = NULL;
226                                 goto after_sack_rexmit;
227                         } else
228                                 /* Can rexmit part of the current hole */
229                                 len = ((long)ulmin(cwin,
230                                                    tp->snd_recover - p->rxmit));
231                 } else
232                         len = ((long)ulmin(cwin, p->end - p->rxmit));
233                 off = p->rxmit - tp->snd_una;
234                 KASSERT(off >= 0,("%s: sack block to the left of una : %d",
235                     __func__, off));
236                 if (len > 0) {
237                         sack_rxmit = 1;
238                         sendalot = 1;
239                         tcpstat.tcps_sack_rexmits++;
240                         tcpstat.tcps_sack_rexmit_bytes +=
241                             min(len, tp->t_maxseg);
242                 }
243         }
244 after_sack_rexmit:
245         /*
246          * Get standard flags, and add SYN or FIN if requested by 'hidden'
247          * state flags.
248          */
249         if (tp->t_flags & TF_NEEDFIN)
250                 flags |= TH_FIN;
251         if (tp->t_flags & TF_NEEDSYN)
252                 flags |= TH_SYN;
253
254         SOCKBUF_LOCK(&so->so_snd);
255         /*
256          * If in persist timeout with window of 0, send 1 byte.
257          * Otherwise, if window is small but nonzero
258          * and timer expired, we will send what we can
259          * and go to transmit state.
260          */
261         if (tp->t_flags & TF_FORCEDATA) {
262                 if (sendwin == 0) {
263                         /*
264                          * If we still have some data to send, then
265                          * clear the FIN bit.  Usually this would
266                          * happen below when it realizes that we
267                          * aren't sending all the data.  However,
268                          * if we have exactly 1 byte of unsent data,
269                          * then it won't clear the FIN bit below,
270                          * and if we are in persist state, we wind
271                          * up sending the packet without recording
272                          * that we sent the FIN bit.
273                          *
274                          * We can't just blindly clear the FIN bit,
275                          * because if we don't have any more data
276                          * to send then the probe will be the FIN
277                          * itself.
278                          */
279                         if (off < so->so_snd.sb_cc)
280                                 flags &= ~TH_FIN;
281                         sendwin = 1;
282                 } else {
283                         callout_stop(tp->tt_persist);
284                         tp->t_rxtshift = 0;
285                 }
286         }
287
288         /*
289          * If snd_nxt == snd_max and we have transmitted a FIN, the
290          * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
291          * a negative length.  This can also occur when TCP opens up
292          * its congestion window while receiving additional duplicate
293          * acks after fast-retransmit because TCP will reset snd_nxt
294          * to snd_max after the fast-retransmit.
295          *
296          * In the normal retransmit-FIN-only case, however, snd_nxt will
297          * be set to snd_una, the offset will be 0, and the length may
298          * wind up 0.
299          *
300          * If sack_rxmit is true we are retransmitting from the scoreboard
301          * in which case len is already set.
302          */
303         if (sack_rxmit == 0) {
304                 if (sack_bytes_rxmt == 0)
305                         len = ((long)ulmin(so->so_snd.sb_cc, sendwin) - off);
306                 else {
307                         long cwin;
308
309                         /*
310                          * We are inside of a SACK recovery episode and are
311                          * sending new data, having retransmitted all the
312                          * data possible in the scoreboard.
313                          */
314                         len = ((long)ulmin(so->so_snd.sb_cc, tp->snd_wnd) 
315                                - off);
316                         /*
317                          * Don't remove this (len > 0) check !
318                          * We explicitly check for len > 0 here (although it 
319                          * isn't really necessary), to work around a gcc 
320                          * optimization issue - to force gcc to compute
321                          * len above. Without this check, the computation
322                          * of len is bungled by the optimizer.
323                          */
324                         if (len > 0) {
325                                 cwin = tp->snd_cwnd - 
326                                         (tp->snd_nxt - tp->sack_newdata) -
327                                         sack_bytes_rxmt;
328                                 if (cwin < 0)
329                                         cwin = 0;
330                                 len = lmin(len, cwin);
331                         }
332                 }
333         }
334
335         /*
336          * Lop off SYN bit if it has already been sent.  However, if this
337          * is SYN-SENT state and if segment contains data and if we don't
338          * know that foreign host supports TAO, suppress sending segment.
339          */
340         if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
341                 flags &= ~TH_SYN;
342                 off--, len++;
343         }
344
345         /*
346          * Be careful not to send data and/or FIN on SYN segments.
347          * This measure is needed to prevent interoperability problems
348          * with not fully conformant TCP implementations.
349          */
350         if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
351                 len = 0;
352                 flags &= ~TH_FIN;
353         }
354
355         if (len < 0) {
356                 /*
357                  * If FIN has been sent but not acked,
358                  * but we haven't been called to retransmit,
359                  * len will be < 0.  Otherwise, window shrank
360                  * after we sent into it.  If window shrank to 0,
361                  * cancel pending retransmit, pull snd_nxt back
362                  * to (closed) window, and set the persist timer
363                  * if it isn't already going.  If the window didn't
364                  * close completely, just wait for an ACK.
365                  */
366                 len = 0;
367                 if (sendwin == 0) {
368                         callout_stop(tp->tt_rexmt);
369                         tp->t_rxtshift = 0;
370                         tp->snd_nxt = tp->snd_una;
371                         if (!callout_active(tp->tt_persist))
372                                 tcp_setpersist(tp);
373                 }
374         }
375
376         /*
377          * len will be >= 0 after this point.  Truncate to the maximum
378          * segment length and ensure that FIN is removed if the length
379          * no longer contains the last data byte.
380          */
381         if (len > tp->t_maxseg) {
382                 len = tp->t_maxseg;
383                 sendalot = 1;
384         }
385         if (sack_rxmit) {
386                 if (SEQ_LT(p->rxmit + len, tp->snd_una + so->so_snd.sb_cc))
387                         flags &= ~TH_FIN;
388         } else {
389                 if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))
390                         flags &= ~TH_FIN;
391         }
392
393         recwin = sbspace(&so->so_rcv);
394
395         /*
396          * Sender silly window avoidance.   We transmit under the following
397          * conditions when len is non-zero:
398          *
399          *      - We have a full segment
400          *      - This is the last buffer in a write()/send() and we are
401          *        either idle or running NODELAY
402          *      - we've timed out (e.g. persist timer)
403          *      - we have more then 1/2 the maximum send window's worth of
404          *        data (receiver may be limited the window size)
405          *      - we need to retransmit
406          */
407         if (len) {
408                 if (len == tp->t_maxseg)
409                         goto send;
410                 /*
411                  * NOTE! on localhost connections an 'ack' from the remote
412                  * end may occur synchronously with the output and cause
413                  * us to flush a buffer queued with moretocome.  XXX
414                  *
415                  * note: the len + off check is almost certainly unnecessary.
416                  */
417                 if (!(tp->t_flags & TF_MORETOCOME) &&   /* normal case */
418                     (idle || (tp->t_flags & TF_NODELAY)) &&
419                     len + off >= so->so_snd.sb_cc &&
420                     (tp->t_flags & TF_NOPUSH) == 0) {
421                         goto send;
422                 }
423                 if (tp->t_flags & TF_FORCEDATA)         /* typ. timeout case */
424                         goto send;
425                 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
426                         goto send;
427                 if (SEQ_LT(tp->snd_nxt, tp->snd_max))   /* retransmit case */
428                         goto send;
429                 if (sack_rxmit)
430                         goto send;
431         }
432
433         /*
434          * Compare available window to amount of window
435          * known to peer (as advertised window less
436          * next expected input).  If the difference is at least two
437          * max size segments, or at least 50% of the maximum possible
438          * window, then want to send a window update to peer.
439          * Skip this if the connection is in T/TCP half-open state.
440          */
441         if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN)) {
442                 /*
443                  * "adv" is the amount we can increase the window,
444                  * taking into account that we are limited by
445                  * TCP_MAXWIN << tp->rcv_scale.
446                  */
447                 long adv = min(recwin, (long)TCP_MAXWIN << tp->rcv_scale) -
448                         (tp->rcv_adv - tp->rcv_nxt);
449
450                 if (adv >= (long) (2 * tp->t_maxseg))
451                         goto send;
452                 if (2 * adv >= (long) so->so_rcv.sb_hiwat)
453                         goto send;
454         }
455
456         /*
457          * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
458          * is also a catch-all for the retransmit timer timeout case.
459          */
460         if (tp->t_flags & TF_ACKNOW)
461                 goto send;
462         if ((flags & TH_RST) ||
463             ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0))
464                 goto send;
465         if (SEQ_GT(tp->snd_up, tp->snd_una))
466                 goto send;
467         /*
468          * If our state indicates that FIN should be sent
469          * and we have not yet done so, then we need to send.
470          */
471         if (flags & TH_FIN &&
472             ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
473                 goto send;
474         /*
475          * In SACK, it is possible for tcp_output to fail to send a segment
476          * after the retransmission timer has been turned off.  Make sure
477          * that the retransmission timer is set.
478          */
479         if (tp->sack_enable && SEQ_GT(tp->snd_max, tp->snd_una) &&
480             !callout_active(tp->tt_rexmt) &&
481             !callout_active(tp->tt_persist)) {
482                 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
483                               tcp_timer_rexmt, tp);
484                 goto just_return;
485         } 
486         /*
487          * TCP window updates are not reliable, rather a polling protocol
488          * using ``persist'' packets is used to insure receipt of window
489          * updates.  The three ``states'' for the output side are:
490          *      idle                    not doing retransmits or persists
491          *      persisting              to move a small or zero window
492          *      (re)transmitting        and thereby not persisting
493          *
494          * callout_active(tp->tt_persist)
495          *      is true when we are in persist state.
496          * (tp->t_flags & TF_FORCEDATA)
497          *      is set when we are called to send a persist packet.
498          * callout_active(tp->tt_rexmt)
499          *      is set when we are retransmitting
500          * The output side is idle when both timers are zero.
501          *
502          * If send window is too small, there is data to transmit, and no
503          * retransmit or persist is pending, then go to persist state.
504          * If nothing happens soon, send when timer expires:
505          * if window is nonzero, transmit what we can,
506          * otherwise force out a byte.
507          */
508         if (so->so_snd.sb_cc && !callout_active(tp->tt_rexmt) &&
509             !callout_active(tp->tt_persist)) {
510                 tp->t_rxtshift = 0;
511                 tcp_setpersist(tp);
512         }
513
514         /*
515          * No reason to send a segment, just return.
516          */
517 just_return:
518         SOCKBUF_UNLOCK(&so->so_snd);
519         return (0);
520
521 send:
522         SOCKBUF_LOCK_ASSERT(&so->so_snd);
523         /*
524          * Before ESTABLISHED, force sending of initial options
525          * unless TCP set not to do any options.
526          * NOTE: we assume that the IP/TCP header plus TCP options
527          * always fit in a single mbuf, leaving room for a maximum
528          * link header, i.e.
529          *      max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
530          */
531         optlen = 0;
532 #ifdef INET6
533         if (isipv6)
534                 hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
535         else
536 #endif
537         hdrlen = sizeof (struct tcpiphdr);
538         if (flags & TH_SYN) {
539                 tp->snd_nxt = tp->iss;
540                 if ((tp->t_flags & TF_NOOPT) == 0) {
541                         u_short mss;
542
543                         opt[0] = TCPOPT_MAXSEG;
544                         opt[1] = TCPOLEN_MAXSEG;
545                         mss = htons((u_short) tcp_mssopt(&tp->t_inpcb->inp_inc));
546                         (void)memcpy(opt + 2, &mss, sizeof(mss));
547                         optlen = TCPOLEN_MAXSEG;
548
549                         if ((tp->t_flags & TF_REQ_SCALE) &&
550                             ((flags & TH_ACK) == 0 ||
551                             (tp->t_flags & TF_RCVD_SCALE))) {
552                                 *((u_int32_t *)(opt + optlen)) = htonl(
553                                         TCPOPT_NOP << 24 |
554                                         TCPOPT_WINDOW << 16 |
555                                         TCPOLEN_WINDOW << 8 |
556                                         tp->request_r_scale);
557                                 optlen += 4;
558                         }
559                 }
560         }
561
562         /*
563          * Send a timestamp and echo-reply if this is a SYN and our side
564          * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
565          * and our peer have sent timestamps in our SYN's.
566          */
567         if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
568             (flags & TH_RST) == 0 &&
569             ((flags & TH_ACK) == 0 ||
570              (tp->t_flags & TF_RCVD_TSTMP))) {
571                 u_int32_t *lp = (u_int32_t *)(opt + optlen);
572
573                 /* Form timestamp option as shown in appendix A of RFC 1323. */
574                 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
575                 *lp++ = htonl(ticks);
576                 *lp   = htonl(tp->ts_recent);
577                 optlen += TCPOLEN_TSTAMP_APPA;
578         }
579
580 #ifdef TCP_SIGNATURE
581 #ifdef INET6
582         if (!isipv6)
583 #endif
584         if (tp->t_flags & TF_SIGNATURE) {
585                 int i;
586                 u_char *bp;
587
588                 /* Initialize TCP-MD5 option (RFC2385) */
589                 bp = (u_char *)opt + optlen;
590                 *bp++ = TCPOPT_SIGNATURE;
591                 *bp++ = TCPOLEN_SIGNATURE;
592                 sigoff = optlen + 2;
593                 for (i = 0; i < TCP_SIGLEN; i++)
594                         *bp++ = 0;
595                 optlen += TCPOLEN_SIGNATURE;
596         }
597 #endif /* TCP_SIGNATURE */
598
599         if (tp->sack_enable && ((tp->t_flags & TF_NOOPT) == 0)) {
600                 /* 
601                  * Tack on the SACK permitted option *last*.
602                  * And do padding of options after tacking this on.
603                  * This is because of MSS, TS, WinScale and Signatures are
604                  * all present, we have just 2 bytes left for the SACK
605                  * permitted option, which is just enough.
606                  */
607                 /*
608                  * If this is the first SYN of connection (not a SYN
609                  * ACK), include SACK permitted option.  If this is a
610                  * SYN ACK, include SACK permitted option if peer has
611                  * already done so. This is only for active connect,
612                  * since the syncache takes care of the passive connect.
613                  */
614                 if ((flags & TH_SYN) &&
615                     (!(flags & TH_ACK) || (tp->t_flags & TF_SACK_PERMIT))) {
616                         u_char *bp;
617                         bp = (u_char *)opt + optlen;
618
619                         *bp++ = TCPOPT_SACK_PERMITTED;
620                         *bp++ = TCPOLEN_SACK_PERMITTED;
621                         optlen += TCPOLEN_SACK_PERMITTED;
622                 }
623
624                 /*
625                  * Send SACKs if necessary.  This should be the last
626                  * option processed.  Only as many SACKs are sent as
627                  * are permitted by the maximum options size.
628                  *
629                  * In general, SACK blocks consume 8*n+2 bytes.
630                  * So a full size SACK blocks option is 34 bytes
631                  * (to generate 4 SACK blocks).  At a minimum,
632                  * we need 10 bytes (to generate 1 SACK block).
633                  * If TCP Timestamps (12 bytes) and TCP Signatures
634                  * (18 bytes) are both present, we'll just have
635                  * 10 bytes for SACK options 40 - (12 + 18).
636                  */
637                 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
638                     (tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0 &&
639                     MAX_TCPOPTLEN - optlen - 2 >= TCPOLEN_SACK) {
640                         int nsack, sackoptlen, padlen;
641                         u_char *bp = (u_char *)opt + optlen;
642                         u_int32_t *lp;
643
644                         nsack = (MAX_TCPOPTLEN - optlen - 2) / TCPOLEN_SACK;
645                         nsack = min(nsack, tp->rcv_numsacks);
646                         sackoptlen = (2 + nsack * TCPOLEN_SACK);
647
648                         /*
649                          * First we need to pad options so that the
650                          * SACK blocks can start at a 4-byte boundary
651                          * (sack option and length are at a 2 byte offset).
652                          */
653                         padlen = (MAX_TCPOPTLEN - optlen - sackoptlen) % 4;
654                         optlen += padlen;
655                         while (padlen-- > 0)
656                                 *bp++ = TCPOPT_NOP;
657
658                         tcpstat.tcps_sack_send_blocks++;
659                         *bp++ = TCPOPT_SACK;
660                         *bp++ = sackoptlen;
661                         lp = (u_int32_t *)bp;
662                         for (i = 0; i < nsack; i++) {
663                                 struct sackblk sack = tp->sackblks[i];
664                                 *lp++ = htonl(sack.start);
665                                 *lp++ = htonl(sack.end);
666                         }
667                         optlen += sackoptlen;
668                 }
669         }
670
671         /* Pad TCP options to a 4 byte boundary */
672         if (optlen < MAX_TCPOPTLEN && (optlen % sizeof(u_int32_t))) {
673                 int pad = sizeof(u_int32_t) - (optlen % sizeof(u_int32_t));
674                 u_char *bp = (u_char *)opt + optlen;
675
676                 optlen += pad;
677                 while (pad) {
678                         *bp++ = TCPOPT_EOL;
679                         pad--;
680                 }
681         }
682
683         hdrlen += optlen;
684
685 #ifdef INET6
686         if (isipv6)
687                 ipoptlen = ip6_optlen(tp->t_inpcb);
688         else
689 #endif
690         if (tp->t_inpcb->inp_options)
691                 ipoptlen = tp->t_inpcb->inp_options->m_len -
692                                 offsetof(struct ipoption, ipopt_list);
693         else
694                 ipoptlen = 0;
695 #ifdef IPSEC
696         ipoptlen += ipsec_hdrsiz_tcp(tp);
697 #endif
698
699         /*
700          * Adjust data length if insertion of options will
701          * bump the packet length beyond the t_maxopd length.
702          * Clear the FIN bit because we cut off the tail of
703          * the segment.
704          */
705         if (len + optlen + ipoptlen > tp->t_maxopd) {
706                 /*
707                  * If there is still more to send, don't close the connection.
708                  */
709                 flags &= ~TH_FIN;
710                 len = tp->t_maxopd - optlen - ipoptlen;
711                 sendalot = 1;
712         }
713
714 /*#ifdef DIAGNOSTIC*/
715 #ifdef INET6
716         if (max_linkhdr + hdrlen > MCLBYTES)
717 #else
718         if (max_linkhdr + hdrlen > MHLEN)
719 #endif
720                 panic("tcphdr too big");
721 /*#endif*/
722
723         /*
724          * Grab a header mbuf, attaching a copy of data to
725          * be transmitted, and initialize the header from
726          * the template for sends on this connection.
727          */
728         if (len) {
729                 if ((tp->t_flags & TF_FORCEDATA) && len == 1)
730                         tcpstat.tcps_sndprobe++;
731                 else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
732                         tcpstat.tcps_sndrexmitpack++;
733                         tcpstat.tcps_sndrexmitbyte += len;
734                 } else {
735                         tcpstat.tcps_sndpack++;
736                         tcpstat.tcps_sndbyte += len;
737                 }
738 #ifdef notyet
739                 if ((m = m_copypack(so->so_snd.sb_mb, off,
740                     (int)len, max_linkhdr + hdrlen)) == 0) {
741                         SOCKBUF_UNLOCK(&so->so_snd);
742                         error = ENOBUFS;
743                         goto out;
744                 }
745                 /*
746                  * m_copypack left space for our hdr; use it.
747                  */
748                 m->m_len += hdrlen;
749                 m->m_data -= hdrlen;
750 #else
751                 MGETHDR(m, M_DONTWAIT, MT_DATA);
752                 if (m == NULL) {
753                         SOCKBUF_UNLOCK(&so->so_snd);
754                         error = ENOBUFS;
755                         goto out;
756                 }
757 #ifdef INET6
758                 if (MHLEN < hdrlen + max_linkhdr) {
759                         MCLGET(m, M_DONTWAIT);
760                         if ((m->m_flags & M_EXT) == 0) {
761                                 SOCKBUF_UNLOCK(&so->so_snd);
762                                 m_freem(m);
763                                 error = ENOBUFS;
764                                 goto out;
765                         }
766                 }
767 #endif
768                 m->m_data += max_linkhdr;
769                 m->m_len = hdrlen;
770                 if (len <= MHLEN - hdrlen - max_linkhdr) {
771                         m_copydata(so->so_snd.sb_mb, off, (int) len,
772                             mtod(m, caddr_t) + hdrlen);
773                         m->m_len += len;
774                 } else {
775                         m->m_next = m_copy(so->so_snd.sb_mb, off, (int) len);
776                         if (m->m_next == 0) {
777                                 SOCKBUF_UNLOCK(&so->so_snd);
778                                 (void) m_free(m);
779                                 error = ENOBUFS;
780                                 goto out;
781                         }
782                 }
783 #endif
784                 /*
785                  * If we're sending everything we've got, set PUSH.
786                  * (This will keep happy those implementations which only
787                  * give data to the user when a buffer fills or
788                  * a PUSH comes in.)
789                  */
790                 if (off + len == so->so_snd.sb_cc)
791                         flags |= TH_PUSH;
792                 SOCKBUF_UNLOCK(&so->so_snd);
793         } else {
794                 SOCKBUF_UNLOCK(&so->so_snd);
795                 if (tp->t_flags & TF_ACKNOW)
796                         tcpstat.tcps_sndacks++;
797                 else if (flags & (TH_SYN|TH_FIN|TH_RST))
798                         tcpstat.tcps_sndctrl++;
799                 else if (SEQ_GT(tp->snd_up, tp->snd_una))
800                         tcpstat.tcps_sndurg++;
801                 else
802                         tcpstat.tcps_sndwinup++;
803
804                 MGETHDR(m, M_DONTWAIT, MT_DATA);
805                 if (m == NULL) {
806                         error = ENOBUFS;
807                         goto out;
808                 }
809 #ifdef INET6
810                 if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
811                     MHLEN >= hdrlen) {
812                         MH_ALIGN(m, hdrlen);
813                 } else
814 #endif
815                 m->m_data += max_linkhdr;
816                 m->m_len = hdrlen;
817         }
818         SOCKBUF_UNLOCK_ASSERT(&so->so_snd);
819         m->m_pkthdr.rcvif = (struct ifnet *)0;
820 #ifdef MAC
821         mac_create_mbuf_from_inpcb(tp->t_inpcb, m);
822 #endif
823 #ifdef INET6
824         if (isipv6) {
825                 ip6 = mtod(m, struct ip6_hdr *);
826                 th = (struct tcphdr *)(ip6 + 1);
827                 tcpip_fillheaders(tp->t_inpcb, ip6, th);
828         } else
829 #endif /* INET6 */
830         {
831                 ip = mtod(m, struct ip *);
832                 ipov = (struct ipovly *)ip;
833                 th = (struct tcphdr *)(ip + 1);
834                 tcpip_fillheaders(tp->t_inpcb, ip, th);
835         }
836
837         /*
838          * Fill in fields, remembering maximum advertised
839          * window for use in delaying messages about window sizes.
840          * If resending a FIN, be sure not to use a new sequence number.
841          */
842         if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
843             tp->snd_nxt == tp->snd_max)
844                 tp->snd_nxt--;
845         /*
846          * If we are doing retransmissions, then snd_nxt will
847          * not reflect the first unsent octet.  For ACK only
848          * packets, we do not want the sequence number of the
849          * retransmitted packet, we want the sequence number
850          * of the next unsent octet.  So, if there is no data
851          * (and no SYN or FIN), use snd_max instead of snd_nxt
852          * when filling in ti_seq.  But if we are in persist
853          * state, snd_max might reflect one byte beyond the
854          * right edge of the window, so use snd_nxt in that
855          * case, since we know we aren't doing a retransmission.
856          * (retransmit and persist are mutually exclusive...)
857          */
858         if (sack_rxmit == 0) {
859                 if (len || (flags & (TH_SYN|TH_FIN))
860                     || callout_active(tp->tt_persist))
861                         th->th_seq = htonl(tp->snd_nxt);
862                 else
863                         th->th_seq = htonl(tp->snd_max);
864         } else {
865                 th->th_seq = htonl(p->rxmit);
866                 p->rxmit += len;
867                 tp->sackhint.sack_bytes_rexmit += len;
868         }
869         th->th_ack = htonl(tp->rcv_nxt);
870         if (optlen) {
871                 bcopy(opt, th + 1, optlen);
872                 th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
873         }
874         th->th_flags = flags;
875         /*
876          * Calculate receive window.  Don't shrink window,
877          * but avoid silly window syndrome.
878          */
879         if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
880             recwin < (long)tp->t_maxseg)
881                 recwin = 0;
882         if (recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
883                 recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
884         if (recwin > (long)TCP_MAXWIN << tp->rcv_scale)
885                 recwin = (long)TCP_MAXWIN << tp->rcv_scale;
886         th->th_win = htons((u_short) (recwin >> tp->rcv_scale));
887
888
889         /*
890          * Adjust the RXWIN0SENT flag - indicate that we have advertised
891          * a 0 window.  This may cause the remote transmitter to stall.  This
892          * flag tells soreceive() to disable delayed acknowledgements when
893          * draining the buffer.  This can occur if the receiver is attempting
894          * to read more data then can be buffered prior to transmitting on
895          * the connection.
896          */
897         if (recwin == 0)
898                 tp->t_flags |= TF_RXWIN0SENT;
899         else
900                 tp->t_flags &= ~TF_RXWIN0SENT;
901         if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
902                 th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
903                 th->th_flags |= TH_URG;
904         } else
905                 /*
906                  * If no urgent pointer to send, then we pull
907                  * the urgent pointer to the left edge of the send window
908                  * so that it doesn't drift into the send window on sequence
909                  * number wraparound.
910                  */
911                 tp->snd_up = tp->snd_una;               /* drag it along */
912
913 #ifdef TCP_SIGNATURE
914 #ifdef INET6
915         if (!isipv6)
916 #endif
917         if (tp->t_flags & TF_SIGNATURE)
918                 tcp_signature_compute(m, sizeof(struct ip), len, optlen,
919                     (u_char *)(th + 1) + sigoff, IPSEC_DIR_OUTBOUND);
920 #endif
921
922         /*
923          * Put TCP length in extended header, and then
924          * checksum extended header and data.
925          */
926         m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
927 #ifdef INET6
928         if (isipv6)
929                 /*
930                  * ip6_plen is not need to be filled now, and will be filled
931                  * in ip6_output.
932                  */
933                 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
934                                        sizeof(struct tcphdr) + optlen + len);
935         else
936 #endif /* INET6 */
937         {
938                 m->m_pkthdr.csum_flags = CSUM_TCP;
939                 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
940                 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
941                     htons(sizeof(struct tcphdr) + IPPROTO_TCP + len + optlen));
942
943                 /* IP version must be set here for ipv4/ipv6 checking later */
944                 KASSERT(ip->ip_v == IPVERSION,
945                     ("%s: IP version incorrect: %d", __func__, ip->ip_v));
946         }
947
948         /*
949          * In transmit state, time the transmission and arrange for
950          * the retransmit.  In persist state, just set snd_max.
951          */
952         if ((tp->t_flags & TF_FORCEDATA) == 0 || 
953             !callout_active(tp->tt_persist)) {
954                 tcp_seq startseq = tp->snd_nxt;
955
956                 /*
957                  * Advance snd_nxt over sequence space of this segment.
958                  */
959                 if (flags & (TH_SYN|TH_FIN)) {
960                         if (flags & TH_SYN)
961                                 tp->snd_nxt++;
962                         if (flags & TH_FIN) {
963                                 tp->snd_nxt++;
964                                 tp->t_flags |= TF_SENTFIN;
965                         }
966                 }
967                 if (sack_rxmit)
968                         goto timer;
969                 tp->snd_nxt += len;
970                 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
971                         tp->snd_max = tp->snd_nxt;
972                         /*
973                          * Time this transmission if not a retransmission and
974                          * not currently timing anything.
975                          */
976                         if (tp->t_rtttime == 0) {
977                                 tp->t_rtttime = ticks;
978                                 tp->t_rtseq = startseq;
979                                 tcpstat.tcps_segstimed++;
980                         }
981                 }
982
983                 /*
984                  * Set retransmit timer if not currently set,
985                  * and not doing a pure ack or a keep-alive probe.
986                  * Initial value for retransmit timer is smoothed
987                  * round-trip time + 2 * round-trip time variance.
988                  * Initialize shift counter which is used for backoff
989                  * of retransmit time.
990                  */
991 timer:
992                 if (!callout_active(tp->tt_rexmt) &&
993                     ((sack_rxmit && tp->snd_nxt != tp->snd_max) ||
994                      (tp->snd_nxt != tp->snd_una))) {
995                         if (callout_active(tp->tt_persist)) {
996                                 callout_stop(tp->tt_persist);
997                                 tp->t_rxtshift = 0;
998                         }
999                         callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1000                                       tcp_timer_rexmt, tp);
1001                 }
1002         } else {
1003                 /*
1004                  * Persist case, update snd_max but since we are in
1005                  * persist mode (no window) we do not update snd_nxt.
1006                  */
1007                 int xlen = len;
1008                 if (flags & TH_SYN)
1009                         ++xlen;
1010                 if (flags & TH_FIN) {
1011                         ++xlen;
1012                         tp->t_flags |= TF_SENTFIN;
1013                 }
1014                 if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
1015                         tp->snd_max = tp->snd_nxt + len;
1016         }
1017
1018 #ifdef TCPDEBUG
1019         /*
1020          * Trace.
1021          */
1022         if (so->so_options & SO_DEBUG) {
1023                 u_short save = 0;
1024 #ifdef INET6
1025                 if (!isipv6)
1026 #endif
1027                 {
1028                         save = ipov->ih_len;
1029                         ipov->ih_len = htons(m->m_pkthdr.len /* - hdrlen + (th->th_off << 2) */);
1030                 }
1031                 tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
1032 #ifdef INET6
1033                 if (!isipv6)
1034 #endif
1035                 ipov->ih_len = save;
1036         }
1037 #endif
1038
1039         /*
1040          * Fill in IP length and desired time to live and
1041          * send to IP level.  There should be a better way
1042          * to handle ttl and tos; we could keep them in
1043          * the template, but need a way to checksum without them.
1044          */
1045         /*
1046          * m->m_pkthdr.len should have been set before cksum calcuration,
1047          * because in6_cksum() need it.
1048          */
1049 #ifdef INET6
1050         if (isipv6) {
1051                 /*
1052                  * we separately set hoplimit for every segment, since the
1053                  * user might want to change the value via setsockopt.
1054                  * Also, desired default hop limit might be changed via
1055                  * Neighbor Discovery.
1056                  */
1057                 ip6->ip6_hlim = in6_selecthlim(tp->t_inpcb, NULL);
1058
1059                 /* TODO: IPv6 IP6TOS_ECT bit on */
1060                 error = ip6_output(m,
1061                             tp->t_inpcb->in6p_outputopts, NULL,
1062                             ((so->so_options & SO_DONTROUTE) ?
1063                             IP_ROUTETOIF : 0), NULL, NULL, tp->t_inpcb);
1064         } else
1065 #endif /* INET6 */
1066     {
1067         ip->ip_len = m->m_pkthdr.len;
1068 #ifdef INET6
1069         if (INP_CHECK_SOCKAF(so, AF_INET6))
1070                 ip->ip_ttl = in6_selecthlim(tp->t_inpcb, NULL);
1071 #endif /* INET6 */
1072         /*
1073          * If we do path MTU discovery, then we set DF on every packet.
1074          * This might not be the best thing to do according to RFC3390
1075          * Section 2. However the tcp hostcache migitates the problem
1076          * so it affects only the first tcp connection with a host.
1077          */
1078         if (path_mtu_discovery)
1079                 ip->ip_off |= IP_DF;
1080
1081         error = ip_output(m, tp->t_inpcb->inp_options, NULL,
1082             ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0,
1083             tp->t_inpcb);
1084     }
1085         if (error) {
1086
1087                 /*
1088                  * We know that the packet was lost, so back out the
1089                  * sequence number advance, if any.
1090                  */
1091                 if ((tp->t_flags & TF_FORCEDATA) == 0 || 
1092                     !callout_active(tp->tt_persist)) {
1093                         /*
1094                          * No need to check for TH_FIN here because
1095                          * the TF_SENTFIN flag handles that case.
1096                          */
1097                         if ((flags & TH_SYN) == 0) {
1098                                 if (sack_rxmit) {
1099                                         p->rxmit -= len;
1100                                         tp->sackhint.sack_bytes_rexmit -= len;
1101                                         KASSERT(tp->sackhint.sack_bytes_rexmit
1102                                                 >= 0,
1103                                                 ("sackhint bytes rtx >= 0"));
1104                                 } else
1105                                         tp->snd_nxt -= len;
1106                         }
1107                 }
1108
1109 out:
1110                 SOCKBUF_UNLOCK_ASSERT(&so->so_snd);     /* Check gotos. */
1111                 if (error == ENOBUFS) {
1112                         if (!callout_active(tp->tt_rexmt) &&
1113                             !callout_active(tp->tt_persist))
1114                                 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1115                                     tcp_timer_rexmt, tp);
1116                         tp->snd_cwnd = tp->t_maxseg;
1117                         return (0);
1118                 }
1119                 if (error == EMSGSIZE) {
1120                         /*
1121                          * ip_output() will have already fixed the route
1122                          * for us.  tcp_mtudisc() will, as its last action,
1123                          * initiate retransmission, so it is important to
1124                          * not do so here.
1125                          */
1126                         tcp_mtudisc(tp->t_inpcb, 0);
1127                         return 0;
1128                 }
1129                 if ((error == EHOSTUNREACH || error == ENETDOWN)
1130                     && TCPS_HAVERCVDSYN(tp->t_state)) {
1131                         tp->t_softerror = error;
1132                         return (0);
1133                 }
1134                 return (error);
1135         }
1136         tcpstat.tcps_sndtotal++;
1137
1138         /*
1139          * Data sent (as far as we can tell).
1140          * If this advertises a larger window than any other segment,
1141          * then remember the size of the advertised window.
1142          * Any pending ACK has now been sent.
1143          */
1144         if (recwin > 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
1145                 tp->rcv_adv = tp->rcv_nxt + recwin;
1146         tp->last_ack_sent = tp->rcv_nxt;
1147         tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
1148         if (callout_active(tp->tt_delack))
1149                 callout_stop(tp->tt_delack);
1150 #if 0
1151         /*
1152          * This completely breaks TCP if newreno is turned on.  What happens
1153          * is that if delayed-acks are turned on on the receiver, this code
1154          * on the transmitter effectively destroys the TCP window, forcing
1155          * it to four packets (1.5Kx4 = 6K window).
1156          */
1157         if (sendalot && (!tcp_do_newreno || --maxburst))
1158                 goto again;
1159 #endif
1160         if (sendalot)
1161                 goto again;
1162         return (0);
1163 }
1164
1165 void
1166 tcp_setpersist(tp)
1167         register struct tcpcb *tp;
1168 {
1169         int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
1170         int tt;
1171
1172         if (callout_active(tp->tt_rexmt))
1173                 panic("tcp_setpersist: retransmit pending");
1174         /*
1175          * Start/restart persistance timer.
1176          */
1177         TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
1178                       TCPTV_PERSMIN, TCPTV_PERSMAX);
1179         callout_reset(tp->tt_persist, tt, tcp_timer_persist, tp);
1180         if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1181                 tp->t_rxtshift++;
1182 }