SDL static config fix (Roman Zippel)
[qemu] / slirp / tcp_output.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)tcp_output.c        8.3 (Berkeley) 12/30/93
34  * tcp_output.c,v 1.3 1994/09/15 10:36:55 davidg Exp
35  */
36
37 /*
38  * Changes and additions relating to SLiRP
39  * Copyright (c) 1995 Danny Gasparovski.
40  * 
41  * Please read the file COPYRIGHT for the 
42  * terms and conditions of the copyright.
43  */
44
45 #include <slirp.h>
46
47 #define max(x,y) ((x) > (y) ? (x) : (y))
48 #define min(x,y) ((x) < (y) ? (x) : (y))
49
50 /*
51  * Since this is only used in "stats socket", we give meaning
52  * names instead of the REAL names
53  */
54 char *tcpstates[] = {
55 /*      "CLOSED",       "LISTEN",       "SYN_SENT",     "SYN_RCVD", */
56         "REDIRECT",     "LISTEN",       "SYN_SENT",     "SYN_RCVD",
57         "ESTABLISHED",  "CLOSE_WAIT",   "FIN_WAIT_1",   "CLOSING",
58         "LAST_ACK",     "FIN_WAIT_2",   "TIME_WAIT",
59 };
60
61 u_char  tcp_outflags[TCP_NSTATES] = {
62         TH_RST|TH_ACK, 0,      TH_SYN,        TH_SYN|TH_ACK,
63         TH_ACK,        TH_ACK, TH_FIN|TH_ACK, TH_FIN|TH_ACK, 
64         TH_FIN|TH_ACK, TH_ACK, TH_ACK,
65 };
66
67
68 #define MAX_TCPOPTLEN   32      /* max # bytes that go in options */
69
70 /*
71  * Tcp output routine: figure out what should be sent and send it.
72  */
73 int
74 tcp_output(tp)
75         register struct tcpcb *tp;
76 {
77         register struct socket *so = tp->t_socket;
78         register long len, win;
79         int off, flags, error;
80         register struct mbuf *m;
81         register struct tcpiphdr *ti;
82         u_char opt[MAX_TCPOPTLEN];
83         unsigned optlen, hdrlen;
84         int idle, sendalot;
85         
86         DEBUG_CALL("tcp_output");
87         DEBUG_ARG("tp = %lx", (long )tp);
88         
89         /*
90          * Determine length of data that should be transmitted,
91          * and flags that will be used.
92          * If there is some data or critical controls (SYN, RST)
93          * to send, then transmit; otherwise, investigate further.
94          */
95         idle = (tp->snd_max == tp->snd_una);
96         if (idle && tp->t_idle >= tp->t_rxtcur)
97                 /*
98                  * We have been idle for "a while" and no acks are
99                  * expected to clock out any data we send --
100                  * slow start to get ack "clock" running again.
101                  */
102                 tp->snd_cwnd = tp->t_maxseg;
103 again:
104         sendalot = 0;
105         off = tp->snd_nxt - tp->snd_una;
106         win = min(tp->snd_wnd, tp->snd_cwnd);
107
108         flags = tcp_outflags[tp->t_state];
109         
110         DEBUG_MISC((dfd, " --- tcp_output flags = 0x%x\n",flags));
111         
112         /*
113          * If in persist timeout with window of 0, send 1 byte.
114          * Otherwise, if window is small but nonzero
115          * and timer expired, we will send what we can
116          * and go to transmit state.
117          */
118         if (tp->t_force) {
119                 if (win == 0) {
120                         /*
121                          * If we still have some data to send, then
122                          * clear the FIN bit.  Usually this would
123                          * happen below when it realizes that we
124                          * aren't sending all the data.  However,
125                          * if we have exactly 1 byte of unset data,
126                          * then it won't clear the FIN bit below,
127                          * and if we are in persist state, we wind
128                          * up sending the packet without recording
129                          * that we sent the FIN bit.
130                          *
131                          * We can't just blindly clear the FIN bit,
132                          * because if we don't have any more data
133                          * to send then the probe will be the FIN
134                          * itself.
135                          */
136                         if (off < so->so_snd.sb_cc)
137                                 flags &= ~TH_FIN;
138                         win = 1;
139                 } else {
140                         tp->t_timer[TCPT_PERSIST] = 0;
141                         tp->t_rxtshift = 0;
142                 }
143         }
144
145         len = min(so->so_snd.sb_cc, win) - off;
146
147         if (len < 0) {
148                 /*
149                  * If FIN has been sent but not acked,
150                  * but we haven't been called to retransmit,
151                  * len will be -1.  Otherwise, window shrank
152                  * after we sent into it.  If window shrank to 0,
153                  * cancel pending retransmit and pull snd_nxt
154                  * back to (closed) window.  We will enter persist
155                  * state below.  If the window didn't close completely,
156                  * just wait for an ACK.
157                  */
158                 len = 0;
159                 if (win == 0) {
160                         tp->t_timer[TCPT_REXMT] = 0;
161                         tp->snd_nxt = tp->snd_una;
162                 }
163         }
164         
165         if (len > tp->t_maxseg) {
166                 len = tp->t_maxseg;
167                 sendalot = 1;
168         }
169         if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))
170                 flags &= ~TH_FIN;
171
172         win = sbspace(&so->so_rcv);
173
174         /*
175          * Sender silly window avoidance.  If connection is idle
176          * and can send all data, a maximum segment,
177          * at least a maximum default-size segment do it,
178          * or are forced, do it; otherwise don't bother.
179          * If peer's buffer is tiny, then send
180          * when window is at least half open.
181          * If retransmitting (possibly after persist timer forced us
182          * to send into a small window), then must resend.
183          */
184         if (len) {
185                 if (len == tp->t_maxseg)
186                         goto send;
187                 if ((1 || idle || tp->t_flags & TF_NODELAY) &&
188                     len + off >= so->so_snd.sb_cc)
189                         goto send;
190                 if (tp->t_force)
191                         goto send;
192                 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
193                         goto send;
194                 if (SEQ_LT(tp->snd_nxt, tp->snd_max))
195                         goto send;
196         }
197
198         /*
199          * Compare available window to amount of window
200          * known to peer (as advertised window less
201          * next expected input).  If the difference is at least two
202          * max size segments, or at least 50% of the maximum possible
203          * window, then want to send a window update to peer.
204          */
205         if (win > 0) {
206                 /* 
207                  * "adv" is the amount we can increase the window,
208                  * taking into account that we are limited by
209                  * TCP_MAXWIN << tp->rcv_scale.
210                  */
211                 long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
212                         (tp->rcv_adv - tp->rcv_nxt);
213
214                 if (adv >= (long) (2 * tp->t_maxseg))
215                         goto send;
216                 if (2 * adv >= (long) so->so_rcv.sb_datalen)
217                         goto send;
218         }
219
220         /*
221          * Send if we owe peer an ACK.
222          */
223         if (tp->t_flags & TF_ACKNOW)
224                 goto send;
225         if (flags & (TH_SYN|TH_RST))
226                 goto send;
227         if (SEQ_GT(tp->snd_up, tp->snd_una))
228                 goto send;
229         /*
230          * If our state indicates that FIN should be sent
231          * and we have not yet done so, or we're retransmitting the FIN,
232          * then we need to send.
233          */
234         if (flags & TH_FIN &&
235             ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
236                 goto send;
237
238         /*
239          * TCP window updates are not reliable, rather a polling protocol
240          * using ``persist'' packets is used to insure receipt of window
241          * updates.  The three ``states'' for the output side are:
242          *      idle                    not doing retransmits or persists
243          *      persisting              to move a small or zero window
244          *      (re)transmitting        and thereby not persisting
245          *
246          * tp->t_timer[TCPT_PERSIST]
247          *      is set when we are in persist state.
248          * tp->t_force
249          *      is set when we are called to send a persist packet.
250          * tp->t_timer[TCPT_REXMT]
251          *      is set when we are retransmitting
252          * The output side is idle when both timers are zero.
253          *
254          * If send window is too small, there is data to transmit, and no
255          * retransmit or persist is pending, then go to persist state.
256          * If nothing happens soon, send when timer expires:
257          * if window is nonzero, transmit what we can,
258          * otherwise force out a byte.
259          */
260         if (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&
261             tp->t_timer[TCPT_PERSIST] == 0) {
262                 tp->t_rxtshift = 0;
263                 tcp_setpersist(tp);
264         }
265
266         /*
267          * No reason to send a segment, just return.
268          */
269         tcpstat.tcps_didnuttin++;
270         
271         return (0);
272
273 send:
274         /*
275          * Before ESTABLISHED, force sending of initial options
276          * unless TCP set not to do any options.
277          * NOTE: we assume that the IP/TCP header plus TCP options
278          * always fit in a single mbuf, leaving room for a maximum
279          * link header, i.e.
280          *      max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN
281          */
282         optlen = 0;
283         hdrlen = sizeof (struct tcpiphdr);
284         if (flags & TH_SYN) {
285                 tp->snd_nxt = tp->iss;
286                 if ((tp->t_flags & TF_NOOPT) == 0) {
287                         u_int16_t mss;
288
289                         opt[0] = TCPOPT_MAXSEG;
290                         opt[1] = 4;
291                         mss = htons((u_int16_t) tcp_mss(tp, 0));
292                         memcpy((caddr_t)(opt + 2), (caddr_t)&mss, sizeof(mss));
293                         optlen = 4;
294
295 /*                      if ((tp->t_flags & TF_REQ_SCALE) &&
296  *                          ((flags & TH_ACK) == 0 ||
297  *                          (tp->t_flags & TF_RCVD_SCALE))) {
298  *                              *((u_int32_t *) (opt + optlen)) = htonl(
299  *                                      TCPOPT_NOP << 24 |
300  *                                      TCPOPT_WINDOW << 16 |
301  *                                      TCPOLEN_WINDOW << 8 |
302  *                                      tp->request_r_scale);
303  *                              optlen += 4;
304  *                      }
305  */
306                 }
307         }
308  
309         /*
310          * Send a timestamp and echo-reply if this is a SYN and our side 
311          * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
312          * and our peer have sent timestamps in our SYN's.
313          */
314 /*      if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
315  *           (flags & TH_RST) == 0 &&
316  *          ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
317  *           (tp->t_flags & TF_RCVD_TSTMP))) {
318  *              u_int32_t *lp = (u_int32_t *)(opt + optlen);
319  *
320  *              / * Form timestamp option as shown in appendix A of RFC 1323. *  /
321  *              *lp++ = htonl(TCPOPT_TSTAMP_HDR);
322  *              *lp++ = htonl(tcp_now);
323  *              *lp   = htonl(tp->ts_recent);
324  *              optlen += TCPOLEN_TSTAMP_APPA;
325  *      }
326  */
327         hdrlen += optlen;
328  
329         /*
330          * Adjust data length if insertion of options will
331          * bump the packet length beyond the t_maxseg length.
332          */
333          if (len > tp->t_maxseg - optlen) {
334                 len = tp->t_maxseg - optlen;
335                 sendalot = 1;
336          }
337
338         /*
339          * Grab a header mbuf, attaching a copy of data to
340          * be transmitted, and initialize the header from
341          * the template for sends on this connection.
342          */
343         if (len) {
344                 if (tp->t_force && len == 1)
345                         tcpstat.tcps_sndprobe++;
346                 else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
347                         tcpstat.tcps_sndrexmitpack++;
348                         tcpstat.tcps_sndrexmitbyte += len;
349                 } else {
350                         tcpstat.tcps_sndpack++;
351                         tcpstat.tcps_sndbyte += len;
352                 }
353
354                 m = m_get();
355                 if (m == NULL) {
356 /*                      error = ENOBUFS; */
357                         error = 1;
358                         goto out;
359                 }
360                 m->m_data += if_maxlinkhdr;
361                 m->m_len = hdrlen;
362                 
363                 /* 
364                  * This will always succeed, since we make sure our mbufs
365                  * are big enough to hold one MSS packet + header + ... etc.
366                  */
367 /*              if (len <= MHLEN - hdrlen - max_linkhdr) { */
368
369                         sbcopy(&so->so_snd, off, (int) len, mtod(m, caddr_t) + hdrlen);
370                         m->m_len += len;
371
372 /*              } else {
373  *                      m->m_next = m_copy(so->so_snd.sb_mb, off, (int) len);
374  *                      if (m->m_next == 0)
375  *                              len = 0;
376  *              }
377  */
378                 /*
379                  * If we're sending everything we've got, set PUSH.
380                  * (This will keep happy those implementations which only
381                  * give data to the user when a buffer fills or
382                  * a PUSH comes in.)
383                  */
384                 if (off + len == so->so_snd.sb_cc)
385                         flags |= TH_PUSH;
386         } else {
387                 if (tp->t_flags & TF_ACKNOW)
388                         tcpstat.tcps_sndacks++;
389                 else if (flags & (TH_SYN|TH_FIN|TH_RST))
390                         tcpstat.tcps_sndctrl++;
391                 else if (SEQ_GT(tp->snd_up, tp->snd_una))
392                         tcpstat.tcps_sndurg++;
393                 else
394                         tcpstat.tcps_sndwinup++;
395
396                 m = m_get();
397                 if (m == NULL) {
398 /*                      error = ENOBUFS; */
399                         error = 1;
400                         goto out;
401                 }
402                 m->m_data += if_maxlinkhdr;
403                 m->m_len = hdrlen;
404         }
405
406         ti = mtod(m, struct tcpiphdr *);
407         
408         memcpy((caddr_t)ti, &tp->t_template, sizeof (struct tcpiphdr));
409
410         /*
411          * Fill in fields, remembering maximum advertised
412          * window for use in delaying messages about window sizes.
413          * If resending a FIN, be sure not to use a new sequence number.
414          */
415         if (flags & TH_FIN && tp->t_flags & TF_SENTFIN && 
416             tp->snd_nxt == tp->snd_max)
417                 tp->snd_nxt--;
418         /*
419          * If we are doing retransmissions, then snd_nxt will
420          * not reflect the first unsent octet.  For ACK only
421          * packets, we do not want the sequence number of the
422          * retransmitted packet, we want the sequence number
423          * of the next unsent octet.  So, if there is no data
424          * (and no SYN or FIN), use snd_max instead of snd_nxt
425          * when filling in ti_seq.  But if we are in persist
426          * state, snd_max might reflect one byte beyond the
427          * right edge of the window, so use snd_nxt in that
428          * case, since we know we aren't doing a retransmission.
429          * (retransmit and persist are mutually exclusive...)
430          */
431         if (len || (flags & (TH_SYN|TH_FIN)) || tp->t_timer[TCPT_PERSIST])
432                 ti->ti_seq = htonl(tp->snd_nxt);
433         else
434                 ti->ti_seq = htonl(tp->snd_max);
435         ti->ti_ack = htonl(tp->rcv_nxt);
436         if (optlen) {
437                 memcpy((caddr_t)(ti + 1), (caddr_t)opt, optlen);
438                 ti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;
439         }
440         ti->ti_flags = flags;
441         /*
442          * Calculate receive window.  Don't shrink window,
443          * but avoid silly window syndrome.
444          */
445         if (win < (long)(so->so_rcv.sb_datalen / 4) && win < (long)tp->t_maxseg)
446                 win = 0;
447         if (win > (long)TCP_MAXWIN << tp->rcv_scale)
448                 win = (long)TCP_MAXWIN << tp->rcv_scale;
449         if (win < (long)(tp->rcv_adv - tp->rcv_nxt))
450                 win = (long)(tp->rcv_adv - tp->rcv_nxt);
451         ti->ti_win = htons((u_int16_t) (win>>tp->rcv_scale));
452         
453         if (SEQ_GT(tp->snd_up, tp->snd_una)) {
454                 ti->ti_urp = htons((u_int16_t)(tp->snd_up - ntohl(ti->ti_seq)));
455 #ifdef notdef           
456         if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
457                 ti->ti_urp = htons((u_int16_t)(tp->snd_up - tp->snd_nxt));
458 #endif
459                 ti->ti_flags |= TH_URG;
460         } else
461                 /*
462                  * If no urgent pointer to send, then we pull
463                  * the urgent pointer to the left edge of the send window
464                  * so that it doesn't drift into the send window on sequence
465                  * number wraparound.
466                  */
467                 tp->snd_up = tp->snd_una;               /* drag it along */
468
469         /*
470          * Put TCP length in extended header, and then
471          * checksum extended header and data.
472          */
473         if (len + optlen)
474                 ti->ti_len = htons((u_int16_t)(sizeof (struct tcphdr) +
475                     optlen + len));
476         ti->ti_sum = cksum(m, (int)(hdrlen + len));
477
478         /*
479          * In transmit state, time the transmission and arrange for
480          * the retransmit.  In persist state, just set snd_max.
481          */
482         if (tp->t_force == 0 || tp->t_timer[TCPT_PERSIST] == 0) {
483                 tcp_seq startseq = tp->snd_nxt;
484
485                 /*
486                  * Advance snd_nxt over sequence space of this segment.
487                  */
488                 if (flags & (TH_SYN|TH_FIN)) {
489                         if (flags & TH_SYN)
490                                 tp->snd_nxt++;
491                         if (flags & TH_FIN) {
492                                 tp->snd_nxt++;
493                                 tp->t_flags |= TF_SENTFIN;
494                         }
495                 }
496                 tp->snd_nxt += len;
497                 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
498                         tp->snd_max = tp->snd_nxt;
499                         /*
500                          * Time this transmission if not a retransmission and
501                          * not currently timing anything.
502                          */
503                         if (tp->t_rtt == 0) {
504                                 tp->t_rtt = 1;
505                                 tp->t_rtseq = startseq;
506                                 tcpstat.tcps_segstimed++;
507                         }
508                 }
509
510                 /*
511                  * Set retransmit timer if not currently set,
512                  * and not doing an ack or a keep-alive probe.
513                  * Initial value for retransmit timer is smoothed
514                  * round-trip time + 2 * round-trip time variance.
515                  * Initialize shift counter which is used for backoff
516                  * of retransmit time.
517                  */
518                 if (tp->t_timer[TCPT_REXMT] == 0 &&
519                     tp->snd_nxt != tp->snd_una) {
520                         tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
521                         if (tp->t_timer[TCPT_PERSIST]) {
522                                 tp->t_timer[TCPT_PERSIST] = 0;
523                                 tp->t_rxtshift = 0;
524                         }
525                 }
526         } else
527                 if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
528                         tp->snd_max = tp->snd_nxt + len;
529
530         /*
531          * Fill in IP length and desired time to live and
532          * send to IP level.  There should be a better way
533          * to handle ttl and tos; we could keep them in
534          * the template, but need a way to checksum without them.
535          */
536         m->m_len = hdrlen + len; /* XXX Needed? m_len should be correct */
537         
538     {
539             
540         ((struct ip *)ti)->ip_len = m->m_len;
541
542         ((struct ip *)ti)->ip_ttl = ip_defttl;
543         ((struct ip *)ti)->ip_tos = so->so_iptos;
544             
545 /* #if BSD >= 43 */
546         /* Don't do IP options... */
547 /*      error = ip_output(m, tp->t_inpcb->inp_options, &tp->t_inpcb->inp_route,
548  *          so->so_options & SO_DONTROUTE, 0);
549  */
550         error = ip_output(so, m);
551
552 /* #else
553  *      error = ip_output(m, (struct mbuf *)0, &tp->t_inpcb->inp_route, 
554  *          so->so_options & SO_DONTROUTE);
555  * #endif
556  */
557     }
558         if (error) {
559 out:
560 /*              if (error == ENOBUFS) {
561  *                      tcp_quench(tp->t_inpcb, 0);
562  *                      return (0);
563  *              }
564  */
565 /*              if ((error == EHOSTUNREACH || error == ENETDOWN)
566  *                  && TCPS_HAVERCVDSYN(tp->t_state)) {
567  *                      tp->t_softerror = error;
568  *                      return (0);
569  *              }
570  */
571                 return (error);
572         }
573         tcpstat.tcps_sndtotal++;
574
575         /*
576          * Data sent (as far as we can tell).
577          * If this advertises a larger window than any other segment,
578          * then remember the size of the advertised window.
579          * Any pending ACK has now been sent.
580          */
581         if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
582                 tp->rcv_adv = tp->rcv_nxt + win;
583         tp->last_ack_sent = tp->rcv_nxt;
584         tp->t_flags &= ~(TF_ACKNOW|TF_DELACK);
585         if (sendalot)
586                 goto again;
587
588         return (0);
589 }
590
591 void
592 tcp_setpersist(tp)
593         register struct tcpcb *tp;
594 {
595     int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
596
597 /*      if (tp->t_timer[TCPT_REXMT])
598  *              panic("tcp_output REXMT");
599  */
600         /*
601          * Start/restart persistence timer.
602          */
603         TCPT_RANGESET(tp->t_timer[TCPT_PERSIST],
604             t * tcp_backoff[tp->t_rxtshift],
605             TCPTV_PERSMIN, TCPTV_PERSMAX);
606         if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
607                 tp->t_rxtshift++;
608 }