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