Fixes network stats printf strings
[akaros.git] / kern / src / net / tcp.c
1 // INFERNO
2 #include <vfs.h>
3 #include <kfs.h>
4 #include <slab.h>
5 #include <kmalloc.h>
6 #include <kref.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <assert.h>
10 #include <error.h>
11 #include <cpio.h>
12 #include <pmap.h>
13 #include <smp.h>
14 #include <ip.h>
15
16 #include <vfs.h>
17 #include <kfs.h>
18 #include <slab.h>
19 #include <kmalloc.h>
20 #include <kref.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <assert.h>
24 #include <error.h>
25 #include <cpio.h>
26 #include <pmap.h>
27 #include <smp.h>
28 #include <ip.h>
29
30 enum {
31         QMAX = 64 * 1024 - 1,
32         IP_TCPPROTO = 6,
33
34         TCP4_IPLEN = 8,
35         TCP4_PHDRSIZE = 12,
36         TCP4_HDRSIZE = 20,
37         TCP4_TCBPHDRSZ = 40,
38         TCP4_PKT = TCP4_IPLEN + TCP4_PHDRSIZE,
39
40         TCP6_IPLEN = 0,
41         TCP6_PHDRSIZE = 40,
42         TCP6_HDRSIZE = 20,
43         TCP6_TCBPHDRSZ = 60,
44         TCP6_PKT = TCP6_IPLEN + TCP6_PHDRSIZE,
45
46         TcptimerOFF = 0,
47         TcptimerON = 1,
48         TcptimerDONE = 2,
49         MAX_TIME = (1 << 20),   /* Forever */
50         TCP_ACK = 50,   /* Timed ack sequence in ms */
51         MAXBACKMS = 9 * 60 * 1000,      /* longest backoff time (ms) before hangup */
52
53         URG = 0x20,     /* Data marked urgent */
54         ACK = 0x10,     /* Acknowledge is valid */
55         PSH = 0x08,     /* Whole data pipe is pushed */
56         RST = 0x04,     /* Reset connection */
57         SYN = 0x02,     /* Pkt. is synchronise */
58         FIN = 0x01,     /* Start close down */
59
60         EOLOPT = 0,
61         NOOPOPT = 1,
62         MSSOPT = 2,
63         MSS_LENGTH = 4, /* Mean segment size */
64         WSOPT = 3,
65         WS_LENGTH = 3,  /* Bits to scale window size by */
66         MSL2 = 10,
67         MSPTICK = 50,   /* Milliseconds per timer tick */
68         DEF_MSS = 1460, /* Default mean segment */
69         DEF_MSS6 = 1280,        /* Default mean segment (min) for v6 */
70         DEF_RTT = 500,  /* Default round trip */
71         DEF_KAT = 120000,       /* Default time (ms) between keep alives */
72         TCP_LISTEN = 0, /* Listen connection */
73         TCP_CONNECT = 1,        /* Outgoing connection */
74         SYNACK_RXTIMER = 250,   /* ms between SYNACK retransmits */
75
76         TCPREXMTTHRESH = 3,     /* dupack threshhold for rxt */
77
78         FORCE = 1,
79         CLONE = 2,
80         RETRAN = 4,
81         ACTIVE = 8,
82         SYNACK = 16,
83
84         LOGAGAIN = 3,
85         LOGDGAIN = 2,
86
87         Closed = 0,     /* Connection states */
88         Listen,
89         Syn_sent,
90         Syn_received,
91         Established,
92         Finwait1,
93         Finwait2,
94         Close_wait,
95         Closing,
96         Last_ack,
97         Time_wait,
98
99         Maxlimbo = 1000,        /* maximum procs waiting for response to SYN ACK */
100         NLHT = 256,     /* hash table size, must be a power of 2 */
101         LHTMASK = NLHT - 1,
102
103         HaveWS = 1 << 8,
104 };
105
106 /* Must correspond to the enumeration above */
107 char *tcpstates[] = {
108         "Closed", "Listen", "Syn_sent", "Syn_received",
109         "Established", "Finwait1", "Finwait2", "Close_wait",
110         "Closing", "Last_ack", "Time_wait"
111 };
112
113 typedef struct Tcptimer Tcptimer;
114 struct Tcptimer {
115         Tcptimer *next;
116         Tcptimer *prev;
117         Tcptimer *readynext;
118         int state;
119         int start;
120         int count;
121         void (*func) (void *);
122         void *arg;
123 };
124
125 /*
126  *  v4 and v6 pseudo headers used for
127  *  checksuming tcp
128  */
129 typedef struct Tcp4hdr Tcp4hdr;
130 struct Tcp4hdr {
131         uint8_t vihl;                           /* Version and header length */
132         uint8_t tos;                            /* Type of service */
133         uint8_t length[2];                      /* packet length */
134         uint8_t id[2];                          /* Identification */
135         uint8_t frag[2];                        /* Fragment information */
136         uint8_t Unused;
137         uint8_t proto;
138         uint8_t tcplen[2];
139         uint8_t tcpsrc[4];
140         uint8_t tcpdst[4];
141         uint8_t tcpsport[2];
142         uint8_t tcpdport[2];
143         uint8_t tcpseq[4];
144         uint8_t tcpack[4];
145         uint8_t tcpflag[2];
146         uint8_t tcpwin[2];
147         uint8_t tcpcksum[2];
148         uint8_t tcpurg[2];
149         /* Options segment */
150         uint8_t tcpopt[1];
151 };
152
153 typedef struct Tcp6hdr Tcp6hdr;
154 struct Tcp6hdr {
155         uint8_t vcf[4];
156         uint8_t ploadlen[2];
157         uint8_t proto;
158         uint8_t ttl;
159         uint8_t tcpsrc[IPaddrlen];
160         uint8_t tcpdst[IPaddrlen];
161         uint8_t tcpsport[2];
162         uint8_t tcpdport[2];
163         uint8_t tcpseq[4];
164         uint8_t tcpack[4];
165         uint8_t tcpflag[2];
166         uint8_t tcpwin[2];
167         uint8_t tcpcksum[2];
168         uint8_t tcpurg[2];
169         /* Options segment */
170         uint8_t tcpopt[1];
171 };
172
173 /*
174  *  this represents the control info
175  *  for a single packet.  It is derived from
176  *  a packet in ntohtcp{4,6}() and stuck into
177  *  a packet in htontcp{4,6}().
178  */
179 typedef struct Tcp Tcp;
180 struct Tcp {
181         uint16_t source;
182         uint16_t dest;
183         uint32_t seq;
184         uint32_t ack;
185         uint8_t flags;
186         uint16_t ws;                            /* window scale option (if not zero) */
187         uint32_t wnd;
188         uint16_t urg;
189         uint16_t mss;                           /* max segment size option (if not zero) */
190         uint16_t len;                           /* size of data */
191 };
192
193 /*
194  *  this header is malloc'd to thread together fragments
195  *  waiting to be coalesced
196  */
197 typedef struct Reseq Reseq;
198 struct Reseq {
199         Reseq *next;
200         Tcp seg;
201         struct block *bp;
202         uint16_t length;
203 };
204
205 /*
206  *  the qlock in the Conv locks this structure
207  */
208 typedef struct Tcpctl Tcpctl;
209 struct Tcpctl {
210         uint8_t state;                          /* Connection state */
211         uint8_t type;                           /* Listening or active connection */
212         uint8_t code;                           /* Icmp code */
213         struct {
214                 uint32_t una;                   /* Unacked data pointer */
215                 uint32_t nxt;                   /* Next sequence expected */
216                 uint32_t ptr;                   /* Data pointer */
217                 uint32_t wnd;                   /* Tcp send window */
218                 uint32_t urg;                   /* Urgent data pointer */
219                 uint32_t wl2;
220                 int scale;                              /* how much to right shift window in xmitted packets */
221                 /* to implement tahoe and reno TCP */
222                 uint32_t dupacks;               /* number of duplicate acks rcvd */
223                 int recovery;                   /* loss recovery flag */
224                 uint32_t rxt;                   /* right window marker for recovery */
225         } snd;
226         struct {
227                 uint32_t nxt;                   /* Receive pointer to next uint8_t slot */
228                 uint32_t wnd;                   /* Receive window incoming */
229                 uint32_t urg;                   /* Urgent pointer */
230                 int blocked;
231                 int una;                                /* unacked data segs */
232                 int scale;                              /* how much to left shift window in rcved packets */
233         } rcv;
234         uint32_t iss;                           /* Initial sequence number */
235         int sawwsopt;                           /* true if we saw a wsopt on the incoming SYN */
236         uint32_t cwind;                         /* Congestion window */
237         int scale;                                      /* desired snd.scale */
238         uint16_t ssthresh;                      /* Slow start threshold */
239         int resent;                                     /* Bytes just resent */
240         int irs;                                        /* Initial received squence */
241         uint16_t mss;                           /* Mean segment size */
242         int rerecv;                                     /* Overlap of data rerecevived */
243         uint32_t window;                        /* Recevive window */
244         uint8_t backoff;                        /* Exponential backoff counter */
245         int backedoff;                          /* ms we've backed off for rexmits */
246         uint8_t flags;                          /* State flags */
247         Reseq *reseq;                           /* Resequencing queue */
248         Tcptimer timer;                         /* Activity timer */
249         Tcptimer acktimer;                      /* Acknowledge timer */
250         Tcptimer rtt_timer;                     /* Round trip timer */
251         Tcptimer katimer;                       /* keep alive timer */
252         uint32_t rttseq;                        /* Round trip sequence */
253         int srtt;                                       /* Shortened round trip */
254         int mdev;                                       /* Mean deviation of round trip */
255         int kacounter;                          /* count down for keep alive */
256         unsigned int sndsyntime;        /* time syn sent */
257         uint32_t time;                          /* time Finwait2 or Syn_received was sent */
258         int nochecksum;                         /* non-zero means don't send checksums */
259         int flgcnt;                                     /* number of flags in the sequence (FIN,SEQ) */
260
261         union {
262                 Tcp4hdr tcp4hdr;
263                 Tcp6hdr tcp6hdr;
264         } protohdr;                                     /* prototype header */
265 };
266
267 /*
268  *  New calls are put in limbo rather than having a conversation structure
269  *  allocated.  Thus, a SYN attack results in lots of limbo'd calls but not
270  *  any real Conv structures mucking things up.  Calls in limbo rexmit their
271  *  SYN ACK every SYNACK_RXTIMER ms up to 4 times, i.e., they disappear after 1 second.
272  *
273  *  In particular they aren't on a listener's queue so that they don't figure
274  *  in the input queue limit.
275  *
276  *  If 1/2 of a T3 was attacking SYN packets, we'ld have a permanent queue
277  *  of 70000 limbo'd calls.  Not great for a linear list but doable.  Therefore
278  *  there is no hashing of this list.
279  */
280 typedef struct Limbo Limbo;
281 struct Limbo {
282         Limbo *next;
283
284         uint8_t laddr[IPaddrlen];
285         uint8_t raddr[IPaddrlen];
286         uint16_t lport;
287         uint16_t rport;
288         uint32_t irs;                           /* initial received sequence */
289         uint32_t iss;                           /* initial sent sequence */
290         uint16_t mss;                           /* mss from the other end */
291         uint16_t rcvscale;                      /* how much to scale rcvd windows */
292         uint16_t sndscale;                      /* how much to scale sent windows */
293         uint32_t lastsend;                      /* last time we sent a synack */
294         uint8_t version;                        /* v4 or v6 */
295         uint8_t rexmits;                        /* number of retransmissions */
296 };
297
298 int tcp_irtt = DEF_RTT;                 /* Initial guess at round trip time */
299 uint16_t tcp_mss = DEF_MSS;             /* Maximum segment size to be sent */
300
301 enum {
302         /* MIB stats */
303         MaxConn,
304         ActiveOpens,
305         PassiveOpens,
306         EstabResets,
307         CurrEstab,
308         InSegs,
309         OutSegs,
310         RetransSegs,
311         RetransTimeouts,
312         InErrs,
313         OutRsts,
314
315         /* non-MIB stats */
316         CsumErrs,
317         HlenErrs,
318         LenErrs,
319         OutOfOrder,
320
321         Nstats
322 };
323
324 static char *statnames[] = {
325         [MaxConn] "MaxConn",
326         [ActiveOpens] "ActiveOpens",
327         [PassiveOpens] "PassiveOpens",
328         [EstabResets] "EstabResets",
329         [CurrEstab] "CurrEstab",
330         [InSegs] "InSegs",
331         [OutSegs] "OutSegs",
332         [RetransSegs] "RetransSegs",
333         [RetransTimeouts] "RetransTimeouts",
334         [InErrs] "InErrs",
335         [OutRsts] "OutRsts",
336         [CsumErrs] "CsumErrs",
337         [HlenErrs] "HlenErrs",
338         [LenErrs] "LenErrs",
339         [OutOfOrder] "OutOfOrder",
340 };
341
342 typedef struct Tcppriv Tcppriv;
343 struct tcppriv {
344         /* List of active timers */
345         qlock_t tl;
346         Tcptimer *timers;
347
348         /* hash table for matching conversations */
349         struct Ipht ht;
350
351         /* calls in limbo waiting for an ACK to our SYN ACK */
352         int nlimbo;
353         Limbo *lht[NLHT];
354
355         /* for keeping track of tcpackproc */
356         qlock_t apl;
357         int ackprocstarted;
358
359         uint32_t stats[Nstats];
360 };
361
362 /*
363  *  Setting tcpporthogdefense to non-zero enables Dong Lin's
364  *  solution to hijacked systems staking out port's as a form
365  *  of DoS attack.
366  *
367  *  To avoid stateless Conv hogs, we pick a sequence number at random.  If
368  *  it that number gets acked by the other end, we shut down the connection.
369  *  Look for tcpporthogedefense in the code.
370  */
371 int tcpporthogdefense = 0;
372
373 int addreseq(Tcpctl *, struct tcppriv *, Tcp *, struct block *, uint16_t);
374 void getreseq(Tcpctl *, Tcp *, struct block **, uint16_t *);
375 void localclose(struct conv *, char *unused_char_p_t);
376 void procsyn(struct conv *, Tcp *);
377 void tcpiput(struct Proto *, struct Ipifc *, struct block *);
378 void tcpoutput(struct conv *);
379 int tcptrim(Tcpctl *, Tcp *, struct block **, uint16_t *);
380 void tcpstart(struct conv *, int);
381 void tcptimeout(void *);
382 void tcpsndsyn(struct conv *, Tcpctl *);
383 void tcprcvwin(struct conv *);
384 void tcpacktimer(void *);
385 void tcpkeepalive(void *);
386 void tcpsetkacounter(Tcpctl *);
387 void tcprxmit(struct conv *);
388 void tcpsettimer(Tcpctl *);
389 void tcpsynackrtt(struct conv *);
390 void tcpsetscale(struct conv *, Tcpctl *, uint16_t, uint16_t);
391
392 static void limborexmit(struct Proto *);
393 static void limbo(struct conv *, uint8_t * unused_uint8_p_t, uint8_t *, Tcp *,
394                                   int);
395
396 void tcpsetstate(struct conv *s, uint8_t newstate)
397 {
398         Tcpctl *tcb;
399         uint8_t oldstate;
400         struct tcppriv *tpriv;
401
402         tpriv = s->p->priv;
403
404         tcb = (Tcpctl *) s->ptcl;
405
406         oldstate = tcb->state;
407         if (oldstate == newstate)
408                 return;
409
410         if (oldstate == Established)
411                 tpriv->stats[CurrEstab]--;
412         if (newstate == Established)
413                 tpriv->stats[CurrEstab]++;
414
415         /**
416         print( "%d/%d %s->%s CurrEstab=%d\n", s->lport, s->rport,
417                 tcpstates[oldstate], tcpstates[newstate], tpriv->tstats.tcpCurrEstab );
418         **/
419
420         switch (newstate) {
421                 case Closed:
422                         qclose(s->rq);
423                         qclose(s->wq);
424                         qclose(s->eq);
425                         break;
426
427                 case Close_wait:        /* Remote closes */
428                         qhangup(s->rq, NULL);
429                         break;
430         }
431
432         tcb->state = newstate;
433
434         if (oldstate == Syn_sent && newstate != Closed)
435                 Fsconnected(s, NULL);
436 }
437
438 static char *tcpconnect(struct conv *c, char **argv, int argc)
439 {
440         char *e;
441
442         e = Fsstdconnect(c, argv, argc);
443         if (e != NULL)
444                 return e;
445         tcpstart(c, TCP_CONNECT);
446
447         return NULL;
448 }
449
450 static int tcpstate(struct conv *c, char *state, int n)
451 {
452         Tcpctl *s;
453
454         s = (Tcpctl *) (c->ptcl);
455
456         return snprintf(state, n,
457                                         "%s qin %d qout %d srtt %d mdev %d cwin %lu swin %lu>>%d rwin %lu>>%d timer.start %d timer.count %d rerecv %d katimer.start %d katimer.count %d\n",
458                                         tcpstates[s->state],
459                                         c->rq ? qlen(c->rq) : 0,
460                                         c->wq ? qlen(c->wq) : 0,
461                                         s->srtt, s->mdev,
462                                         s->cwind, s->snd.wnd, s->rcv.scale, s->rcv.wnd,
463                                         s->snd.scale, s->timer.start, s->timer.count, s->rerecv,
464                                         s->katimer.start, s->katimer.count);
465 }
466
467 static int tcpinuse(struct conv *c)
468 {
469         Tcpctl *s;
470
471         s = (Tcpctl *) (c->ptcl);
472         return s->state != Closed;
473 }
474
475 static char *tcpannounce(struct conv *c, char **argv, int argc)
476 {
477         char *e;
478
479         e = Fsstdannounce(c, argv, argc);
480         if (e != NULL)
481                 return e;
482         tcpstart(c, TCP_LISTEN);
483         Fsconnected(c, NULL);
484
485         return NULL;
486 }
487
488 /*
489  *  tcpclose is always called with the q locked
490  */
491 static void tcpclose(struct conv *c)
492 {
493         Tcpctl *tcb;
494
495         tcb = (Tcpctl *) c->ptcl;
496
497         qhangup(c->rq, NULL);
498         qhangup(c->wq, NULL);
499         qhangup(c->eq, NULL);
500         qflush(c->rq);
501
502         switch (tcb->state) {
503                 case Listen:
504                         /*
505                          *  reset any incoming calls to this listener
506                          */
507                         Fsconnected(c, "Hangup");
508
509                         localclose(c, NULL);
510                         break;
511                 case Closed:
512                 case Syn_sent:
513                         localclose(c, NULL);
514                         break;
515                 case Syn_received:
516                 case Established:
517                         tcb->flgcnt++;
518                         tcb->snd.nxt++;
519                         tcpsetstate(c, Finwait1);
520                         tcpoutput(c);
521                         break;
522                 case Close_wait:
523                         tcb->flgcnt++;
524                         tcb->snd.nxt++;
525                         tcpsetstate(c, Last_ack);
526                         tcpoutput(c);
527                         break;
528         }
529 }
530
531 void tcpkick(void *x)
532 {
533         ERRSTACK(1);
534         struct conv *s = x;
535         Tcpctl *tcb;
536
537         tcb = (Tcpctl *) s->ptcl;
538
539         if (waserror()) {
540                 qunlock(&s->qlock);
541                 nexterror();
542         }
543         qlock(&s->qlock);
544
545         switch (tcb->state) {
546                 case Syn_sent:
547                 case Syn_received:
548                 case Established:
549                 case Close_wait:
550                         /*
551                          * Push data
552                          */
553                         tcprcvwin(s);
554                         tcpoutput(s);
555                         break;
556                 default:
557                         localclose(s, "Hangup");
558                         break;
559         }
560
561         qunlock(&s->qlock);
562         poperror();
563 }
564
565 void tcprcvwin(struct conv *s)
566 {       /* Call with tcb locked */
567         int w;
568         Tcpctl *tcb;
569
570         tcb = (Tcpctl *) s->ptcl;
571         w = tcb->window - qlen(s->rq);
572         if (w < 0)
573                 w = 0;
574         tcb->rcv.wnd = w;
575         if (w == 0)
576                 tcb->rcv.blocked = 1;
577 }
578
579 void tcpacktimer(void *v)
580 {
581         ERRSTACK(1);
582         Tcpctl *tcb;
583         struct conv *s;
584
585         s = v;
586         tcb = (Tcpctl *) s->ptcl;
587
588         if (waserror()) {
589                 qunlock(&s->qlock);
590                 nexterror();
591         }
592         qlock(&s->qlock);
593         if (tcb->state != Closed) {
594                 tcb->flags |= FORCE;
595                 tcprcvwin(s);
596                 tcpoutput(s);
597         }
598         qunlock(&s->qlock);
599         poperror();
600 }
601
602 static void tcpcreate(struct conv *c)
603 {
604         c->rq = qopen(QMAX, Qcoalesce, tcpacktimer, c);
605         c->wq = qopen((3 * QMAX) / 2, Qkick, tcpkick, c);
606 }
607
608 static void timerstate(struct tcppriv *priv, Tcptimer * t, int newstate)
609 {
610         if (newstate != TcptimerON) {
611                 if (t->state == TcptimerON) {
612                         // unchain
613                         if (priv->timers == t) {
614                                 priv->timers = t->next;
615                                 if (t->prev != NULL)
616                                         panic("timerstate1");
617                         }
618                         if (t->next)
619                                 t->next->prev = t->prev;
620                         if (t->prev)
621                                 t->prev->next = t->next;
622                         t->next = t->prev = NULL;
623                 }
624         } else {
625                 if (t->state != TcptimerON) {
626                         // chain
627                         if (t->prev != NULL || t->next != NULL)
628                                 panic("timerstate2");
629                         t->prev = NULL;
630                         t->next = priv->timers;
631                         if (t->next)
632                                 t->next->prev = t;
633                         priv->timers = t;
634                 }
635         }
636         t->state = newstate;
637 }
638
639 void tcpackproc(void *a)
640 {
641         ERRSTACK(1);
642         Tcptimer *t, *tp, *timeo;
643         struct Proto *tcp;
644         struct tcppriv *priv;
645         int loop;
646
647         tcp = a;
648         priv = tcp->priv;
649
650         for (;;) {
651                 udelay_sched(MSPTICK * 1000);
652
653                 qlock(&priv->tl);
654                 timeo = NULL;
655                 loop = 0;
656                 for (t = priv->timers; t != NULL; t = tp) {
657                         if (loop++ > 10000)
658                                 panic("tcpackproc1");
659                         tp = t->next;
660                         if (t->state == TcptimerON) {
661                                 t->count--;
662                                 if (t->count == 0) {
663                                         timerstate(priv, t, TcptimerDONE);
664                                         t->readynext = timeo;
665                                         timeo = t;
666                                 }
667                         }
668                 }
669                 qunlock(&priv->tl);
670
671                 loop = 0;
672                 for (t = timeo; t != NULL; t = t->readynext) {
673                         if (loop++ > 10000)
674                                 panic("tcpackproc2");
675                         if (t->state == TcptimerDONE && t->func != NULL) {
676                                 /* discard error style */
677                                 if (!waserror())
678                                         (*t->func) (t->arg);
679                                 poperror();
680                         }
681                 }
682
683                 limborexmit(tcp);
684         }
685 }
686
687 void tcpgo(struct tcppriv *priv, Tcptimer * t)
688 {
689         if (t == NULL || t->start == 0)
690                 return;
691
692         qlock(&priv->tl);
693         t->count = t->start;
694         timerstate(priv, t, TcptimerON);
695         qunlock(&priv->tl);
696 }
697
698 void tcphalt(struct tcppriv *priv, Tcptimer * t)
699 {
700         if (t == NULL)
701                 return;
702
703         qlock(&priv->tl);
704         timerstate(priv, t, TcptimerOFF);
705         qunlock(&priv->tl);
706 }
707
708 int backoff(int n)
709 {
710         return 1 << n;
711 }
712
713 void localclose(struct conv *s, char *reason)
714 {       /* called with tcb locked */
715         Tcpctl *tcb;
716         Reseq *rp, *rp1;
717         struct tcppriv *tpriv;
718
719         tpriv = s->p->priv;
720         tcb = (Tcpctl *) s->ptcl;
721
722         iphtrem(&tpriv->ht, s);
723
724         tcphalt(tpriv, &tcb->timer);
725         tcphalt(tpriv, &tcb->rtt_timer);
726         tcphalt(tpriv, &tcb->acktimer);
727         tcphalt(tpriv, &tcb->katimer);
728
729         /* Flush reassembly queue; nothing more can arrive */
730         for (rp = tcb->reseq; rp != NULL; rp = rp1) {
731                 rp1 = rp->next;
732                 freeblist(rp->bp);
733                 kfree(rp);
734         }
735         tcb->reseq = NULL;
736
737         if (tcb->state == Syn_sent)
738                 Fsconnected(s, reason);
739
740         qhangup(s->rq, reason);
741         qhangup(s->wq, reason);
742
743         tcpsetstate(s, Closed);
744
745         /* listener will check the rq state */
746         if (s->state == Announced)
747                 rendez_wakeup(&s->listenr);
748 }
749
750 /* mtu (- TCP + IP hdr len) of 1st hop */
751 int tcpmtu(struct Proto *tcp, uint8_t * addr, int version, int *scale)
752 {
753         struct Ipifc *ifc;
754         int mtu;
755
756         ifc = findipifc(tcp->f, addr, 0);
757         switch (version) {
758                 default:
759                 case V4:
760                         mtu = DEF_MSS;
761                         if (ifc != NULL)
762                                 mtu = ifc->maxtu - ifc->m->hsize - (TCP4_PKT + TCP4_HDRSIZE);
763                         break;
764                 case V6:
765                         mtu = DEF_MSS6;
766                         if (ifc != NULL)
767                                 mtu = ifc->maxtu - ifc->m->hsize - (TCP6_PKT + TCP6_HDRSIZE);
768                         break;
769         }
770         if (ifc != NULL) {
771                 if (ifc->mbps > 100)
772                         *scale = HaveWS | 3;
773                 else if (ifc->mbps > 10)
774                         *scale = HaveWS | 1;
775                 else
776                         *scale = HaveWS | 0;
777         } else
778                 *scale = HaveWS | 0;
779
780         return mtu;
781 }
782
783 void inittcpctl(struct conv *s, int mode)
784 {
785         Tcpctl *tcb;
786         Tcp4hdr *h4;
787         Tcp6hdr *h6;
788         int mss;
789
790         tcb = (Tcpctl *) s->ptcl;
791
792         memset(tcb, 0, sizeof(Tcpctl));
793
794         tcb->ssthresh = 65535;
795         tcb->srtt = tcp_irtt << LOGAGAIN;
796         tcb->mdev = 0;
797
798         /* setup timers */
799         tcb->timer.start = tcp_irtt / MSPTICK;
800         tcb->timer.func = tcptimeout;
801         tcb->timer.arg = s;
802         tcb->rtt_timer.start = MAX_TIME;
803         tcb->acktimer.start = TCP_ACK / MSPTICK;
804         tcb->acktimer.func = tcpacktimer;
805         tcb->acktimer.arg = s;
806         tcb->katimer.start = DEF_KAT / MSPTICK;
807         tcb->katimer.func = tcpkeepalive;
808         tcb->katimer.arg = s;
809
810         mss = DEF_MSS;
811
812         /* create a prototype(pseudo) header */
813         if (mode != TCP_LISTEN) {
814                 if (ipcmp(s->laddr, IPnoaddr) == 0)
815                         findlocalip(s->p->f, s->laddr, s->raddr);
816
817                 switch (s->ipversion) {
818                         case V4:
819                                 h4 = &tcb->protohdr.tcp4hdr;
820                                 memset(h4, 0, sizeof(*h4));
821                                 h4->proto = IP_TCPPROTO;
822                                 hnputs(h4->tcpsport, s->lport);
823                                 hnputs(h4->tcpdport, s->rport);
824                                 v6tov4(h4->tcpsrc, s->laddr);
825                                 v6tov4(h4->tcpdst, s->raddr);
826                                 break;
827                         case V6:
828                                 h6 = &tcb->protohdr.tcp6hdr;
829                                 memset(h6, 0, sizeof(*h6));
830                                 h6->proto = IP_TCPPROTO;
831                                 hnputs(h6->tcpsport, s->lport);
832                                 hnputs(h6->tcpdport, s->rport);
833                                 ipmove(h6->tcpsrc, s->laddr);
834                                 ipmove(h6->tcpdst, s->raddr);
835                                 mss = DEF_MSS6;
836                                 break;
837                         default:
838                                 panic("inittcpctl: version %d", s->ipversion);
839                 }
840         }
841
842         tcb->mss = tcb->cwind = mss;
843
844         /* default is no window scaling */
845         tcb->window = QMAX;
846         tcb->rcv.wnd = QMAX;
847         tcb->rcv.scale = 0;
848         tcb->snd.scale = 0;
849         qsetlimit(s->rq, QMAX);
850 }
851
852 /*
853  *  called with s qlocked
854  */
855 void tcpstart(struct conv *s, int mode)
856 {
857         Tcpctl *tcb;
858         struct tcppriv *tpriv;
859         /* tcpackproc needs to free this if it ever exits */
860         char *kpname = kmalloc(KNAMELEN, KMALLOC_WAIT);
861
862         tpriv = s->p->priv;
863
864         if (tpriv->ackprocstarted == 0) {
865                 qlock(&tpriv->apl);
866                 if (tpriv->ackprocstarted == 0) {
867                         snprintf(kpname, KNAMELEN, "#I%dtcpack", s->p->f->dev);
868                         ktask(kpname, tcpackproc, s->p);
869                         tpriv->ackprocstarted = 1;
870                 }
871                 qunlock(&tpriv->apl);
872         }
873
874         tcb = (Tcpctl *) s->ptcl;
875
876         inittcpctl(s, mode);
877
878         iphtadd(&tpriv->ht, s);
879         switch (mode) {
880                 case TCP_LISTEN:
881                         tpriv->stats[PassiveOpens]++;
882                         tcb->flags |= CLONE;
883                         tcpsetstate(s, Listen);
884                         break;
885
886                 case TCP_CONNECT:
887                         tpriv->stats[ActiveOpens]++;
888                         tcb->flags |= ACTIVE;
889                         tcpsndsyn(s, tcb);
890                         tcpsetstate(s, Syn_sent);
891                         tcpoutput(s);
892                         break;
893         }
894 }
895
896 static char *tcpflag(uint16_t flag)
897 {
898         static char buf[128];
899
900         snprintf(buf, sizeof(buf), "%d", flag >> 10);   /* Head len */
901         if (flag & URG)
902                 snprintf(buf, sizeof(buf), "%s%s", buf, " URG");
903         if (flag & ACK)
904                 snprintf(buf, sizeof(buf), "%s%s", buf, " ACK");
905         if (flag & PSH)
906                 snprintf(buf, sizeof(buf), "%s%s", buf, " PSH");
907         if (flag & RST)
908                 snprintf(buf, sizeof(buf), "%s%s", buf, " RST");
909         if (flag & SYN)
910                 snprintf(buf, sizeof(buf), "%s%s", buf, " SYN");
911         if (flag & FIN)
912                 snprintf(buf, sizeof(buf), "%s%s", buf, " FIN");
913
914         return buf;
915 }
916
917 struct block *htontcp6(Tcp * tcph, struct block *data, Tcp6hdr * ph,
918                                            Tcpctl * tcb)
919 {
920         int dlen;
921         Tcp6hdr *h;
922         uint16_t csum;
923         uint16_t hdrlen, optpad = 0;
924         uint8_t *opt;
925
926         hdrlen = TCP6_HDRSIZE;
927         if (tcph->flags & SYN) {
928                 if (tcph->mss)
929                         hdrlen += MSS_LENGTH;
930                 if (tcph->ws)
931                         hdrlen += WS_LENGTH;
932                 optpad = hdrlen & 3;
933                 if (optpad)
934                         optpad = 4 - optpad;
935                 hdrlen += optpad;
936         }
937
938         if (data) {
939                 dlen = blocklen(data);
940                 data = padblock(data, hdrlen + TCP6_PKT);
941                 if (data == NULL)
942                         return NULL;
943         } else {
944                 dlen = 0;
945                 data = allocb(hdrlen + TCP6_PKT + 64);  /* the 64 pad is to meet mintu's */
946                 if (data == NULL)
947                         return NULL;
948                 data->wp += hdrlen + TCP6_PKT;
949         }
950
951         /* copy in pseudo ip header plus port numbers */
952         h = (Tcp6hdr *) (data->rp);
953         memmove(h, ph, TCP6_TCBPHDRSZ);
954
955         /* compose pseudo tcp header, do cksum calculation */
956         hnputl(h->vcf, hdrlen + dlen);
957         h->ploadlen[0] = h->ploadlen[1] = h->proto = 0;
958         h->ttl = ph->proto;
959
960         /* copy in variable bits */
961         hnputl(h->tcpseq, tcph->seq);
962         hnputl(h->tcpack, tcph->ack);
963         hnputs(h->tcpflag, (hdrlen << 10) | tcph->flags);
964         hnputs(h->tcpwin, tcph->wnd >> (tcb != NULL ? tcb->snd.scale : 0));
965         hnputs(h->tcpurg, tcph->urg);
966
967         if (tcph->flags & SYN) {
968                 opt = h->tcpopt;
969                 if (tcph->mss != 0) {
970                         *opt++ = MSSOPT;
971                         *opt++ = MSS_LENGTH;
972                         hnputs(opt, tcph->mss);
973                         opt += 2;
974                 }
975                 if (tcph->ws != 0) {
976                         *opt++ = WSOPT;
977                         *opt++ = WS_LENGTH;
978                         *opt++ = tcph->ws;
979                 }
980                 while (optpad-- > 0)
981                         *opt++ = NOOPOPT;
982         }
983
984         if (tcb != NULL && tcb->nochecksum) {
985                 h->tcpcksum[0] = h->tcpcksum[1] = 0;
986         } else {
987                 csum = ptclcsum(data, TCP6_IPLEN, hdrlen + dlen + TCP6_PHDRSIZE);
988                 hnputs(h->tcpcksum, csum);
989         }
990
991         /* move from pseudo header back to normal ip header */
992         memset(h->vcf, 0, 4);
993         h->vcf[0] = IP_VER6;
994         hnputs(h->ploadlen, hdrlen + dlen);
995         h->proto = ph->proto;
996
997         return data;
998 }
999
1000 struct block *htontcp4(Tcp * tcph, struct block *data, Tcp4hdr * ph,
1001                                            Tcpctl * tcb)
1002 {
1003         int dlen;
1004         Tcp4hdr *h;
1005         uint16_t csum;
1006         uint16_t hdrlen, optpad = 0;
1007         uint8_t *opt;
1008
1009         hdrlen = TCP4_HDRSIZE;
1010         if (tcph->flags & SYN) {
1011                 if (tcph->mss)
1012                         hdrlen += MSS_LENGTH;
1013                 if (tcph->ws)
1014                         hdrlen += WS_LENGTH;
1015                 optpad = hdrlen & 3;
1016                 if (optpad)
1017                         optpad = 4 - optpad;
1018                 hdrlen += optpad;
1019         }
1020
1021         if (data) {
1022                 dlen = blocklen(data);
1023                 data = padblock(data, hdrlen + TCP4_PKT);
1024                 if (data == NULL)
1025                         return NULL;
1026         } else {
1027                 dlen = 0;
1028                 data = allocb(hdrlen + TCP4_PKT + 64);  /* the 64 pad is to meet mintu's */
1029                 if (data == NULL)
1030                         return NULL;
1031                 data->wp += hdrlen + TCP4_PKT;
1032         }
1033
1034         /* copy in pseudo ip header plus port numbers */
1035         h = (Tcp4hdr *) (data->rp);
1036         memmove(h, ph, TCP4_TCBPHDRSZ);
1037
1038         /* copy in variable bits */
1039         hnputs(h->tcplen, hdrlen + dlen);
1040         hnputl(h->tcpseq, tcph->seq);
1041         hnputl(h->tcpack, tcph->ack);
1042         hnputs(h->tcpflag, (hdrlen << 10) | tcph->flags);
1043         hnputs(h->tcpwin, tcph->wnd >> (tcb != NULL ? tcb->snd.scale : 0));
1044         hnputs(h->tcpurg, tcph->urg);
1045
1046         if (tcph->flags & SYN) {
1047                 opt = h->tcpopt;
1048                 if (tcph->mss != 0) {
1049                         *opt++ = MSSOPT;
1050                         *opt++ = MSS_LENGTH;
1051                         hnputs(opt, tcph->mss);
1052                         opt += 2;
1053                 }
1054                 if (tcph->ws != 0) {
1055                         *opt++ = WSOPT;
1056                         *opt++ = WS_LENGTH;
1057                         *opt++ = tcph->ws;
1058                 }
1059                 while (optpad-- > 0)
1060                         *opt++ = NOOPOPT;
1061         }
1062
1063         if (tcb != NULL && tcb->nochecksum) {
1064                 h->tcpcksum[0] = h->tcpcksum[1] = 0;
1065         } else {
1066                 csum = ptclcsum(data, TCP4_IPLEN, hdrlen + dlen + TCP4_PHDRSIZE);
1067                 hnputs(h->tcpcksum, csum);
1068         }
1069
1070         return data;
1071 }
1072
1073 int ntohtcp6(Tcp * tcph, struct block **bpp)
1074 {
1075         Tcp6hdr *h;
1076         uint8_t *optr;
1077         uint16_t hdrlen;
1078         uint16_t optlen;
1079         int n;
1080
1081         *bpp = pullupblock(*bpp, TCP6_PKT + TCP6_HDRSIZE);
1082         if (*bpp == NULL)
1083                 return -1;
1084
1085         h = (Tcp6hdr *) ((*bpp)->rp);
1086         tcph->source = nhgets(h->tcpsport);
1087         tcph->dest = nhgets(h->tcpdport);
1088         tcph->seq = nhgetl(h->tcpseq);
1089         tcph->ack = nhgetl(h->tcpack);
1090         hdrlen = (h->tcpflag[0] >> 2) & ~3;
1091         if (hdrlen < TCP6_HDRSIZE) {
1092                 freeblist(*bpp);
1093                 return -1;
1094         }
1095
1096         tcph->flags = h->tcpflag[1];
1097         tcph->wnd = nhgets(h->tcpwin);
1098         tcph->urg = nhgets(h->tcpurg);
1099         tcph->mss = 0;
1100         tcph->ws = 0;
1101         tcph->len = nhgets(h->ploadlen) - hdrlen;
1102
1103         *bpp = pullupblock(*bpp, hdrlen + TCP6_PKT);
1104         if (*bpp == NULL)
1105                 return -1;
1106
1107         optr = h->tcpopt;
1108         n = hdrlen - TCP6_HDRSIZE;
1109         while (n > 0 && *optr != EOLOPT) {
1110                 if (*optr == NOOPOPT) {
1111                         n--;
1112                         optr++;
1113                         continue;
1114                 }
1115                 optlen = optr[1];
1116                 if (optlen < 2 || optlen > n)
1117                         break;
1118                 switch (*optr) {
1119                         case MSSOPT:
1120                                 if (optlen == MSS_LENGTH)
1121                                         tcph->mss = nhgets(optr + 2);
1122                                 break;
1123                         case WSOPT:
1124                                 if (optlen == WS_LENGTH && *(optr + 2) <= 14)
1125                                         tcph->ws = HaveWS | *(optr + 2);
1126                                 break;
1127                 }
1128                 n -= optlen;
1129                 optr += optlen;
1130         }
1131         return hdrlen;
1132 }
1133
1134 int ntohtcp4(Tcp * tcph, struct block **bpp)
1135 {
1136         Tcp4hdr *h;
1137         uint8_t *optr;
1138         uint16_t hdrlen;
1139         uint16_t optlen;
1140         int n;
1141
1142         *bpp = pullupblock(*bpp, TCP4_PKT + TCP4_HDRSIZE);
1143         if (*bpp == NULL)
1144                 return -1;
1145
1146         h = (Tcp4hdr *) ((*bpp)->rp);
1147         tcph->source = nhgets(h->tcpsport);
1148         tcph->dest = nhgets(h->tcpdport);
1149         tcph->seq = nhgetl(h->tcpseq);
1150         tcph->ack = nhgetl(h->tcpack);
1151
1152         hdrlen = (h->tcpflag[0] >> 2) & ~3;
1153         if (hdrlen < TCP4_HDRSIZE) {
1154                 freeblist(*bpp);
1155                 return -1;
1156         }
1157
1158         tcph->flags = h->tcpflag[1];
1159         tcph->wnd = nhgets(h->tcpwin);
1160         tcph->urg = nhgets(h->tcpurg);
1161         tcph->mss = 0;
1162         tcph->ws = 0;
1163         tcph->len = nhgets(h->length) - (hdrlen + TCP4_PKT);
1164
1165         *bpp = pullupblock(*bpp, hdrlen + TCP4_PKT);
1166         if (*bpp == NULL)
1167                 return -1;
1168
1169         optr = h->tcpopt;
1170         n = hdrlen - TCP4_HDRSIZE;
1171         while (n > 0 && *optr != EOLOPT) {
1172                 if (*optr == NOOPOPT) {
1173                         n--;
1174                         optr++;
1175                         continue;
1176                 }
1177                 optlen = optr[1];
1178                 if (optlen < 2 || optlen > n)
1179                         break;
1180                 switch (*optr) {
1181                         case MSSOPT:
1182                                 if (optlen == MSS_LENGTH)
1183                                         tcph->mss = nhgets(optr + 2);
1184                                 break;
1185                         case WSOPT:
1186                                 if (optlen == WS_LENGTH && *(optr + 2) <= 14)
1187                                         tcph->ws = HaveWS | *(optr + 2);
1188                                 break;
1189                 }
1190                 n -= optlen;
1191                 optr += optlen;
1192         }
1193         return hdrlen;
1194 }
1195
1196 /*
1197  *  For outgiing calls, generate an initial sequence
1198  *  number and put a SYN on the send queue
1199  */
1200 void tcpsndsyn(struct conv *s, Tcpctl * tcb)
1201 {
1202         tcb->iss = (nrand(1 << 16) << 16) | nrand(1 << 16);
1203         tcb->rttseq = tcb->iss;
1204         tcb->snd.wl2 = tcb->iss;
1205         tcb->snd.una = tcb->iss;
1206         tcb->snd.ptr = tcb->rttseq;
1207         tcb->snd.nxt = tcb->rttseq;
1208         tcb->flgcnt++;
1209         tcb->flags |= FORCE;
1210         tcb->sndsyntime = NOW;
1211
1212         /* set desired mss and scale */
1213         tcb->mss = tcpmtu(s->p, s->laddr, s->ipversion, &tcb->scale);
1214 }
1215
1216 void
1217 sndrst(struct Proto *tcp, uint8_t * source, uint8_t * dest,
1218            uint16_t length, Tcp * seg, uint8_t version, char *reason)
1219 {
1220         struct block *hbp;
1221         uint8_t rflags;
1222         struct tcppriv *tpriv;
1223         Tcp4hdr ph4;
1224         Tcp6hdr ph6;
1225
1226         netlog(tcp->f, Logtcp, "sndrst: %s", reason);
1227
1228         tpriv = tcp->priv;
1229
1230         if (seg->flags & RST)
1231                 return;
1232
1233         /* make pseudo header */
1234         switch (version) {
1235                 case V4:
1236                         memset(&ph4, 0, sizeof(ph4));
1237                         ph4.vihl = IP_VER4;
1238                         v6tov4(ph4.tcpsrc, dest);
1239                         v6tov4(ph4.tcpdst, source);
1240                         ph4.proto = IP_TCPPROTO;
1241                         hnputs(ph4.tcplen, TCP4_HDRSIZE);
1242                         hnputs(ph4.tcpsport, seg->dest);
1243                         hnputs(ph4.tcpdport, seg->source);
1244                         break;
1245                 case V6:
1246                         memset(&ph6, 0, sizeof(ph6));
1247                         ph6.vcf[0] = IP_VER6;
1248                         ipmove(ph6.tcpsrc, dest);
1249                         ipmove(ph6.tcpdst, source);
1250                         ph6.proto = IP_TCPPROTO;
1251                         hnputs(ph6.ploadlen, TCP6_HDRSIZE);
1252                         hnputs(ph6.tcpsport, seg->dest);
1253                         hnputs(ph6.tcpdport, seg->source);
1254                         break;
1255                 default:
1256                         panic("sndrst: version %d", version);
1257         }
1258
1259         tpriv->stats[OutRsts]++;
1260         rflags = RST;
1261
1262         /* convince the other end that this reset is in band */
1263         if (seg->flags & ACK) {
1264                 seg->seq = seg->ack;
1265                 seg->ack = 0;
1266         } else {
1267                 rflags |= ACK;
1268                 seg->ack = seg->seq;
1269                 seg->seq = 0;
1270                 if (seg->flags & SYN)
1271                         seg->ack++;
1272                 seg->ack += length;
1273                 if (seg->flags & FIN)
1274                         seg->ack++;
1275         }
1276         seg->flags = rflags;
1277         seg->wnd = 0;
1278         seg->urg = 0;
1279         seg->mss = 0;
1280         seg->ws = 0;
1281         switch (version) {
1282                 case V4:
1283                         hbp = htontcp4(seg, NULL, &ph4, NULL);
1284                         if (hbp == NULL)
1285                                 return;
1286                         ipoput4(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1287                         break;
1288                 case V6:
1289                         hbp = htontcp6(seg, NULL, &ph6, NULL);
1290                         if (hbp == NULL)
1291                                 return;
1292                         ipoput6(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1293                         break;
1294                 default:
1295                         panic("sndrst2: version %d", version);
1296         }
1297 }
1298
1299 /*
1300  *  send a reset to the remote side and close the conversation
1301  *  called with s qlocked
1302  */
1303 char *tcphangup(struct conv *s)
1304 {
1305         ERRSTACK(2);
1306         Tcp seg;
1307         Tcpctl *tcb;
1308         struct block *hbp;
1309
1310         tcb = (Tcpctl *) s->ptcl;
1311         if (waserror()) {
1312                 poperror();
1313                 return commonerror();
1314         }
1315         if (ipcmp(s->raddr, IPnoaddr)) {
1316                 /* discard error style, poperror regardless */
1317                 if (!waserror()) {
1318                         seg.flags = RST | ACK;
1319                         seg.ack = tcb->rcv.nxt;
1320                         tcb->rcv.una = 0;
1321                         seg.seq = tcb->snd.ptr;
1322                         seg.wnd = 0;
1323                         seg.urg = 0;
1324                         seg.mss = 0;
1325                         seg.ws = 0;
1326                         switch (s->ipversion) {
1327                                 case V4:
1328                                         tcb->protohdr.tcp4hdr.vihl = IP_VER4;
1329                                         hbp = htontcp4(&seg, NULL, &tcb->protohdr.tcp4hdr, tcb);
1330                                         ipoput4(s->p->f, hbp, 0, s->ttl, s->tos, s);
1331                                         break;
1332                                 case V6:
1333                                         tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
1334                                         hbp = htontcp6(&seg, NULL, &tcb->protohdr.tcp6hdr, tcb);
1335                                         ipoput6(s->p->f, hbp, 0, s->ttl, s->tos, s);
1336                                         break;
1337                                 default:
1338                                         panic("tcphangup: version %d", s->ipversion);
1339                         }
1340                 }
1341                 poperror();
1342         }
1343         localclose(s, NULL);
1344         poperror();
1345         return NULL;
1346 }
1347
1348 /*
1349  *  (re)send a SYN ACK
1350  */
1351 int sndsynack(struct Proto *tcp, Limbo * lp)
1352 {
1353         struct block *hbp;
1354         Tcp4hdr ph4;
1355         Tcp6hdr ph6;
1356         Tcp seg;
1357         int scale;
1358
1359         /* make pseudo header */
1360         switch (lp->version) {
1361                 case V4:
1362                         memset(&ph4, 0, sizeof(ph4));
1363                         ph4.vihl = IP_VER4;
1364                         v6tov4(ph4.tcpsrc, lp->laddr);
1365                         v6tov4(ph4.tcpdst, lp->raddr);
1366                         ph4.proto = IP_TCPPROTO;
1367                         hnputs(ph4.tcplen, TCP4_HDRSIZE);
1368                         hnputs(ph4.tcpsport, lp->lport);
1369                         hnputs(ph4.tcpdport, lp->rport);
1370                         break;
1371                 case V6:
1372                         memset(&ph6, 0, sizeof(ph6));
1373                         ph6.vcf[0] = IP_VER6;
1374                         ipmove(ph6.tcpsrc, lp->laddr);
1375                         ipmove(ph6.tcpdst, lp->raddr);
1376                         ph6.proto = IP_TCPPROTO;
1377                         hnputs(ph6.ploadlen, TCP6_HDRSIZE);
1378                         hnputs(ph6.tcpsport, lp->lport);
1379                         hnputs(ph6.tcpdport, lp->rport);
1380                         break;
1381                 default:
1382                         panic("sndrst: version %d", lp->version);
1383         }
1384
1385         seg.seq = lp->iss;
1386         seg.ack = lp->irs + 1;
1387         seg.flags = SYN | ACK;
1388         seg.urg = 0;
1389         seg.mss = tcpmtu(tcp, lp->laddr, lp->version, &scale);
1390         seg.wnd = QMAX;
1391
1392         /* if the other side set scale, we should too */
1393         if (lp->rcvscale) {
1394                 seg.ws = scale;
1395                 lp->sndscale = scale;
1396         } else {
1397                 seg.ws = 0;
1398                 lp->sndscale = 0;
1399         }
1400
1401         switch (lp->version) {
1402                 case V4:
1403                         hbp = htontcp4(&seg, NULL, &ph4, NULL);
1404                         if (hbp == NULL)
1405                                 return -1;
1406                         ipoput4(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1407                         break;
1408                 case V6:
1409                         hbp = htontcp6(&seg, NULL, &ph6, NULL);
1410                         if (hbp == NULL)
1411                                 return -1;
1412                         ipoput6(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1413                         break;
1414                 default:
1415                         panic("sndsnack: version %d", lp->version);
1416         }
1417         lp->lastsend = NOW;
1418         return 0;
1419 }
1420
1421 #define hashipa(a, p) ( ( (a)[IPaddrlen-2] + (a)[IPaddrlen-1] + p )&LHTMASK )
1422
1423 /*
1424  *  put a call into limbo and respond with a SYN ACK
1425  *
1426  *  called with proto locked
1427  */
1428 static void
1429 limbo(struct conv *s, uint8_t * source, uint8_t * dest, Tcp * seg, int version)
1430 {
1431         Limbo *lp, **l;
1432         struct tcppriv *tpriv;
1433         int h;
1434
1435         tpriv = s->p->priv;
1436         h = hashipa(source, seg->source);
1437
1438         for (l = &tpriv->lht[h]; *l != NULL; l = &lp->next) {
1439                 lp = *l;
1440                 if (lp->lport != seg->dest || lp->rport != seg->source
1441                         || lp->version != version)
1442                         continue;
1443                 if (ipcmp(lp->raddr, source) != 0)
1444                         continue;
1445                 if (ipcmp(lp->laddr, dest) != 0)
1446                         continue;
1447
1448                 /* each new SYN restarts the retransmits */
1449                 lp->irs = seg->seq;
1450                 break;
1451         }
1452         lp = *l;
1453         if (lp == NULL) {
1454                 if (tpriv->nlimbo >= Maxlimbo && tpriv->lht[h]) {
1455                         lp = tpriv->lht[h];
1456                         tpriv->lht[h] = lp->next;
1457                         lp->next = NULL;
1458                 } else {
1459                         lp = kzmalloc(sizeof(*lp), 0);
1460                         if (lp == NULL)
1461                                 return;
1462                         tpriv->nlimbo++;
1463                 }
1464                 *l = lp;
1465                 lp->version = version;
1466                 ipmove(lp->laddr, dest);
1467                 ipmove(lp->raddr, source);
1468                 lp->lport = seg->dest;
1469                 lp->rport = seg->source;
1470                 lp->mss = seg->mss;
1471                 lp->rcvscale = seg->ws;
1472                 lp->irs = seg->seq;
1473                 lp->iss = (nrand(1 << 16) << 16) | nrand(1 << 16);
1474         }
1475
1476         if (sndsynack(s->p, lp) < 0) {
1477                 *l = lp->next;
1478                 tpriv->nlimbo--;
1479                 kfree(lp);
1480         }
1481 }
1482
1483 /*
1484  *  resend SYN ACK's once every SYNACK_RXTIMER ms.
1485  */
1486 static void limborexmit(struct Proto *tcp)
1487 {
1488         struct tcppriv *tpriv;
1489         Limbo **l, *lp;
1490         int h;
1491         int seen;
1492         uint32_t now;
1493
1494         tpriv = tcp->priv;
1495
1496         if (!canqlock(&tcp->qlock))
1497                 return;
1498         seen = 0;
1499         now = NOW;
1500         for (h = 0; h < NLHT && seen < tpriv->nlimbo; h++) {
1501                 for (l = &tpriv->lht[h]; *l != NULL && seen < tpriv->nlimbo;) {
1502                         lp = *l;
1503                         seen++;
1504                         if (now - lp->lastsend < (lp->rexmits + 1) * SYNACK_RXTIMER)
1505                                 continue;
1506
1507                         /* time it out after 1 second */
1508                         if (++(lp->rexmits) > 5) {
1509                                 tpriv->nlimbo--;
1510                                 *l = lp->next;
1511                                 kfree(lp);
1512                                 continue;
1513                         }
1514
1515                         /* if we're being attacked, don't bother resending SYN ACK's */
1516                         if (tpriv->nlimbo > 100)
1517                                 continue;
1518
1519                         if (sndsynack(tcp, lp) < 0) {
1520                                 tpriv->nlimbo--;
1521                                 *l = lp->next;
1522                                 kfree(lp);
1523                                 continue;
1524                         }
1525
1526                         l = &lp->next;
1527                 }
1528         }
1529         qunlock(&tcp->qlock);
1530 }
1531
1532 /*
1533  *  lookup call in limbo.  if found, throw it out.
1534  *
1535  *  called with proto locked
1536  */
1537 static void
1538 limborst(struct conv *s, Tcp * segp, uint8_t * src, uint8_t * dst,
1539                  uint8_t version)
1540 {
1541         Limbo *lp, **l;
1542         int h;
1543         struct tcppriv *tpriv;
1544
1545         tpriv = s->p->priv;
1546
1547         /* find a call in limbo */
1548         h = hashipa(src, segp->source);
1549         for (l = &tpriv->lht[h]; *l != NULL; l = &lp->next) {
1550                 lp = *l;
1551                 if (lp->lport != segp->dest || lp->rport != segp->source
1552                         || lp->version != version)
1553                         continue;
1554                 if (ipcmp(lp->laddr, dst) != 0)
1555                         continue;
1556                 if (ipcmp(lp->raddr, src) != 0)
1557                         continue;
1558
1559                 /* RST can only follow the SYN */
1560                 if (segp->seq == lp->irs + 1) {
1561                         tpriv->nlimbo--;
1562                         *l = lp->next;
1563                         kfree(lp);
1564                 }
1565                 break;
1566         }
1567 }
1568
1569 /*
1570  *  come here when we finally get an ACK to our SYN-ACK.
1571  *  lookup call in limbo.  if found, create a new conversation
1572  *
1573  *  called with proto locked
1574  */
1575 static struct conv *tcpincoming(struct conv *s, Tcp * segp, uint8_t * src,
1576                                                                 uint8_t * dst, uint8_t version)
1577 {
1578         struct conv *new;
1579         Tcpctl *tcb;
1580         struct tcppriv *tpriv;
1581         Tcp4hdr *h4;
1582         Tcp6hdr *h6;
1583         Limbo *lp, **l;
1584         int h;
1585
1586         /* unless it's just an ack, it can't be someone coming out of limbo */
1587         if ((segp->flags & SYN) || (segp->flags & ACK) == 0)
1588                 return NULL;
1589
1590         tpriv = s->p->priv;
1591
1592         /* find a call in limbo */
1593         h = hashipa(src, segp->source);
1594         for (l = &tpriv->lht[h]; (lp = *l) != NULL; l = &lp->next) {
1595                 netlog(s->p->f, Logtcp,
1596                            "tcpincoming s %I,0x%x/%I,0x%x d %I,0x%x/%I,0x%x v %d/%d", src,
1597                            segp->source, lp->raddr, lp->rport, dst, segp->dest, lp->laddr,
1598                            lp->lport, version, lp->version);
1599
1600                 if (lp->lport != segp->dest || lp->rport != segp->source
1601                         || lp->version != version)
1602                         continue;
1603                 if (ipcmp(lp->laddr, dst) != 0)
1604                         continue;
1605                 if (ipcmp(lp->raddr, src) != 0)
1606                         continue;
1607
1608                 /* we're assuming no data with the initial SYN */
1609                 if (segp->seq != lp->irs + 1 || segp->ack != lp->iss + 1) {
1610                         netlog(s->p->f, Logtcp, "tcpincoming s 0x%lx/0x%lx a 0x%lx 0x%lx",
1611                                    segp->seq, lp->irs + 1, segp->ack, lp->iss + 1);
1612                         lp = NULL;
1613                 } else {
1614                         tpriv->nlimbo--;
1615                         *l = lp->next;
1616                 }
1617                 break;
1618         }
1619         if (lp == NULL)
1620                 return NULL;
1621
1622         new = Fsnewcall(s, src, segp->source, dst, segp->dest, version);
1623         if (new == NULL)
1624                 return NULL;
1625
1626         memmove(new->ptcl, s->ptcl, sizeof(Tcpctl));
1627         tcb = (Tcpctl *) new->ptcl;
1628         tcb->flags &= ~CLONE;
1629         tcb->timer.arg = new;
1630         tcb->timer.state = TcptimerOFF;
1631         tcb->acktimer.arg = new;
1632         tcb->acktimer.state = TcptimerOFF;
1633         tcb->katimer.arg = new;
1634         tcb->katimer.state = TcptimerOFF;
1635         tcb->rtt_timer.arg = new;
1636         tcb->rtt_timer.state = TcptimerOFF;
1637
1638         tcb->irs = lp->irs;
1639         tcb->rcv.nxt = tcb->irs + 1;
1640         tcb->rcv.urg = tcb->rcv.nxt;
1641
1642         tcb->iss = lp->iss;
1643         tcb->rttseq = tcb->iss;
1644         tcb->snd.wl2 = tcb->iss;
1645         tcb->snd.una = tcb->iss + 1;
1646         tcb->snd.ptr = tcb->iss + 1;
1647         tcb->snd.nxt = tcb->iss + 1;
1648         tcb->flgcnt = 0;
1649         tcb->flags |= SYNACK;
1650
1651         /* our sending max segment size cannot be bigger than what he asked for */
1652         if (lp->mss != 0 && lp->mss < tcb->mss)
1653                 tcb->mss = lp->mss;
1654
1655         /* window scaling */
1656         tcpsetscale(new, tcb, lp->rcvscale, lp->sndscale);
1657
1658         /* the congestion window always starts out as a single segment */
1659         tcb->snd.wnd = segp->wnd;
1660         tcb->cwind = tcb->mss;
1661
1662         /* set initial round trip time */
1663         tcb->sndsyntime = lp->lastsend + lp->rexmits * SYNACK_RXTIMER;
1664         tcpsynackrtt(new);
1665
1666         kfree(lp);
1667
1668         /* set up proto header */
1669         switch (version) {
1670                 case V4:
1671                         h4 = &tcb->protohdr.tcp4hdr;
1672                         memset(h4, 0, sizeof(*h4));
1673                         h4->proto = IP_TCPPROTO;
1674                         hnputs(h4->tcpsport, new->lport);
1675                         hnputs(h4->tcpdport, new->rport);
1676                         v6tov4(h4->tcpsrc, dst);
1677                         v6tov4(h4->tcpdst, src);
1678                         break;
1679                 case V6:
1680                         h6 = &tcb->protohdr.tcp6hdr;
1681                         memset(h6, 0, sizeof(*h6));
1682                         h6->proto = IP_TCPPROTO;
1683                         hnputs(h6->tcpsport, new->lport);
1684                         hnputs(h6->tcpdport, new->rport);
1685                         ipmove(h6->tcpsrc, dst);
1686                         ipmove(h6->tcpdst, src);
1687                         break;
1688                 default:
1689                         panic("tcpincoming: version %d", new->ipversion);
1690         }
1691
1692         tcpsetstate(new, Established);
1693
1694         iphtadd(&tpriv->ht, new);
1695
1696         return new;
1697 }
1698
1699 int seq_within(uint32_t x, uint32_t low, uint32_t high)
1700 {
1701         if (low <= high) {
1702                 if (low <= x && x <= high)
1703                         return 1;
1704         } else {
1705                 if (x >= low || x <= high)
1706                         return 1;
1707         }
1708         return 0;
1709 }
1710
1711 int seq_lt(uint32_t x, uint32_t y)
1712 {
1713         return (int)(x - y) < 0;
1714 }
1715
1716 int seq_le(uint32_t x, uint32_t y)
1717 {
1718         return (int)(x - y) <= 0;
1719 }
1720
1721 int seq_gt(uint32_t x, uint32_t y)
1722 {
1723         return (int)(x - y) > 0;
1724 }
1725
1726 int seq_ge(uint32_t x, uint32_t y)
1727 {
1728         return (int)(x - y) >= 0;
1729 }
1730
1731 /*
1732  *  use the time between the first SYN and it's ack as the
1733  *  initial round trip time
1734  */
1735 void tcpsynackrtt(struct conv *s)
1736 {
1737         Tcpctl *tcb;
1738         int delta;
1739         struct tcppriv *tpriv;
1740
1741         tcb = (Tcpctl *) s->ptcl;
1742         tpriv = s->p->priv;
1743
1744         delta = NOW - tcb->sndsyntime;
1745         tcb->srtt = delta << LOGAGAIN;
1746         tcb->mdev = delta << LOGDGAIN;
1747
1748         /* halt round trip timer */
1749         tcphalt(tpriv, &tcb->rtt_timer);
1750 }
1751
1752 void update(struct conv *s, Tcp * seg)
1753 {
1754         int rtt, delta;
1755         Tcpctl *tcb;
1756         uint32_t acked;
1757         uint32_t expand;
1758         struct tcppriv *tpriv;
1759
1760         tpriv = s->p->priv;
1761         tcb = (Tcpctl *) s->ptcl;
1762
1763         /* if everything has been acked, force output(?) */
1764         if (seq_gt(seg->ack, tcb->snd.nxt)) {
1765                 tcb->flags |= FORCE;
1766                 return;
1767         }
1768
1769         /* added by Dong Lin for fast retransmission */
1770         if (seg->ack == tcb->snd.una
1771                 && tcb->snd.una != tcb->snd.nxt
1772                 && seg->len == 0 && seg->wnd == tcb->snd.wnd) {
1773
1774                 /* this is a pure ack w/o window update */
1775                 netlog(s->p->f, Logtcprxmt, "dupack %lu ack %lu sndwnd %d advwin %d\n",
1776                            tcb->snd.dupacks, seg->ack, tcb->snd.wnd, seg->wnd);
1777
1778                 if (++tcb->snd.dupacks == TCPREXMTTHRESH) {
1779                         /*
1780                          *  tahoe tcp rxt the packet, half sshthresh,
1781                          *  and set cwnd to one packet
1782                          */
1783                         tcb->snd.recovery = 1;
1784                         tcb->snd.rxt = tcb->snd.nxt;
1785                         netlog(s->p->f, Logtcprxmt, "fast rxt %lu, nxt %lu\n", tcb->snd.una,
1786                                    tcb->snd.nxt);
1787                         tcprxmit(s);
1788                 } else {
1789                         /* do reno tcp here. */
1790                 }
1791         }
1792
1793         /*
1794          *  update window
1795          */
1796         if (seq_gt(seg->ack, tcb->snd.wl2)
1797                 || (tcb->snd.wl2 == seg->ack && seg->wnd > tcb->snd.wnd)) {
1798                 tcb->snd.wnd = seg->wnd;
1799                 tcb->snd.wl2 = seg->ack;
1800         }
1801
1802         if (!seq_gt(seg->ack, tcb->snd.una)) {
1803                 /*
1804                  *  don't let us hangup if sending into a closed window and
1805                  *  we're still getting acks
1806                  */
1807                 if ((tcb->flags & RETRAN) && tcb->snd.wnd == 0) {
1808                         tcb->backedoff = MAXBACKMS / 4;
1809                 }
1810                 return;
1811         }
1812
1813         /*
1814          *  any positive ack turns off fast rxt,
1815          *  (should we do new-reno on partial acks?)
1816          */
1817         if (!tcb->snd.recovery || seq_ge(seg->ack, tcb->snd.rxt)) {
1818                 tcb->snd.dupacks = 0;
1819                 tcb->snd.recovery = 0;
1820         } else
1821                 netlog(s->p->f, Logtcp, "rxt next %lu, cwin %u\n", seg->ack,
1822                            tcb->cwind);
1823
1824         /* Compute the new send window size */
1825         acked = seg->ack - tcb->snd.una;
1826
1827         /* avoid slow start and timers for SYN acks */
1828         if ((tcb->flags & SYNACK) == 0) {
1829                 tcb->flags |= SYNACK;
1830                 acked--;
1831                 tcb->flgcnt--;
1832                 goto done;
1833         }
1834
1835         /* slow start as long as we're not recovering from lost packets */
1836         if (tcb->cwind < tcb->snd.wnd && !tcb->snd.recovery) {
1837                 if (tcb->cwind < tcb->ssthresh) {
1838                         expand = tcb->mss;
1839                         if (acked < expand)
1840                                 expand = acked;
1841                 } else
1842                         expand = ((int)tcb->mss * tcb->mss) / tcb->cwind;
1843
1844                 if (tcb->cwind + expand < tcb->cwind)
1845                         expand = tcb->snd.wnd - tcb->cwind;
1846                 if (tcb->cwind + expand > tcb->snd.wnd)
1847                         expand = tcb->snd.wnd - tcb->cwind;
1848                 tcb->cwind += expand;
1849         }
1850
1851         /* Adjust the timers according to the round trip time */
1852         if (tcb->rtt_timer.state == TcptimerON && seq_ge(seg->ack, tcb->rttseq)) {
1853                 tcphalt(tpriv, &tcb->rtt_timer);
1854                 if ((tcb->flags & RETRAN) == 0) {
1855                         tcb->backoff = 0;
1856                         tcb->backedoff = 0;
1857                         rtt = tcb->rtt_timer.start - tcb->rtt_timer.count;
1858                         if (rtt == 0)
1859                                 rtt = 1;        /* otherwise all close systems will rexmit in 0 time */
1860                         rtt *= MSPTICK;
1861                         if (tcb->srtt == 0) {
1862                                 tcb->srtt = rtt << LOGAGAIN;
1863                                 tcb->mdev = rtt << LOGDGAIN;
1864                         } else {
1865                                 delta = rtt - (tcb->srtt >> LOGAGAIN);
1866                                 tcb->srtt += delta;
1867                                 if (tcb->srtt <= 0)
1868                                         tcb->srtt = 1;
1869
1870                                 delta = abs(delta) - (tcb->mdev >> LOGDGAIN);
1871                                 tcb->mdev += delta;
1872                                 if (tcb->mdev <= 0)
1873                                         tcb->mdev = 1;
1874                         }
1875                         tcpsettimer(tcb);
1876                 }
1877         }
1878
1879 done:
1880         if (qdiscard(s->wq, acked) < acked)
1881                 tcb->flgcnt--;
1882
1883         tcb->snd.una = seg->ack;
1884         if (seq_gt(seg->ack, tcb->snd.urg))
1885                 tcb->snd.urg = seg->ack;
1886
1887         if (tcb->snd.una != tcb->snd.nxt)
1888                 tcpgo(tpriv, &tcb->timer);
1889         else
1890                 tcphalt(tpriv, &tcb->timer);
1891
1892         if (seq_lt(tcb->snd.ptr, tcb->snd.una))
1893                 tcb->snd.ptr = tcb->snd.una;
1894
1895         tcb->flags &= ~RETRAN;
1896         tcb->backoff = 0;
1897         tcb->backedoff = 0;
1898 }
1899
1900 void tcpiput(struct Proto *tcp, struct Ipifc *unused, struct block *bp)
1901 {
1902         ERRSTACK(1);
1903         Tcp seg;
1904         Tcp4hdr *h4;
1905         Tcp6hdr *h6;
1906         int hdrlen;
1907         Tcpctl *tcb;
1908         uint16_t length;
1909         uint8_t source[IPaddrlen], dest[IPaddrlen];
1910         struct conv *s;
1911         struct Fs *f;
1912         struct tcppriv *tpriv;
1913         uint8_t version;
1914
1915         f = tcp->f;
1916         tpriv = tcp->priv;
1917
1918         tpriv->stats[InSegs]++;
1919
1920         h4 = (Tcp4hdr *) (bp->rp);
1921         h6 = (Tcp6hdr *) (bp->rp);
1922
1923         if ((h4->vihl & 0xF0) == IP_VER4) {
1924                 version = V4;
1925                 length = nhgets(h4->length);
1926                 v4tov6(dest, h4->tcpdst);
1927                 v4tov6(source, h4->tcpsrc);
1928
1929                 h4->Unused = 0;
1930                 hnputs(h4->tcplen, length - TCP4_PKT);
1931                 if (!(bp->flag & Btcpck) && (h4->tcpcksum[0] || h4->tcpcksum[1]) &&
1932                         ptclcsum(bp, TCP4_IPLEN, length - TCP4_IPLEN)) {
1933                         tpriv->stats[CsumErrs]++;
1934                         tpriv->stats[InErrs]++;
1935                         netlog(f, Logtcp, "bad tcp proto cksum\n");
1936                         freeblist(bp);
1937                         return;
1938                 }
1939
1940                 hdrlen = ntohtcp4(&seg, &bp);
1941                 if (hdrlen < 0) {
1942                         tpriv->stats[HlenErrs]++;
1943                         tpriv->stats[InErrs]++;
1944                         netlog(f, Logtcp, "bad tcp hdr len\n");
1945                         return;
1946                 }
1947
1948                 /* trim the packet to the size claimed by the datagram */
1949                 length -= hdrlen + TCP4_PKT;
1950                 bp = trimblock(bp, hdrlen + TCP4_PKT, length);
1951                 if (bp == NULL) {
1952                         tpriv->stats[LenErrs]++;
1953                         tpriv->stats[InErrs]++;
1954                         netlog(f, Logtcp, "tcp len < 0 after trim\n");
1955                         return;
1956                 }
1957         } else {
1958                 int ttl = h6->ttl;
1959                 int proto = h6->proto;
1960
1961                 version = V6;
1962                 length = nhgets(h6->ploadlen);
1963                 ipmove(dest, h6->tcpdst);
1964                 ipmove(source, h6->tcpsrc);
1965
1966                 h6->ploadlen[0] = h6->ploadlen[1] = h6->proto = 0;
1967                 h6->ttl = proto;
1968                 hnputl(h6->vcf, length);
1969                 if ((h6->tcpcksum[0] || h6->tcpcksum[1]) &&
1970                         ptclcsum(bp, TCP6_IPLEN, length + TCP6_PHDRSIZE)) {
1971                         tpriv->stats[CsumErrs]++;
1972                         tpriv->stats[InErrs]++;
1973                         netlog(f, Logtcp, "bad tcp proto cksum\n");
1974                         freeblist(bp);
1975                         return;
1976                 }
1977                 h6->ttl = ttl;
1978                 h6->proto = proto;
1979                 hnputs(h6->ploadlen, length);
1980
1981                 hdrlen = ntohtcp6(&seg, &bp);
1982                 if (hdrlen < 0) {
1983                         tpriv->stats[HlenErrs]++;
1984                         tpriv->stats[InErrs]++;
1985                         netlog(f, Logtcp, "bad tcp hdr len\n");
1986                         return;
1987                 }
1988
1989                 /* trim the packet to the size claimed by the datagram */
1990                 length -= hdrlen;
1991                 bp = trimblock(bp, hdrlen + TCP6_PKT, length);
1992                 if (bp == NULL) {
1993                         tpriv->stats[LenErrs]++;
1994                         tpriv->stats[InErrs]++;
1995                         netlog(f, Logtcp, "tcp len < 0 after trim\n");
1996                         return;
1997                 }
1998         }
1999
2000         /* lock protocol while searching for a conversation */
2001         qlock(&tcp->qlock);
2002
2003         /* Look for a matching conversation */
2004         s = iphtlook(&tpriv->ht, source, seg.source, dest, seg.dest);
2005         if (s == NULL) {
2006                 netlog(f, Logtcp, "iphtlook failed");
2007 reset:
2008                 qunlock(&tcp->qlock);
2009                 sndrst(tcp, source, dest, length, &seg, version, "no conversation");
2010                 freeblist(bp);
2011                 return;
2012         }
2013
2014         /* if it's a listener, look for the right flags and get a new conv */
2015         tcb = (Tcpctl *) s->ptcl;
2016         if (tcb->state == Listen) {
2017                 if (seg.flags & RST) {
2018                         limborst(s, &seg, source, dest, version);
2019                         qunlock(&tcp->qlock);
2020                         freeblist(bp);
2021                         return;
2022                 }
2023
2024                 /* if this is a new SYN, put the call into limbo */
2025                 if ((seg.flags & SYN) && (seg.flags & ACK) == 0) {
2026                         limbo(s, source, dest, &seg, version);
2027                         qunlock(&tcp->qlock);
2028                         freeblist(bp);
2029                         return;
2030                 }
2031
2032                 /*
2033                  *  if there's a matching call in limbo, tcpincoming will
2034                  *  return it in state Syn_received
2035                  */
2036                 s = tcpincoming(s, &seg, source, dest, version);
2037                 if (s == NULL)
2038                         goto reset;
2039         }
2040
2041         /* The rest of the input state machine is run with the control block
2042          * locked and implements the state machine directly out of the RFC.
2043          * Out-of-band data is ignored - it was always a bad idea.
2044          */
2045         tcb = (Tcpctl *) s->ptcl;
2046         if (waserror()) {
2047                 qunlock(&s->qlock);
2048                 nexterror();
2049         }
2050         qlock(&s->qlock);
2051         qunlock(&tcp->qlock);
2052
2053         /* fix up window */
2054         seg.wnd <<= tcb->rcv.scale;
2055
2056         /* every input packet in puts off the keep alive time out */
2057         tcpsetkacounter(tcb);
2058
2059         switch (tcb->state) {
2060                 case Closed:
2061                         sndrst(tcp, source, dest, length, &seg, version,
2062                                    "sending to Closed");
2063                         goto raise;
2064                 case Syn_sent:
2065                         if (seg.flags & ACK) {
2066                                 if (!seq_within(seg.ack, tcb->iss + 1, tcb->snd.nxt)) {
2067                                         sndrst(tcp, source, dest, length, &seg, version,
2068                                                    "bad seq in Syn_sent");
2069                                         goto raise;
2070                                 }
2071                         }
2072                         if (seg.flags & RST) {
2073                                 if (seg.flags & ACK)
2074                                         localclose(s, Econrefused);
2075                                 goto raise;
2076                         }
2077
2078                         if (seg.flags & SYN) {
2079                                 procsyn(s, &seg);
2080                                 if (seg.flags & ACK) {
2081                                         update(s, &seg);
2082                                         tcpsynackrtt(s);
2083                                         tcpsetstate(s, Established);
2084                                         tcpsetscale(s, tcb, seg.ws, tcb->scale);
2085                                 } else {
2086                                         tcb->time = NOW;
2087                                         tcpsetstate(s, Syn_received);   /* DLP - shouldn't this be a reset? */
2088                                 }
2089
2090                                 if (length != 0 || (seg.flags & FIN))
2091                                         break;
2092
2093                                 freeblist(bp);
2094                                 goto output;
2095                         } else
2096                                 freeblist(bp);
2097
2098                         qunlock(&s->qlock);
2099                         poperror();
2100                         return;
2101                 case Syn_received:
2102                         /* doesn't matter if it's the correct ack, we're just trying to set timing */
2103                         if (seg.flags & ACK)
2104                                 tcpsynackrtt(s);
2105                         break;
2106         }
2107
2108         /*
2109          *  One DOS attack is to open connections to us and then forget about them,
2110          *  thereby tying up a conv at no long term cost to the attacker.
2111          *  This is an attempt to defeat these stateless DOS attacks.  See
2112          *  corresponding code in tcpsendka().
2113          */
2114         if (tcb->state != Syn_received && (seg.flags & RST) == 0) {
2115                 if (tcpporthogdefense
2116                         && seq_within(seg.ack, tcb->snd.una - (1 << 31),
2117                                                   tcb->snd.una - (1 << 29))) {
2118                         printd("stateless hog %I.%d->%I.%d f 0x%x 0x%lx - 0x%lx - 0x%lx\n",
2119                                    source, seg.source, dest, seg.dest, seg.flags,
2120                                    tcb->snd.una - (1 << 31), seg.ack, tcb->snd.una - (1 << 29));
2121                         localclose(s, "stateless hog");
2122                 }
2123         }
2124
2125         /* Cut the data to fit the receive window */
2126         if (tcptrim(tcb, &seg, &bp, &length) == -1) {
2127                 netlog(f, Logtcp, "tcp len < 0, %lu %d\n", seg.seq, length);
2128                 update(s, &seg);
2129                 if (qlen(s->wq) + tcb->flgcnt == 0 && tcb->state == Closing) {
2130                         tcphalt(tpriv, &tcb->rtt_timer);
2131                         tcphalt(tpriv, &tcb->acktimer);
2132                         tcphalt(tpriv, &tcb->katimer);
2133                         tcpsetstate(s, Time_wait);
2134                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2135                         tcpgo(tpriv, &tcb->timer);
2136                 }
2137                 if (!(seg.flags & RST)) {
2138                         tcb->flags |= FORCE;
2139                         goto output;
2140                 }
2141                 qunlock(&s->qlock);
2142                 poperror();
2143                 return;
2144         }
2145
2146         /* Cannot accept so answer with a rst */
2147         if (length && tcb->state == Closed) {
2148                 sndrst(tcp, source, dest, length, &seg, version, "sending to Closed");
2149                 goto raise;
2150         }
2151
2152         /* The segment is beyond the current receive pointer so
2153          * queue the data in the resequence queue
2154          */
2155         if (seg.seq != tcb->rcv.nxt)
2156                 if (length != 0 || (seg.flags & (SYN | FIN))) {
2157                         update(s, &seg);
2158                         if (addreseq(tcb, tpriv, &seg, bp, length) < 0)
2159                                 printd("reseq %I.%d -> %I.%d\n", s->raddr, s->rport, s->laddr,
2160                                            s->lport);
2161                         tcb->flags |= FORCE;
2162                         goto output;
2163                 }
2164
2165         /*
2166          *  keep looping till we've processed this packet plus any
2167          *  adjacent packets in the resequence queue
2168          */
2169         for (;;) {
2170                 if (seg.flags & RST) {
2171                         if (tcb->state == Established) {
2172                                 tpriv->stats[EstabResets]++;
2173                                 if (tcb->rcv.nxt != seg.seq)
2174                                         printd
2175                                                 ("out of order RST rcvd: %I.%d -> %I.%d, rcv.nxt 0x%lx seq 0x%lx\n",
2176                                                  s->raddr, s->rport, s->laddr, s->lport, tcb->rcv.nxt,
2177                                                  seg.seq);
2178                         }
2179                         localclose(s, Econrefused);
2180                         goto raise;
2181                 }
2182
2183                 if ((seg.flags & ACK) == 0)
2184                         goto raise;
2185
2186                 switch (tcb->state) {
2187                         case Syn_received:
2188                                 if (!seq_within(seg.ack, tcb->snd.una + 1, tcb->snd.nxt)) {
2189                                         sndrst(tcp, source, dest, length, &seg, version,
2190                                                    "bad seq in Syn_received");
2191                                         goto raise;
2192                                 }
2193                                 update(s, &seg);
2194                                 tcpsetstate(s, Established);
2195                         case Established:
2196                         case Close_wait:
2197                                 update(s, &seg);
2198                                 break;
2199                         case Finwait1:
2200                                 update(s, &seg);
2201                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2202                                         tcphalt(tpriv, &tcb->rtt_timer);
2203                                         tcphalt(tpriv, &tcb->acktimer);
2204                                         tcpsetkacounter(tcb);
2205                                         tcb->time = NOW;
2206                                         tcpsetstate(s, Finwait2);
2207                                         tcb->katimer.start = MSL2 * (1000 / MSPTICK);
2208                                         tcpgo(tpriv, &tcb->katimer);
2209                                 }
2210                                 break;
2211                         case Finwait2:
2212                                 update(s, &seg);
2213                                 break;
2214                         case Closing:
2215                                 update(s, &seg);
2216                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2217                                         tcphalt(tpriv, &tcb->rtt_timer);
2218                                         tcphalt(tpriv, &tcb->acktimer);
2219                                         tcphalt(tpriv, &tcb->katimer);
2220                                         tcpsetstate(s, Time_wait);
2221                                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2222                                         tcpgo(tpriv, &tcb->timer);
2223                                 }
2224                                 break;
2225                         case Last_ack:
2226                                 update(s, &seg);
2227                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2228                                         localclose(s, NULL);
2229                                         goto raise;
2230                                 }
2231                         case Time_wait:
2232                                 tcb->flags |= FORCE;
2233                                 if (tcb->timer.state != TcptimerON)
2234                                         tcpgo(tpriv, &tcb->timer);
2235                 }
2236
2237                 if ((seg.flags & URG) && seg.urg) {
2238                         if (seq_gt(seg.urg + seg.seq, tcb->rcv.urg)) {
2239                                 tcb->rcv.urg = seg.urg + seg.seq;
2240                                 pullblock(&bp, seg.urg);
2241                         }
2242                 } else if (seq_gt(tcb->rcv.nxt, tcb->rcv.urg))
2243                         tcb->rcv.urg = tcb->rcv.nxt;
2244
2245                 if (length == 0) {
2246                         if (bp != NULL)
2247                                 freeblist(bp);
2248                 } else {
2249                         switch (tcb->state) {
2250                                 default:
2251                                         /* Ignore segment text */
2252                                         if (bp != NULL)
2253                                                 freeblist(bp);
2254                                         break;
2255
2256                                 case Syn_received:
2257                                 case Established:
2258                                 case Finwait1:
2259                                         /* If we still have some data place on
2260                                          * receive queue
2261                                          */
2262                                         if (bp) {
2263                                                 bp = packblock(bp);
2264                                                 if (bp == NULL)
2265                                                         panic("tcp packblock");
2266                                                 qpassnolim(s->rq, bp);
2267                                                 bp = NULL;
2268
2269                                                 /*
2270                                                  *  Force an ack every 2 data messages.  This is
2271                                                  *  a hack for rob to make his home system run
2272                                                  *  faster.
2273                                                  *
2274                                                  *  this also keeps the standard TCP congestion
2275                                                  *  control working since it needs an ack every
2276                                                  *  2 max segs worth.  This is not quite that,
2277                                                  *  but under a real stream is equivalent since
2278                                                  *  every packet has a max seg in it.
2279                                                  */
2280                                                 if (++(tcb->rcv.una) >= 2)
2281                                                         tcb->flags |= FORCE;
2282                                         }
2283                                         tcb->rcv.nxt += length;
2284
2285                                         /*
2286                                          *  update our rcv window
2287                                          */
2288                                         tcprcvwin(s);
2289
2290                                         /*
2291                                          *  turn on the acktimer if there's something
2292                                          *  to ack
2293                                          */
2294                                         if (tcb->acktimer.state != TcptimerON)
2295                                                 tcpgo(tpriv, &tcb->acktimer);
2296
2297                                         break;
2298                                 case Finwait2:
2299                                         /* no process to read the data, send a reset */
2300                                         if (bp != NULL)
2301                                                 freeblist(bp);
2302                                         sndrst(tcp, source, dest, length, &seg, version,
2303                                                    "send to Finwait2");
2304                                         qunlock(&s->qlock);
2305                                         poperror();
2306                                         return;
2307                         }
2308                 }
2309
2310                 if (seg.flags & FIN) {
2311                         tcb->flags |= FORCE;
2312
2313                         switch (tcb->state) {
2314                                 case Syn_received:
2315                                 case Established:
2316                                         tcb->rcv.nxt++;
2317                                         tcpsetstate(s, Close_wait);
2318                                         break;
2319                                 case Finwait1:
2320                                         tcb->rcv.nxt++;
2321                                         if (qlen(s->wq) + tcb->flgcnt == 0) {
2322                                                 tcphalt(tpriv, &tcb->rtt_timer);
2323                                                 tcphalt(tpriv, &tcb->acktimer);
2324                                                 tcphalt(tpriv, &tcb->katimer);
2325                                                 tcpsetstate(s, Time_wait);
2326                                                 tcb->timer.start = MSL2 * (1000 / MSPTICK);
2327                                                 tcpgo(tpriv, &tcb->timer);
2328                                         } else
2329                                                 tcpsetstate(s, Closing);
2330                                         break;
2331                                 case Finwait2:
2332                                         tcb->rcv.nxt++;
2333                                         tcphalt(tpriv, &tcb->rtt_timer);
2334                                         tcphalt(tpriv, &tcb->acktimer);
2335                                         tcphalt(tpriv, &tcb->katimer);
2336                                         tcpsetstate(s, Time_wait);
2337                                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2338                                         tcpgo(tpriv, &tcb->timer);
2339                                         break;
2340                                 case Close_wait:
2341                                 case Closing:
2342                                 case Last_ack:
2343                                         break;
2344                                 case Time_wait:
2345                                         tcpgo(tpriv, &tcb->timer);
2346                                         break;
2347                         }
2348                 }
2349
2350                 /*
2351                  *  get next adjacent segment from the resequence queue.
2352                  *  dump/trim any overlapping segments
2353                  */
2354                 for (;;) {
2355                         if (tcb->reseq == NULL)
2356                                 goto output;
2357
2358                         if (seq_ge(tcb->rcv.nxt, tcb->reseq->seg.seq) == 0)
2359                                 goto output;
2360
2361                         getreseq(tcb, &seg, &bp, &length);
2362
2363                         if (tcptrim(tcb, &seg, &bp, &length) == 0)
2364                                 break;
2365                 }
2366         }
2367 output:
2368         tcpoutput(s);
2369         qunlock(&s->qlock);
2370         poperror();
2371         return;
2372 raise:
2373         qunlock(&s->qlock);
2374         poperror();
2375         freeblist(bp);
2376         tcpkick(s);
2377 }
2378
2379 /*
2380  *  always enters and exits with the s locked.  We drop
2381  *  the lock to ipoput the packet so some care has to be
2382  *  taken by callers.
2383  */
2384 void tcpoutput(struct conv *s)
2385 {
2386         Tcp seg;
2387         int msgs;
2388         Tcpctl *tcb;
2389         struct block *hbp, *bp;
2390         int sndcnt, n;
2391         uint32_t ssize, dsize, usable, sent;
2392         struct Fs *f;
2393         struct tcppriv *tpriv;
2394         uint8_t version;
2395
2396         f = s->p->f;
2397         tpriv = s->p->priv;
2398         version = s->ipversion;
2399
2400         for (msgs = 0; msgs < 100; msgs++) {
2401                 tcb = (Tcpctl *) s->ptcl;
2402
2403                 switch (tcb->state) {
2404                         case Listen:
2405                         case Closed:
2406                         case Finwait2:
2407                                 return;
2408                 }
2409
2410                 /* force an ack when a window has opened up */
2411                 if (tcb->rcv.blocked && tcb->rcv.wnd > 0) {
2412                         tcb->rcv.blocked = 0;
2413                         tcb->flags |= FORCE;
2414                 }
2415
2416                 sndcnt = qlen(s->wq) + tcb->flgcnt;
2417                 sent = tcb->snd.ptr - tcb->snd.una;
2418
2419                 /* Don't send anything else until our SYN has been acked */
2420                 if (tcb->snd.ptr != tcb->iss && (tcb->flags & SYNACK) == 0)
2421                         break;
2422
2423                 /* Compute usable segment based on offered window and limit
2424                  * window probes to one
2425                  */
2426                 if (tcb->snd.wnd == 0) {
2427                         if (sent != 0) {
2428                                 if ((tcb->flags & FORCE) == 0)
2429                                         break;
2430 //              tcb->snd.ptr = tcb->snd.una;
2431                         }
2432                         usable = 1;
2433                 } else {
2434                         usable = tcb->cwind;
2435                         if (tcb->snd.wnd < usable)
2436                                 usable = tcb->snd.wnd;
2437                         usable -= sent;
2438                 }
2439                 ssize = sndcnt - sent;
2440                 if (ssize && usable < 2)
2441                         netlog(s->p->f, Logtcp, "throttled snd.wnd %lu cwind %lu\n",
2442                                    tcb->snd.wnd, tcb->cwind);
2443                 if (usable < ssize)
2444                         ssize = usable;
2445                 if (tcb->mss < ssize)
2446                         ssize = tcb->mss;
2447                 dsize = ssize;
2448                 seg.urg = 0;
2449
2450                 if (ssize == 0)
2451                         if ((tcb->flags & FORCE) == 0)
2452                                 break;
2453
2454                 tcb->flags &= ~FORCE;
2455                 tcprcvwin(s);
2456
2457                 /* By default we will generate an ack */
2458                 tcphalt(tpriv, &tcb->acktimer);
2459                 tcb->rcv.una = 0;
2460                 seg.source = s->lport;
2461                 seg.dest = s->rport;
2462                 seg.flags = ACK;
2463                 seg.mss = 0;
2464                 seg.ws = 0;
2465                 switch (tcb->state) {
2466                         case Syn_sent:
2467                                 seg.flags = 0;
2468                                 if (tcb->snd.ptr == tcb->iss) {
2469                                         seg.flags |= SYN;
2470                                         dsize--;
2471                                         seg.mss = tcb->mss;
2472                                         seg.ws = tcb->scale;
2473                                 }
2474                                 break;
2475                         case Syn_received:
2476                                 /*
2477                                  *  don't send any data with a SYN/ACK packet
2478                                  *  because Linux rejects the packet in its
2479                                  *  attempt to solve the SYN attack problem
2480                                  */
2481                                 if (tcb->snd.ptr == tcb->iss) {
2482                                         seg.flags |= SYN;
2483                                         dsize = 0;
2484                                         ssize = 1;
2485                                         seg.mss = tcb->mss;
2486                                         seg.ws = tcb->scale;
2487                                 }
2488                                 break;
2489                 }
2490                 seg.seq = tcb->snd.ptr;
2491                 seg.ack = tcb->rcv.nxt;
2492                 seg.wnd = tcb->rcv.wnd;
2493
2494                 /* Pull out data to send */
2495                 bp = NULL;
2496                 if (dsize != 0) {
2497                         bp = qcopy(s->wq, dsize, sent);
2498                         if (BLEN(bp) != dsize) {
2499                                 seg.flags |= FIN;
2500                                 dsize--;
2501                         }
2502                 }
2503
2504                 if (sent + dsize == sndcnt)
2505                         seg.flags |= PSH;
2506
2507                 /* keep track of balance of resent data */
2508                 if (seq_lt(tcb->snd.ptr, tcb->snd.nxt)) {
2509                         n = tcb->snd.nxt - tcb->snd.ptr;
2510                         if (ssize < n)
2511                                 n = ssize;
2512                         tcb->resent += n;
2513                         netlog(f, Logtcp, "rexmit: %I.%d -> %I.%d ptr 0x%lx nxt 0x%lx\n",
2514                                    s->raddr, s->rport, s->laddr, s->lport, tcb->snd.ptr,
2515                                    tcb->snd.nxt);
2516                         tpriv->stats[RetransSegs]++;
2517                 }
2518
2519                 tcb->snd.ptr += ssize;
2520
2521                 /* Pull up the send pointer so we can accept acks
2522                  * for this window
2523                  */
2524                 if (seq_gt(tcb->snd.ptr, tcb->snd.nxt))
2525                         tcb->snd.nxt = tcb->snd.ptr;
2526
2527                 /* Build header, link data and compute cksum */
2528                 switch (version) {
2529                         case V4:
2530                                 tcb->protohdr.tcp4hdr.vihl = IP_VER4;
2531                                 hbp = htontcp4(&seg, bp, &tcb->protohdr.tcp4hdr, tcb);
2532                                 if (hbp == NULL) {
2533                                         freeblist(bp);
2534                                         return;
2535                                 }
2536                                 break;
2537                         case V6:
2538                                 tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
2539                                 hbp = htontcp6(&seg, bp, &tcb->protohdr.tcp6hdr, tcb);
2540                                 if (hbp == NULL) {
2541                                         freeblist(bp);
2542                                         return;
2543                                 }
2544                                 break;
2545                         default:
2546                                 hbp = NULL;     /* to suppress a warning */
2547                                 panic("tcpoutput: version %d", version);
2548                 }
2549
2550                 /* Start the transmission timers if there is new data and we
2551                  * expect acknowledges
2552                  */
2553                 if (ssize != 0) {
2554                         if (tcb->timer.state != TcptimerON)
2555                                 tcpgo(tpriv, &tcb->timer);
2556
2557                         /*  If round trip timer isn't running, start it.
2558                          *  measure the longest packet only in case the
2559                          *  transmission time dominates RTT
2560                          */
2561                         if (tcb->rtt_timer.state != TcptimerON)
2562                                 if (ssize == tcb->mss) {
2563                                         tcpgo(tpriv, &tcb->rtt_timer);
2564                                         tcb->rttseq = tcb->snd.ptr;
2565                                 }
2566                 }
2567
2568                 tpriv->stats[OutSegs]++;
2569
2570                 /* put off the next keep alive */
2571                 tcpgo(tpriv, &tcb->katimer);
2572
2573                 switch (version) {
2574                         case V4:
2575                                 if (ipoput4(f, hbp, 0, s->ttl, s->tos, s) < 0) {
2576                                         /* a negative return means no route */
2577                                         localclose(s, "no route");
2578                                 }
2579                                 break;
2580                         case V6:
2581                                 if (ipoput6(f, hbp, 0, s->ttl, s->tos, s) < 0) {
2582                                         /* a negative return means no route */
2583                                         localclose(s, "no route");
2584                                 }
2585                                 break;
2586                         default:
2587                                 panic("tcpoutput2: version %d", version);
2588                 }
2589                 if ((msgs % 4) == 1) {
2590                         qunlock(&s->qlock);
2591                         kthread_yield();
2592                         qlock(&s->qlock);
2593                 }
2594         }
2595 }
2596
2597 /*
2598  *  the BSD convention (hack?) for keep alives.  resend last uint8_t acked.
2599  */
2600 void tcpsendka(struct conv *s)
2601 {
2602         Tcp seg;
2603         Tcpctl *tcb;
2604         struct block *hbp, *dbp;
2605
2606         tcb = (Tcpctl *) s->ptcl;
2607
2608         dbp = NULL;
2609         seg.urg = 0;
2610         seg.source = s->lport;
2611         seg.dest = s->rport;
2612         seg.flags = ACK | PSH;
2613         seg.mss = 0;
2614         seg.ws = 0;
2615         if (tcpporthogdefense)
2616                 seg.seq = tcb->snd.una - (1 << 30) - nrand(1 << 20);
2617         else
2618                 seg.seq = tcb->snd.una - 1;
2619         seg.ack = tcb->rcv.nxt;
2620         tcb->rcv.una = 0;
2621         seg.wnd = tcb->rcv.wnd;
2622         if (tcb->state == Finwait2) {
2623                 seg.flags |= FIN;
2624         } else {
2625                 dbp = allocb(1);
2626                 dbp->wp++;
2627         }
2628
2629         if (isv4(s->raddr)) {
2630                 /* Build header, link data and compute cksum */
2631                 tcb->protohdr.tcp4hdr.vihl = IP_VER4;
2632                 hbp = htontcp4(&seg, dbp, &tcb->protohdr.tcp4hdr, tcb);
2633                 if (hbp == NULL) {
2634                         freeblist(dbp);
2635                         return;
2636                 }
2637                 ipoput4(s->p->f, hbp, 0, s->ttl, s->tos, s);
2638         } else {
2639                 /* Build header, link data and compute cksum */
2640                 tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
2641                 hbp = htontcp6(&seg, dbp, &tcb->protohdr.tcp6hdr, tcb);
2642                 if (hbp == NULL) {
2643                         freeblist(dbp);
2644                         return;
2645                 }
2646                 ipoput6(s->p->f, hbp, 0, s->ttl, s->tos, s);
2647         }
2648 }
2649
2650 /*
2651  *  set connection to time out after 12 minutes
2652  */
2653 void tcpsetkacounter(Tcpctl * tcb)
2654 {
2655         tcb->kacounter = (12 * 60 * 1000) / (tcb->katimer.start * MSPTICK);
2656         if (tcb->kacounter < 3)
2657                 tcb->kacounter = 3;
2658 }
2659
2660 /*
2661  *  if we've timed out, close the connection
2662  *  otherwise, send a keepalive and restart the timer
2663  */
2664 void tcpkeepalive(void *v)
2665 {
2666         ERRSTACK(1);
2667         Tcpctl *tcb;
2668         struct conv *s;
2669
2670         s = v;
2671         tcb = (Tcpctl *) s->ptcl;
2672         if (waserror()) {
2673                 qunlock(&s->qlock);
2674                 nexterror();
2675         }
2676         qlock(&s->qlock);
2677         if (tcb->state != Closed) {
2678                 if (--(tcb->kacounter) <= 0) {
2679                         localclose(s, Etimedout);
2680                 } else {
2681                         tcpsendka(s);
2682                         tcpgo(s->p->priv, &tcb->katimer);
2683                 }
2684         }
2685         qunlock(&s->qlock);
2686         poperror();
2687 }
2688
2689 /*
2690  *  start keepalive timer
2691  */
2692 char *tcpstartka(struct conv *s, char **f, int n)
2693 {
2694         Tcpctl *tcb;
2695         int x;
2696
2697         tcb = (Tcpctl *) s->ptcl;
2698         if (tcb->state != Established)
2699                 return "connection must be in Establised state";
2700         if (n > 1) {
2701                 x = atoi(f[1]);
2702                 if (x >= MSPTICK)
2703                         tcb->katimer.start = x / MSPTICK;
2704         }
2705         tcpsetkacounter(tcb);
2706         tcpgo(s->p->priv, &tcb->katimer);
2707
2708         return NULL;
2709 }
2710
2711 /*
2712  *  turn checksums on/off
2713  */
2714 char *tcpsetchecksum(struct conv *s, char **f, int unused)
2715 {
2716         Tcpctl *tcb;
2717
2718         tcb = (Tcpctl *) s->ptcl;
2719         tcb->nochecksum = !atoi(f[1]);
2720
2721         return NULL;
2722 }
2723
2724 void tcprxmit(struct conv *s)
2725 {
2726         Tcpctl *tcb;
2727
2728         tcb = (Tcpctl *) s->ptcl;
2729
2730         tcb->flags |= RETRAN | FORCE;
2731         tcb->snd.ptr = tcb->snd.una;
2732
2733         /*
2734          *  We should be halving the slow start threshhold (down to one
2735          *  mss) but leaving it at mss seems to work well enough
2736          */
2737         tcb->ssthresh = tcb->mss;
2738
2739         /*
2740          *  pull window down to a single packet
2741          */
2742         tcb->cwind = tcb->mss;
2743         tcpoutput(s);
2744 }
2745
2746 void tcptimeout(void *arg)
2747 {
2748         ERRSTACK(1);
2749         struct conv *s;
2750         Tcpctl *tcb;
2751         int maxback;
2752         struct tcppriv *tpriv;
2753
2754         s = (struct conv *)arg;
2755         tpriv = s->p->priv;
2756         tcb = (Tcpctl *) s->ptcl;
2757
2758         if (waserror()) {
2759                 qunlock(&s->qlock);
2760                 nexterror();
2761         }
2762         qlock(&s->qlock);
2763         switch (tcb->state) {
2764                 default:
2765                         tcb->backoff++;
2766                         if (tcb->state == Syn_sent)
2767                                 maxback = MAXBACKMS / 2;
2768                         else
2769                                 maxback = MAXBACKMS;
2770                         tcb->backedoff += tcb->timer.start * MSPTICK;
2771                         if (tcb->backedoff >= maxback) {
2772                                 localclose(s, Etimedout);
2773                                 break;
2774                         }
2775                         netlog(s->p->f, Logtcprxmt, "timeout rexmit 0x%lx %d/%d\n",
2776                                    tcb->snd.una, tcb->timer.start, NOW);
2777                         tcpsettimer(tcb);
2778                         tcprxmit(s);
2779                         tpriv->stats[RetransTimeouts]++;
2780                         tcb->snd.dupacks = 0;
2781                         break;
2782                 case Time_wait:
2783                         localclose(s, NULL);
2784                         break;
2785                 case Closed:
2786                         break;
2787         }
2788         qunlock(&s->qlock);
2789         poperror();
2790 }
2791
2792 int inwindow(Tcpctl * tcb, int seq)
2793 {
2794         return seq_within(seq, tcb->rcv.nxt, tcb->rcv.nxt + tcb->rcv.wnd - 1);
2795 }
2796
2797 /*
2798  *  set up state for a received SYN (or SYN ACK) packet
2799  */
2800 void procsyn(struct conv *s, Tcp * seg)
2801 {
2802         Tcpctl *tcb;
2803
2804         tcb = (Tcpctl *) s->ptcl;
2805         tcb->flags |= FORCE;
2806
2807         tcb->rcv.nxt = seg->seq + 1;
2808         tcb->rcv.urg = tcb->rcv.nxt;
2809         tcb->irs = seg->seq;
2810
2811         /* our sending max segment size cannot be bigger than what he asked for */
2812         if (seg->mss != 0 && seg->mss < tcb->mss)
2813                 tcb->mss = seg->mss;
2814
2815         /* the congestion window always starts out as a single segment */
2816         tcb->snd.wnd = seg->wnd;
2817         tcb->cwind = tcb->mss;
2818 }
2819
2820 int
2821 addreseq(Tcpctl * tcb, struct tcppriv *tpriv, Tcp * seg,
2822                  struct block *bp, uint16_t length)
2823 {
2824         Reseq *rp, *rp1;
2825         int i, rqlen, qmax;
2826
2827         rp = kzmalloc(sizeof(Reseq), 0);
2828         if (rp == NULL) {
2829                 freeblist(bp);  /* bp always consumed by add_reseq */
2830                 return 0;
2831         }
2832
2833         rp->seg = *seg;
2834         rp->bp = bp;
2835         rp->length = length;
2836
2837         /* Place on reassembly list sorting by starting seq number */
2838         rp1 = tcb->reseq;
2839         if (rp1 == NULL || seq_lt(seg->seq, rp1->seg.seq)) {
2840                 rp->next = rp1;
2841                 tcb->reseq = rp;
2842                 if (rp->next != NULL)
2843                         tpriv->stats[OutOfOrder]++;
2844                 return 0;
2845         }
2846
2847         rqlen = 0;
2848         for (i = 0;; i++) {
2849                 rqlen += rp1->length;
2850                 if (rp1->next == NULL || seq_lt(seg->seq, rp1->next->seg.seq)) {
2851                         rp->next = rp1->next;
2852                         rp1->next = rp;
2853                         if (rp->next != NULL)
2854                                 tpriv->stats[OutOfOrder]++;
2855                         break;
2856                 }
2857                 rp1 = rp1->next;
2858         }
2859         qmax = QMAX << tcb->rcv.scale;
2860         if (rqlen > qmax) {
2861                 printd("resequence queue > window: %d > %d\n", rqlen, qmax);
2862                 i = 0;
2863                 for (rp1 = tcb->reseq; rp1 != NULL; rp1 = rp1->next) {
2864                         printd("0x%#lx 0x%#lx 0x%#x\n", rp1->seg.seq,
2865                                    rp1->seg.ack, rp1->seg.flags);
2866                         if (i++ > 10) {
2867                                 printd("...\n");
2868                                 break;
2869                         }
2870                 }
2871
2872                 // delete entire reassembly queue; wait for retransmit.
2873                 // - should we be smarter and only delete the tail?
2874                 for (rp = tcb->reseq; rp != NULL; rp = rp1) {
2875                         rp1 = rp->next;
2876                         freeblist(rp->bp);
2877                         kfree(rp);
2878                 }
2879                 tcb->reseq = NULL;
2880
2881                 return -1;
2882         }
2883         return 0;
2884 }
2885
2886 void getreseq(Tcpctl * tcb, Tcp * seg, struct block **bp, uint16_t * length)
2887 {
2888         Reseq *rp;
2889
2890         rp = tcb->reseq;
2891         if (rp == NULL)
2892                 return;
2893
2894         tcb->reseq = rp->next;
2895
2896         *seg = rp->seg;
2897         *bp = rp->bp;
2898         *length = rp->length;
2899
2900         kfree(rp);
2901 }
2902
2903 int tcptrim(Tcpctl * tcb, Tcp * seg, struct block **bp, uint16_t * length)
2904 {
2905         uint16_t len;
2906         uint8_t accept;
2907         int dupcnt, excess;
2908
2909         accept = 0;
2910         len = *length;
2911         if (seg->flags & SYN)
2912                 len++;
2913         if (seg->flags & FIN)
2914                 len++;
2915
2916         if (tcb->rcv.wnd == 0) {
2917                 if (len == 0 && seg->seq == tcb->rcv.nxt)
2918                         return 0;
2919         } else {
2920                 /* Some part of the segment should be in the window */
2921                 if (inwindow(tcb, seg->seq))
2922                         accept++;
2923                 else if (len != 0) {
2924                         if (inwindow(tcb, seg->seq + len - 1) ||
2925                                 seq_within(tcb->rcv.nxt, seg->seq, seg->seq + len - 1))
2926                                 accept++;
2927                 }
2928         }
2929         if (!accept) {
2930                 freeblist(*bp);
2931                 return -1;
2932         }
2933         dupcnt = tcb->rcv.nxt - seg->seq;
2934         if (dupcnt > 0) {
2935                 tcb->rerecv += dupcnt;
2936                 if (seg->flags & SYN) {
2937                         seg->flags &= ~SYN;
2938                         seg->seq++;
2939
2940                         if (seg->urg > 1)
2941                                 seg->urg--;
2942                         else
2943                                 seg->flags &= ~URG;
2944                         dupcnt--;
2945                 }
2946                 if (dupcnt > 0) {
2947                         pullblock(bp, (uint16_t) dupcnt);
2948                         seg->seq += dupcnt;
2949                         *length -= dupcnt;
2950
2951                         if (seg->urg > dupcnt)
2952                                 seg->urg -= dupcnt;
2953                         else {
2954                                 seg->flags &= ~URG;
2955                                 seg->urg = 0;
2956                         }
2957                 }
2958         }
2959         excess = seg->seq + *length - (tcb->rcv.nxt + tcb->rcv.wnd);
2960         if (excess > 0) {
2961                 tcb->rerecv += excess;
2962                 *length -= excess;
2963                 *bp = trimblock(*bp, 0, *length);
2964                 if (*bp == NULL)
2965                         panic("presotto is a boofhead");
2966                 seg->flags &= ~FIN;
2967         }
2968         return 0;
2969 }
2970
2971 void tcpadvise(struct Proto *tcp, struct block *bp, char *msg)
2972 {
2973         Tcp4hdr *h4;
2974         Tcp6hdr *h6;
2975         Tcpctl *tcb;
2976         uint8_t source[IPaddrlen];
2977         uint8_t dest[IPaddrlen];
2978         uint16_t psource, pdest;
2979         struct conv *s, **p;
2980
2981         h4 = (Tcp4hdr *) (bp->rp);
2982         h6 = (Tcp6hdr *) (bp->rp);
2983
2984         if ((h4->vihl & 0xF0) == IP_VER4) {
2985                 v4tov6(dest, h4->tcpdst);
2986                 v4tov6(source, h4->tcpsrc);
2987                 psource = nhgets(h4->tcpsport);
2988                 pdest = nhgets(h4->tcpdport);
2989         } else {
2990                 ipmove(dest, h6->tcpdst);
2991                 ipmove(source, h6->tcpsrc);
2992                 psource = nhgets(h6->tcpsport);
2993                 pdest = nhgets(h6->tcpdport);
2994         }
2995
2996         /* Look for a connection */
2997         qlock(&tcp->qlock);
2998         for (p = tcp->conv; *p; p++) {
2999                 s = *p;
3000                 tcb = (Tcpctl *) s->ptcl;
3001                 if (s->rport == pdest)
3002                         if (s->lport == psource)
3003                                 if (tcb->state != Closed)
3004                                         if (ipcmp(s->raddr, dest) == 0)
3005                                                 if (ipcmp(s->laddr, source) == 0) {
3006                                                         qlock(&s->qlock);
3007                                                         qunlock(&tcp->qlock);
3008                                                         switch (tcb->state) {
3009                                                                 case Syn_sent:
3010                                                                         localclose(s, msg);
3011                                                                         break;
3012                                                         }
3013                                                         qunlock(&s->qlock);
3014                                                         freeblist(bp);
3015                                                         return;
3016                                                 }
3017         }
3018         qunlock(&tcp->qlock);
3019         freeblist(bp);
3020 }
3021
3022 static char *tcpporthogdefensectl(char *val)
3023 {
3024         if (strcmp(val, "on") == 0)
3025                 tcpporthogdefense = 1;
3026         else if (strcmp(val, "off") == 0)
3027                 tcpporthogdefense = 0;
3028         else
3029                 return "unknown value for tcpporthogdefense";
3030         return NULL;
3031 }
3032
3033 /* called with c qlocked */
3034 char *tcpctl(struct conv *c, char **f, int n)
3035 {
3036         if (n == 1 && strcmp(f[0], "hangup") == 0)
3037                 return tcphangup(c);
3038         if (n >= 1 && strcmp(f[0], "keepalive") == 0)
3039                 return tcpstartka(c, f, n);
3040         if (n >= 1 && strcmp(f[0], "checksum") == 0)
3041                 return tcpsetchecksum(c, f, n);
3042         if (n >= 1 && strcmp(f[0], "tcpporthogdefense") == 0)
3043                 return tcpporthogdefensectl(f[1]);
3044         return "unknown control request";
3045 }
3046
3047 int tcpstats(struct Proto *tcp, char *buf, int len)
3048 {
3049         struct tcppriv *priv;
3050         char *p, *e;
3051         int i;
3052
3053         priv = tcp->priv;
3054         p = buf;
3055         e = p + len;
3056         for (i = 0; i < Nstats; i++)
3057                 p = seprintf(p, e, "%s: %u\n", statnames[i], priv->stats[i]);
3058         return p - buf;
3059 }
3060
3061 /*
3062  *  garbage collect any stale conversations:
3063  *      - SYN received but no SYN-ACK after 5 seconds (could be the SYN attack)
3064  *      - Finwait2 after 5 minutes
3065  *
3066  *  this is called whenever we run out of channels.  Both checks are
3067  *  of questionable validity so we try to use them only when we're
3068  *  up against the wall.
3069  */
3070 int tcpgc(struct Proto *tcp)
3071 {
3072         struct conv *c, **pp, **ep;
3073         int n;
3074         Tcpctl *tcb;
3075
3076         n = 0;
3077         ep = &tcp->conv[tcp->nc];
3078         for (pp = tcp->conv; pp < ep; pp++) {
3079                 c = *pp;
3080                 if (c == NULL)
3081                         break;
3082                 if (!canqlock(&c->qlock))
3083                         continue;
3084                 tcb = (Tcpctl *) c->ptcl;
3085                 switch (tcb->state) {
3086                         case Syn_received:
3087                                 if (NOW - tcb->time > 5000) {
3088                                         localclose(c, "timed out");
3089                                         n++;
3090                                 }
3091                                 break;
3092                         case Finwait2:
3093                                 if (NOW - tcb->time > 5 * 60 * 1000) {
3094                                         localclose(c, "timed out");
3095                                         n++;
3096                                 }
3097                                 break;
3098                 }
3099                 qunlock(&c->qlock);
3100         }
3101         return n;
3102 }
3103
3104 void tcpsettimer(Tcpctl * tcb)
3105 {
3106         int x;
3107
3108         /* round trip dependency */
3109         x = backoff(tcb->backoff) *
3110                 (tcb->mdev + (tcb->srtt >> LOGAGAIN) + MSPTICK) / MSPTICK;
3111
3112         /* bounded twixt 1/2 and 64 seconds */
3113         if (x < 500 / MSPTICK)
3114                 x = 500 / MSPTICK;
3115         else if (x > (64000 / MSPTICK))
3116                 x = 64000 / MSPTICK;
3117         tcb->timer.start = x;
3118 }
3119
3120 void tcpinit(struct Fs *fs)
3121 {
3122         struct Proto *tcp;
3123         struct tcppriv *tpriv;
3124
3125         tcp = kzmalloc(sizeof(struct Proto), 0);
3126         tpriv = tcp->priv = kzmalloc(sizeof(struct tcppriv), 0);
3127         qlock_init(&tpriv->tl);
3128         qlock_init(&tpriv->apl);
3129         tcp->name = "tcp";
3130         tcp->connect = tcpconnect;
3131         tcp->announce = tcpannounce;
3132         tcp->ctl = tcpctl;
3133         tcp->state = tcpstate;
3134         tcp->create = tcpcreate;
3135         tcp->close = tcpclose;
3136         tcp->rcv = tcpiput;
3137         tcp->advise = tcpadvise;
3138         tcp->stats = tcpstats;
3139         tcp->inuse = tcpinuse;
3140         tcp->gc = tcpgc;
3141         tcp->ipproto = IP_TCPPROTO;
3142         tcp->nc = scalednconv();
3143         tcp->ptclsize = sizeof(Tcpctl);
3144         tpriv->stats[MaxConn] = tcp->nc;
3145
3146         Fsproto(fs, tcp);
3147 }
3148
3149 void
3150 tcpsetscale(struct conv *s, Tcpctl * tcb, uint16_t rcvscale, uint16_t sndscale)
3151 {
3152         if (rcvscale) {
3153                 tcb->rcv.scale = rcvscale & 0xff;
3154                 tcb->snd.scale = sndscale & 0xff;
3155                 tcb->window = QMAX << tcb->snd.scale;
3156                 qsetlimit(s->rq, tcb->window);
3157         } else {
3158                 tcb->rcv.scale = 0;
3159                 tcb->snd.scale = 0;
3160                 tcb->window = QMAX;
3161                 qsetlimit(s->rq, tcb->window);
3162         }
3163 }