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