67af4321bd32404c8f304fec116476475b3d3743
[vpp.git] / src / vnet / tcp / tcp_input.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <vppinfra/sparse_vec.h>
17 #include <vnet/tcp/tcp_packet.h>
18 #include <vnet/tcp/tcp.h>
19 #include <vnet/session/session.h>
20 #include <math.h>
21
22 static char *tcp_error_strings[] = {
23 #define tcp_error(n,s) s,
24 #include <vnet/tcp/tcp_error.def>
25 #undef tcp_error
26 };
27
28 /* All TCP nodes have the same outgoing arcs */
29 #define foreach_tcp_state_next                  \
30   _ (DROP, "error-drop")                        \
31   _ (TCP4_OUTPUT, "tcp4-output")                \
32   _ (TCP6_OUTPUT, "tcp6-output")
33
34 typedef enum _tcp_established_next
35 {
36 #define _(s,n) TCP_ESTABLISHED_NEXT_##s,
37   foreach_tcp_state_next
38 #undef _
39     TCP_ESTABLISHED_N_NEXT,
40 } tcp_established_next_t;
41
42 typedef enum _tcp_rcv_process_next
43 {
44 #define _(s,n) TCP_RCV_PROCESS_NEXT_##s,
45   foreach_tcp_state_next
46 #undef _
47     TCP_RCV_PROCESS_N_NEXT,
48 } tcp_rcv_process_next_t;
49
50 typedef enum _tcp_syn_sent_next
51 {
52 #define _(s,n) TCP_SYN_SENT_NEXT_##s,
53   foreach_tcp_state_next
54 #undef _
55     TCP_SYN_SENT_N_NEXT,
56 } tcp_syn_sent_next_t;
57
58 typedef enum _tcp_listen_next
59 {
60 #define _(s,n) TCP_LISTEN_NEXT_##s,
61   foreach_tcp_state_next
62 #undef _
63     TCP_LISTEN_N_NEXT,
64 } tcp_listen_next_t;
65
66 /* Generic, state independent indices */
67 typedef enum _tcp_state_next
68 {
69 #define _(s,n) TCP_NEXT_##s,
70   foreach_tcp_state_next
71 #undef _
72     TCP_STATE_N_NEXT,
73 } tcp_state_next_t;
74
75 #define tcp_next_output(is_ip4) (is_ip4 ? TCP_NEXT_TCP4_OUTPUT          \
76                                         : TCP_NEXT_TCP6_OUTPUT)
77
78 vlib_node_registration_t tcp4_established_node;
79 vlib_node_registration_t tcp6_established_node;
80
81 /**
82  * Validate segment sequence number. As per RFC793:
83  *
84  * Segment Receive Test
85  *      Length  Window
86  *      ------- -------  -------------------------------------------
87  *      0       0       SEG.SEQ = RCV.NXT
88  *      0       >0      RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
89  *      >0      0       not acceptable
90  *      >0      >0      RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
91  *                      or RCV.NXT =< SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND
92  *
93  * This ultimately consists in checking if segment falls within the window.
94  * The one important difference compared to RFC793 is that we use rcv_las,
95  * or the rcv_nxt at last ack sent instead of rcv_nxt since that's the
96  * peer's reference when computing our receive window.
97  *
98  * This accepts only segments within the window.
99  */
100 always_inline u8
101 tcp_segment_in_rcv_wnd (tcp_connection_t * tc, u32 seq, u32 end_seq)
102 {
103   return seq_leq (end_seq, tc->rcv_las + tc->rcv_wnd)
104     && seq_geq (seq, tc->rcv_nxt);
105 }
106
107 void
108 tcp_options_parse (tcp_header_t * th, tcp_options_t * to)
109 {
110   const u8 *data;
111   u8 opt_len, opts_len, kind;
112   int j;
113   sack_block_t b;
114
115   opts_len = (tcp_doff (th) << 2) - sizeof (tcp_header_t);
116   data = (const u8 *) (th + 1);
117
118   /* Zero out all flags but those set in SYN */
119   to->flags &= (TCP_OPTS_FLAG_SACK_PERMITTED | TCP_OPTS_FLAG_WSCALE);
120
121   for (; opts_len > 0; opts_len -= opt_len, data += opt_len)
122     {
123       kind = data[0];
124
125       /* Get options length */
126       if (kind == TCP_OPTION_EOL)
127         break;
128       else if (kind == TCP_OPTION_NOOP)
129         opt_len = 1;
130       else
131         {
132           /* broken options */
133           if (opts_len < 2)
134             break;
135           opt_len = data[1];
136
137           /* weird option length */
138           if (opt_len < 2 || opt_len > opts_len)
139             break;
140         }
141
142       /* Parse options */
143       switch (kind)
144         {
145         case TCP_OPTION_MSS:
146           if ((opt_len == TCP_OPTION_LEN_MSS) && tcp_syn (th))
147             {
148               to->flags |= TCP_OPTS_FLAG_MSS;
149               to->mss = clib_net_to_host_u16 (*(u16 *) (data + 2));
150             }
151           break;
152         case TCP_OPTION_WINDOW_SCALE:
153           if ((opt_len == TCP_OPTION_LEN_WINDOW_SCALE) && tcp_syn (th))
154             {
155               to->flags |= TCP_OPTS_FLAG_WSCALE;
156               to->wscale = data[2];
157               if (to->wscale > TCP_MAX_WND_SCALE)
158                 {
159                   clib_warning ("Illegal window scaling value: %d",
160                                 to->wscale);
161                   to->wscale = TCP_MAX_WND_SCALE;
162                 }
163             }
164           break;
165         case TCP_OPTION_TIMESTAMP:
166           if (opt_len == TCP_OPTION_LEN_TIMESTAMP)
167             {
168               to->flags |= TCP_OPTS_FLAG_TSTAMP;
169               to->tsval = clib_net_to_host_u32 (*(u32 *) (data + 2));
170               to->tsecr = clib_net_to_host_u32 (*(u32 *) (data + 6));
171             }
172           break;
173         case TCP_OPTION_SACK_PERMITTED:
174           if (opt_len == TCP_OPTION_LEN_SACK_PERMITTED && tcp_syn (th))
175             to->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
176           break;
177         case TCP_OPTION_SACK_BLOCK:
178           /* If SACK permitted was not advertised or a SYN, break */
179           if ((to->flags & TCP_OPTS_FLAG_SACK_PERMITTED) == 0 || tcp_syn (th))
180             break;
181
182           /* If too short or not correctly formatted, break */
183           if (opt_len < 10 || ((opt_len - 2) % TCP_OPTION_LEN_SACK_BLOCK))
184             break;
185
186           to->flags |= TCP_OPTS_FLAG_SACK;
187           to->n_sack_blocks = (opt_len - 2) / TCP_OPTION_LEN_SACK_BLOCK;
188           vec_reset_length (to->sacks);
189           for (j = 0; j < to->n_sack_blocks; j++)
190             {
191               b.start = clib_net_to_host_u32 (*(u32 *) (data + 2 + 4 * j));
192               b.end = clib_net_to_host_u32 (*(u32 *) (data + 6 + 4 * j));
193               vec_add1 (to->sacks, b);
194             }
195           break;
196         default:
197           /* Nothing to see here */
198           continue;
199         }
200     }
201 }
202
203 always_inline int
204 tcp_segment_check_paws (tcp_connection_t * tc)
205 {
206   /* XXX normally test for timestamp should be lt instead of leq, but for
207    * local testing this is not enough */
208   return tcp_opts_tstamp (&tc->opt) && tc->tsval_recent
209     && timestamp_lt (tc->opt.tsval, tc->tsval_recent);
210 }
211
212 /**
213  * Validate incoming segment as per RFC793 p. 69 and RFC1323 p. 19
214  *
215  * It first verifies if segment has a wrapped sequence number (PAWS) and then
216  * does the processing associated to the first four steps (ignoring security
217  * and precedence): sequence number, rst bit and syn bit checks.
218  *
219  * @return 0 if segments passes validation.
220  */
221 static int
222 tcp_segment_validate (vlib_main_t * vm, tcp_connection_t * tc0,
223                       vlib_buffer_t * b0, tcp_header_t * th0, u32 * next0)
224 {
225   u8 paws_failed;
226
227   if (PREDICT_FALSE (!tcp_ack (th0) && !tcp_rst (th0) && !tcp_syn (th0)))
228     return -1;
229
230   tcp_options_parse (th0, &tc0->opt);
231
232   /* RFC1323: Check against wrapped sequence numbers (PAWS). If we have
233    * timestamp to echo and it's less than tsval_recent, drop segment
234    * but still send an ACK in order to retain TCP's mechanism for detecting
235    * and recovering from half-open connections */
236   paws_failed = tcp_segment_check_paws (tc0);
237   if (paws_failed)
238     {
239       clib_warning ("paws failed");
240
241       /* If it just so happens that a segment updates tsval_recent for a
242        * segment over 24 days old, invalidate tsval_recent. */
243       if (timestamp_lt (tc0->tsval_recent_age + TCP_PAWS_IDLE,
244                         tcp_time_now ()))
245         {
246           /* Age isn't reset until we get a valid tsval (bsd inspired) */
247           tc0->tsval_recent = 0;
248         }
249       else
250         {
251           /* Drop after ack if not rst */
252           if (!tcp_rst (th0))
253             {
254               tcp_make_ack (tc0, b0);
255               *next0 = tcp_next_output (tc0->c_is_ip4);
256               return -1;
257             }
258         }
259     }
260
261   /* 1st: check sequence number */
262   if (!tcp_segment_in_rcv_wnd (tc0, vnet_buffer (b0)->tcp.seq_number,
263                                vnet_buffer (b0)->tcp.seq_end))
264     {
265       if (!tcp_rst (th0))
266         {
267           /* Send dup ack */
268           tcp_make_ack (tc0, b0);
269           *next0 = tcp_next_output (tc0->c_is_ip4);
270         }
271       return -1;
272     }
273
274   /* 2nd: check the RST bit */
275   if (tcp_rst (th0))
276     {
277       tcp_connection_reset (tc0);
278       return -1;
279     }
280
281   /* 3rd: check security and precedence (skip) */
282
283   /* 4th: check the SYN bit */
284   if (tcp_syn (th0))
285     {
286       tcp_send_reset (b0, tc0->c_is_ip4);
287       return -1;
288     }
289
290   /* If PAWS passed and segment in window, save timestamp */
291   if (!paws_failed)
292     {
293       tc0->tsval_recent = tc0->opt.tsval;
294       tc0->tsval_recent_age = tcp_time_now ();
295     }
296
297   return 0;
298 }
299
300 always_inline int
301 tcp_rcv_ack_is_acceptable (tcp_connection_t * tc0, vlib_buffer_t * tb0)
302 {
303   /* SND.UNA =< SEG.ACK =< SND.NXT */
304   return (seq_leq (tc0->snd_una, vnet_buffer (tb0)->tcp.ack_number)
305           && seq_leq (vnet_buffer (tb0)->tcp.ack_number, tc0->snd_nxt));
306 }
307
308 /**
309  * Compute smoothed RTT as per VJ's '88 SIGCOMM and RFC6298
310  *
311  * Note that although the original article, srtt and rttvar are scaled
312  * to minimize round-off errors, here we don't. Instead, we rely on
313  * better precision time measurements.
314  *
315  * TODO support us rtt resolution
316  */
317 static void
318 tcp_estimate_rtt (tcp_connection_t * tc, u32 mrtt)
319 {
320   int err;
321
322   if (tc->srtt != 0)
323     {
324       err = mrtt - tc->srtt;
325       tc->srtt += err >> 3;
326
327       /* XXX Drop in RTT results in RTTVAR increase and bigger RTO.
328        * The increase should be bound */
329       tc->rttvar += (clib_abs (err) - tc->rttvar) >> 2;
330     }
331   else
332     {
333       /* First measurement. */
334       tc->srtt = mrtt;
335       tc->rttvar = mrtt << 1;
336     }
337 }
338
339 /** Update RTT estimate and RTO timer
340  *
341  * Measure RTT: We have two sources of RTT measurements: TSOPT and ACK
342  * timing. Middle boxes are known to fiddle with TCP options so we
343  * should give higher priority to ACK timing.
344  *
345  * return 1 if valid rtt 0 otherwise
346  */
347 static int
348 tcp_update_rtt (tcp_connection_t * tc, u32 ack)
349 {
350   u32 mrtt = 0;
351
352   /* Karn's rule, part 1. Don't use retransmitted segments to estimate
353    * RTT because they're ambiguous. */
354   if (tc->rtt_seq && seq_gt (ack, tc->rtt_seq) && !tc->rto_boff)
355     {
356       mrtt = tcp_time_now () - tc->rtt_ts;
357       tc->rtt_seq = 0;
358     }
359
360   /* As per RFC7323 TSecr can be used for RTTM only if the segment advances
361    * snd_una, i.e., the left side of the send window:
362    * seq_lt (tc->snd_una, ack). Note: last condition could be dropped, we don't
363    * try to update rtt for dupacks */
364   else if (tcp_opts_tstamp (&tc->opt) && tc->opt.tsecr && tc->bytes_acked)
365     {
366       mrtt = tcp_time_now () - tc->opt.tsecr;
367     }
368
369   /* Ignore dubious measurements */
370   if (mrtt == 0 || mrtt > TCP_RTT_MAX)
371     return 0;
372
373   tcp_estimate_rtt (tc, mrtt);
374
375   tc->rto = clib_min (tc->srtt + (tc->rttvar << 2), TCP_RTO_MAX);
376
377   return 1;
378 }
379
380 /**
381  * Dequeue bytes that have been acked and while at it update RTT estimates.
382  */
383 static void
384 tcp_dequeue_acked (tcp_connection_t * tc, u32 ack)
385 {
386   /* Dequeue the newly ACKed bytes */
387   stream_session_dequeue_drop (&tc->connection, tc->bytes_acked);
388
389   /* Update rtt and rto */
390   if (tcp_update_rtt (tc, ack))
391     {
392       /* Good ACK received and valid RTT, make sure retransmit backoff is 0 */
393       tc->rto_boff = 0;
394     }
395 }
396
397 /** Check if dupack as per RFC5681 Sec. 2 */
398 always_inline u8
399 tcp_ack_is_dupack (tcp_connection_t * tc, vlib_buffer_t * b, u32 new_snd_wnd)
400 {
401   return ((vnet_buffer (b)->tcp.ack_number == tc->snd_una)
402           && seq_gt (tc->snd_una_max, tc->snd_una)
403           && (vnet_buffer (b)->tcp.seq_end == vnet_buffer (b)->tcp.seq_number)
404           && (new_snd_wnd == tc->snd_wnd));
405 }
406
407 void
408 scoreboard_remove_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * hole)
409 {
410   sack_scoreboard_hole_t *next, *prev;
411
412   if (hole->next != TCP_INVALID_SACK_HOLE_INDEX)
413     {
414       next = pool_elt_at_index (sb->holes, hole->next);
415       next->prev = hole->prev;
416     }
417
418   if (hole->prev != TCP_INVALID_SACK_HOLE_INDEX)
419     {
420       prev = pool_elt_at_index (sb->holes, hole->prev);
421       prev->next = hole->next;
422     }
423   else
424     {
425       sb->head = hole->next;
426     }
427
428   pool_put (sb->holes, hole);
429 }
430
431 sack_scoreboard_hole_t *
432 scoreboard_insert_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * prev,
433                         u32 start, u32 end)
434 {
435   sack_scoreboard_hole_t *hole, *next;
436   u32 hole_index;
437
438   pool_get (sb->holes, hole);
439   memset (hole, 0, sizeof (*hole));
440
441   hole->start = start;
442   hole->end = end;
443   hole_index = hole - sb->holes;
444
445   if (prev)
446     {
447       hole->prev = prev - sb->holes;
448       hole->next = prev->next;
449
450       if ((next = scoreboard_next_hole (sb, hole)))
451         next->prev = hole_index;
452
453       prev->next = hole_index;
454     }
455   else
456     {
457       sb->head = hole_index;
458       hole->prev = TCP_INVALID_SACK_HOLE_INDEX;
459       hole->next = TCP_INVALID_SACK_HOLE_INDEX;
460     }
461
462   return hole;
463 }
464
465 static void
466 tcp_rcv_sacks (tcp_connection_t * tc, u32 ack)
467 {
468   sack_scoreboard_t *sb = &tc->sack_sb;
469   sack_block_t *blk, tmp;
470   sack_scoreboard_hole_t *hole, *next_hole;
471   u32 blk_index = 0;
472   int i, j;
473
474   if (!tcp_opts_sack (tc) && sb->head == TCP_INVALID_SACK_HOLE_INDEX)
475     return;
476
477   /* Remove invalid blocks */
478   vec_foreach (blk, tc->opt.sacks)
479   {
480     if (seq_lt (blk->start, blk->end)
481         && seq_gt (blk->start, tc->snd_una)
482         && seq_gt (blk->start, ack) && seq_lt (blk->end, tc->snd_nxt))
483       continue;
484
485     vec_del1 (tc->opt.sacks, blk - tc->opt.sacks);
486   }
487
488   /* Add block for cumulative ack */
489   if (seq_gt (ack, tc->snd_una))
490     {
491       tmp.start = tc->snd_una;
492       tmp.end = ack;
493       vec_add1 (tc->opt.sacks, tmp);
494     }
495
496   if (vec_len (tc->opt.sacks) == 0)
497     return;
498
499   /* Make sure blocks are ordered */
500   for (i = 0; i < vec_len (tc->opt.sacks); i++)
501     for (j = i; j < vec_len (tc->opt.sacks); j++)
502       if (seq_lt (tc->opt.sacks[j].start, tc->opt.sacks[i].start))
503         {
504           tmp = tc->opt.sacks[i];
505           tc->opt.sacks[i] = tc->opt.sacks[j];
506           tc->opt.sacks[j] = tmp;
507         }
508
509   /* If no holes, insert the first that covers all outstanding bytes */
510   if (sb->head == TCP_INVALID_SACK_HOLE_INDEX)
511     {
512       scoreboard_insert_hole (sb, 0, tc->snd_una, tc->snd_una_max);
513     }
514
515   /* Walk the holes with the SACK blocks */
516   hole = pool_elt_at_index (sb->holes, sb->head);
517   while (hole && blk_index < vec_len (tc->opt.sacks))
518     {
519       blk = &tc->opt.sacks[blk_index];
520
521       if (seq_leq (blk->start, hole->start))
522         {
523           /* Block covers hole. Remove hole */
524           if (seq_geq (blk->end, hole->end))
525             {
526               next_hole = scoreboard_next_hole (sb, hole);
527
528               /* Byte accounting */
529               if (seq_lt (hole->end, ack))
530                 {
531                   /* Bytes lost because snd wnd left edge advances */
532                   if (seq_lt (next_hole->start, ack))
533                     sb->sacked_bytes -= next_hole->start - hole->end;
534                   else
535                     sb->sacked_bytes -= ack - hole->end;
536                 }
537               else
538                 {
539                   sb->sacked_bytes += scoreboard_hole_bytes (hole);
540                 }
541
542               scoreboard_remove_hole (sb, hole);
543               hole = next_hole;
544             }
545           /* Partial overlap */
546           else
547             {
548               sb->sacked_bytes += blk->end - hole->start;
549               hole->start = blk->end;
550               blk_index++;
551             }
552         }
553       else
554         {
555           /* Hole must be split */
556           if (seq_leq (blk->end, hole->end))
557             {
558               sb->sacked_bytes += blk->end - blk->start;
559               scoreboard_insert_hole (sb, hole, blk->end, hole->end);
560               hole->end = blk->start - 1;
561               blk_index++;
562             }
563           else
564             {
565               sb->sacked_bytes += hole->end - blk->start + 1;
566               hole->end = blk->start - 1;
567               hole = scoreboard_next_hole (sb, hole);
568             }
569         }
570     }
571 }
572
573 /** Update snd_wnd
574  *
575  * If (SND.WL1 < SEG.SEQ or (SND.WL1 = SEG.SEQ and SND.WL2 =< SEG.ACK)), set
576  * SND.WND <- SEG.WND, set SND.WL1 <- SEG.SEQ, and set SND.WL2 <- SEG.ACK */
577 static void
578 tcp_update_snd_wnd (tcp_connection_t * tc, u32 seq, u32 ack, u32 snd_wnd)
579 {
580   if (tc->snd_wl1 < seq || (tc->snd_wl1 == seq && tc->snd_wl2 <= ack))
581     {
582       tc->snd_wnd = snd_wnd;
583       tc->snd_wl1 = seq;
584       tc->snd_wl2 = ack;
585     }
586 }
587
588 static void
589 tcp_cc_congestion (tcp_connection_t * tc)
590 {
591   tc->cc_algo->congestion (tc);
592 }
593
594 static void
595 tcp_cc_recover (tcp_connection_t * tc)
596 {
597   if (tcp_in_fastrecovery (tc))
598     {
599       tc->cc_algo->recovered (tc);
600       tcp_recovery_off (tc);
601     }
602   else if (tcp_in_recovery (tc))
603     {
604       tcp_recovery_off (tc);
605       tc->cwnd = tcp_loss_wnd (tc);
606     }
607 }
608
609 static void
610 tcp_cc_rcv_ack (tcp_connection_t * tc)
611 {
612   u8 partial_ack;
613
614   if (tcp_in_recovery (tc))
615     {
616       partial_ack = seq_lt (tc->snd_una, tc->snd_una_max);
617       if (!partial_ack)
618         {
619           /* Clear retransmitted bytes. */
620           tc->rtx_bytes = 0;
621           tcp_cc_recover (tc);
622         }
623       else
624         {
625           /* Clear retransmitted bytes. XXX should we clear all? */
626           tc->rtx_bytes = 0;
627           tc->cc_algo->rcv_cong_ack (tc, TCP_CC_PARTIALACK);
628
629           /* Retransmit first unacked segment */
630           tcp_retransmit_first_unacked (tc);
631         }
632     }
633   else
634     {
635       tc->cc_algo->rcv_ack (tc);
636     }
637
638   tc->rcv_dupacks = 0;
639   tc->tsecr_last_ack = tc->opt.tsecr;
640 }
641
642 static void
643 tcp_cc_rcv_dupack (tcp_connection_t * tc, u32 ack)
644 {
645   ASSERT (tc->snd_una == ack);
646
647   tc->rcv_dupacks++;
648   if (tc->rcv_dupacks == TCP_DUPACK_THRESHOLD)
649     {
650       /* RFC6582 NewReno heuristic to avoid multiple fast retransmits */
651       if (tc->opt.tsecr != tc->tsecr_last_ack)
652         {
653           tc->rcv_dupacks = 0;
654           return;
655         }
656
657       tcp_fastrecovery_on (tc);
658
659       /* Handle congestion and dupack */
660       tcp_cc_congestion (tc);
661       tc->cc_algo->rcv_cong_ack (tc, TCP_CC_DUPACK);
662
663       tcp_fast_retransmit (tc);
664
665       /* Post retransmit update cwnd to ssthresh and account for the
666        * three segments that have left the network and should've been
667        * buffered at the receiver */
668       tc->cwnd = tc->ssthresh + TCP_DUPACK_THRESHOLD * tc->snd_mss;
669     }
670   else if (tc->rcv_dupacks > TCP_DUPACK_THRESHOLD)
671     {
672       ASSERT (tcp_in_fastrecovery (tc));
673
674       tc->cc_algo->rcv_cong_ack (tc, TCP_CC_DUPACK);
675     }
676 }
677
678 void
679 tcp_cc_init (tcp_connection_t * tc)
680 {
681   tc->cc_algo = tcp_cc_algo_get (TCP_CC_NEWRENO);
682   tc->cc_algo->init (tc);
683 }
684
685 static int
686 tcp_rcv_ack (tcp_connection_t * tc, vlib_buffer_t * b,
687              tcp_header_t * th, u32 * next, u32 * error)
688 {
689   u32 new_snd_wnd;
690
691   /* If the ACK acks something not yet sent (SEG.ACK > SND.NXT) then send an
692    * ACK, drop the segment, and return  */
693   if (seq_gt (vnet_buffer (b)->tcp.ack_number, tc->snd_nxt))
694     {
695       tcp_make_ack (tc, b);
696       *next = tcp_next_output (tc->c_is_ip4);
697       *error = TCP_ERROR_ACK_INVALID;
698       return -1;
699     }
700
701   /* If old ACK, discard */
702   if (seq_lt (vnet_buffer (b)->tcp.ack_number, tc->snd_una))
703     {
704       *error = TCP_ERROR_ACK_OLD;
705       return -1;
706     }
707
708   if (tcp_opts_sack_permitted (&tc->opt))
709     tcp_rcv_sacks (tc, vnet_buffer (b)->tcp.ack_number);
710
711   new_snd_wnd = clib_net_to_host_u16 (th->window) << tc->snd_wscale;
712
713   if (tcp_ack_is_dupack (tc, b, new_snd_wnd))
714     {
715       tcp_cc_rcv_dupack (tc, vnet_buffer (b)->tcp.ack_number);
716       *error = TCP_ERROR_ACK_DUP;
717       return -1;
718     }
719
720   /* Valid ACK */
721   tc->bytes_acked = vnet_buffer (b)->tcp.ack_number - tc->snd_una;
722   tc->snd_una = vnet_buffer (b)->tcp.ack_number;
723
724   /* Dequeue ACKed packet and update RTT */
725   tcp_dequeue_acked (tc, vnet_buffer (b)->tcp.ack_number);
726
727   tcp_update_snd_wnd (tc, vnet_buffer (b)->tcp.seq_number,
728                       vnet_buffer (b)->tcp.ack_number, new_snd_wnd);
729
730   /* Updates congestion control (slow start/congestion avoidance) */
731   tcp_cc_rcv_ack (tc);
732
733   TCP_EVT_DBG (TCP_EVT_ACK_RCVD, tc);
734
735   /* If everything has been acked, stop retransmit timer
736    * otherwise update */
737   if (tc->snd_una == tc->snd_una_max)
738     tcp_timer_reset (tc, TCP_TIMER_RETRANSMIT);
739   else
740     tcp_timer_update (tc, TCP_TIMER_RETRANSMIT, tc->rto);
741
742   return 0;
743 }
744
745 /**
746  * Build SACK list as per RFC2018.
747  *
748  * Makes sure the first block contains the segment that generated the current
749  * ACK and the following ones are the ones most recently reported in SACK
750  * blocks.
751  *
752  * @param tc TCP connection for which the SACK list is updated
753  * @param start Start sequence number of the newest SACK block
754  * @param end End sequence of the newest SACK block
755  */
756 static void
757 tcp_update_sack_list (tcp_connection_t * tc, u32 start, u32 end)
758 {
759   sack_block_t *new_list = 0, block;
760   u32 n_elts;
761   int i;
762   u8 new_head = 0;
763
764   /* If the first segment is ooo add it to the list. Last write might've moved
765    * rcv_nxt over the first segment. */
766   if (seq_lt (tc->rcv_nxt, start))
767     {
768       block.start = start;
769       block.end = end;
770       vec_add1 (new_list, block);
771       new_head = 1;
772     }
773
774   /* Find the blocks still worth keeping. */
775   for (i = 0; i < vec_len (tc->snd_sacks); i++)
776     {
777       /* Discard if:
778        * 1) rcv_nxt advanced beyond current block OR
779        * 2) Segment overlapped by the first segment, i.e., it has been merged
780        *    into it.*/
781       if (seq_leq (tc->snd_sacks[i].start, tc->rcv_nxt)
782           || seq_leq (tc->snd_sacks[i].start, end))
783         continue;
784
785       /* Save subsequent segments to new SACK list. */
786       n_elts = clib_min (vec_len (tc->snd_sacks) - i,
787                          TCP_MAX_SACK_BLOCKS - new_head);
788       vec_insert_elts (new_list, &tc->snd_sacks[i], n_elts, new_head);
789       break;
790     }
791
792   /* Replace old vector with new one */
793   vec_free (tc->snd_sacks);
794   tc->snd_sacks = new_list;
795 }
796
797 /** Enqueue data for delivery to application */
798 always_inline u32
799 tcp_session_enqueue_data (tcp_connection_t * tc, vlib_buffer_t * b,
800                           u16 data_len)
801 {
802   int written;
803
804   /* Pure ACK. Update rcv_nxt and be done. */
805   if (PREDICT_FALSE (data_len == 0))
806     {
807       tc->rcv_nxt = vnet_buffer (b)->tcp.seq_end;
808       return TCP_ERROR_PURE_ACK;
809     }
810
811   written = stream_session_enqueue_data (&tc->connection,
812                                          vlib_buffer_get_current (b),
813                                          data_len, 1 /* queue event */ );
814
815   /* Update rcv_nxt */
816   if (PREDICT_TRUE (written == data_len))
817     {
818       tc->rcv_nxt = vnet_buffer (b)->tcp.seq_end;
819     }
820   /* If more data written than expected, account for out-of-order bytes. */
821   else if (written > data_len)
822     {
823       tc->rcv_nxt = vnet_buffer (b)->tcp.seq_end + written - data_len;
824
825       /* Send ACK confirming the update */
826       tc->flags |= TCP_CONN_SNDACK;
827
828       /* Update SACK list if need be */
829       if (tcp_opts_sack_permitted (&tc->opt))
830         {
831           /* Remove SACK blocks that have been delivered */
832           tcp_update_sack_list (tc, tc->rcv_nxt, tc->rcv_nxt);
833         }
834     }
835   else
836     {
837       ASSERT (0);
838       return TCP_ERROR_FIFO_FULL;
839     }
840
841   return TCP_ERROR_ENQUEUED;
842 }
843
844 /** Enqueue out-of-order data */
845 always_inline u32
846 tcp_session_enqueue_ooo (tcp_connection_t * tc, vlib_buffer_t * b,
847                          u16 data_len)
848 {
849   stream_session_t *s0;
850   u32 offset, seq;
851
852   s0 = stream_session_get (tc->c_s_index, tc->c_thread_index);
853   seq = vnet_buffer (b)->tcp.seq_number;
854   offset = seq - tc->rcv_nxt;
855
856   if (svm_fifo_enqueue_with_offset (s0->server_rx_fifo, s0->pid, offset,
857                                     data_len, vlib_buffer_get_current (b)))
858     return TCP_ERROR_FIFO_FULL;
859
860   /* Update SACK list if in use */
861   if (tcp_opts_sack_permitted (&tc->opt))
862     {
863       ooo_segment_t *newest;
864       u32 start, end;
865
866       /* Get the newest segment from the fifo */
867       newest = svm_fifo_newest_ooo_segment (s0->server_rx_fifo);
868       start = tc->rcv_nxt + ooo_segment_offset (s0->server_rx_fifo, newest);
869       end = tc->rcv_nxt + ooo_segment_end_offset (s0->server_rx_fifo, newest);
870
871       tcp_update_sack_list (tc, start, end);
872     }
873
874   return TCP_ERROR_ENQUEUED;
875 }
876
877 /**
878  * Check if ACK could be delayed. DELACK timer is set only after frame is
879  * processed so this can return true for a full bursts of packets.
880  */
881 always_inline int
882 tcp_can_delack (tcp_connection_t * tc)
883 {
884   /* If there's no DELACK timer set and the last window sent wasn't 0 we
885    * can safely delay. */
886   if (!tcp_timer_is_active (tc, TCP_TIMER_DELACK)
887       && (tc->flags & TCP_CONN_SENT_RCV_WND0) == 0
888       && (tc->flags & TCP_CONN_SNDACK) == 0)
889     return 1;
890
891   return 0;
892 }
893
894 static int
895 tcp_segment_rcv (tcp_main_t * tm, tcp_connection_t * tc, vlib_buffer_t * b,
896                  u16 n_data_bytes, u32 * next0)
897 {
898   u32 error = 0;
899
900   /* Handle out-of-order data */
901   if (PREDICT_FALSE (vnet_buffer (b)->tcp.seq_number != tc->rcv_nxt))
902     {
903       error = tcp_session_enqueue_ooo (tc, b, n_data_bytes);
904
905       /* Don't send more than 3 dupacks per burst
906        * XXX decide if this is good */
907       if (tc->snt_dupacks < 3)
908         {
909           /* RFC2581: Send DUPACK for fast retransmit */
910           tcp_make_ack (tc, b);
911           *next0 = tcp_next_output (tc->c_is_ip4);
912
913           /* Mark as DUPACK. We may filter these in output if
914            * the burst fills the holes. */
915           vnet_buffer (b)->tcp.flags = TCP_BUF_FLAG_DUPACK;
916
917           tc->snt_dupacks++;
918         }
919
920       goto done;
921     }
922
923   /* In order data, enqueue. Fifo figures out by itself if any out-of-order
924    * segments can be enqueued after fifo tail offset changes. */
925   error = tcp_session_enqueue_data (tc, b, n_data_bytes);
926
927   TCP_EVT_DBG (TCP_EVT_INPUT, tc, n_data_bytes);
928
929   /* Check if ACK can be delayed */
930   if (tcp_can_delack (tc))
931     {
932       /* Nothing to do for pure ACKs */
933       if (n_data_bytes == 0)
934         goto done;
935
936       /* If connection has not been previously marked for delay ack
937        * add it to the list and flag it */
938       if (!tc->flags & TCP_CONN_DELACK)
939         {
940           vec_add1 (tm->delack_connections[tc->c_thread_index],
941                     tc->c_c_index);
942           tc->flags |= TCP_CONN_DELACK;
943         }
944     }
945   else
946     {
947       /* Check if a packet has already been enqueued to output for burst.
948        * If yes, then drop this one, otherwise, let it pass through to
949        * output */
950       if ((tc->flags & TCP_CONN_BURSTACK) == 0)
951         {
952           *next0 = tcp_next_output (tc->c_is_ip4);
953           tcp_make_ack (tc, b);
954           error = TCP_ERROR_ENQUEUED;
955
956           /* TODO: maybe add counter to ensure N acks will be sent/burst */
957           tc->flags |= TCP_CONN_BURSTACK;
958         }
959     }
960
961 done:
962   return error;
963 }
964
965 void
966 delack_timers_init (tcp_main_t * tm, u32 thread_index)
967 {
968   tcp_connection_t *tc;
969   u32 i, *conns;
970   tw_timer_wheel_16t_2w_512sl_t *tw;
971
972   tw = &tm->timer_wheels[thread_index];
973   conns = tm->delack_connections[thread_index];
974   for (i = 0; i < vec_len (conns); i++)
975     {
976       tc = pool_elt_at_index (tm->connections[thread_index], conns[i]);
977       ASSERT (0 != tc);
978
979       tc->timers[TCP_TIMER_DELACK]
980         = tw_timer_start_16t_2w_512sl (tw, conns[i],
981                                        TCP_TIMER_DELACK, TCP_DELACK_TIME);
982     }
983   vec_reset_length (tm->delack_connections[thread_index]);
984 }
985
986 always_inline uword
987 tcp46_established_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
988                           vlib_frame_t * from_frame, int is_ip4)
989 {
990   u32 n_left_from, next_index, *from, *to_next;
991   u32 my_thread_index = vm->cpu_index, errors = 0;
992   tcp_main_t *tm = vnet_get_tcp_main ();
993
994   from = vlib_frame_vector_args (from_frame);
995   n_left_from = from_frame->n_vectors;
996
997   next_index = node->cached_next_index;
998
999   while (n_left_from > 0)
1000     {
1001       u32 n_left_to_next;
1002
1003       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1004
1005       while (n_left_from > 0 && n_left_to_next > 0)
1006         {
1007           u32 bi0;
1008           vlib_buffer_t *b0;
1009           tcp_header_t *th0 = 0;
1010           tcp_connection_t *tc0;
1011           ip4_header_t *ip40;
1012           ip6_header_t *ip60;
1013           u32 n_advance_bytes0, n_data_bytes0;
1014           u32 next0 = TCP_ESTABLISHED_NEXT_DROP, error0 = TCP_ERROR_ENQUEUED;
1015
1016           bi0 = from[0];
1017           to_next[0] = bi0;
1018           from += 1;
1019           to_next += 1;
1020           n_left_from -= 1;
1021           n_left_to_next -= 1;
1022
1023           b0 = vlib_get_buffer (vm, bi0);
1024           tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
1025                                     my_thread_index);
1026
1027           if (PREDICT_FALSE (tc0 == 0))
1028             {
1029               error0 = TCP_ERROR_INVALID_CONNECTION;
1030               goto drop;
1031             }
1032
1033           /* Checksum computed by ipx_local no need to compute again */
1034
1035           if (is_ip4)
1036             {
1037               ip40 = vlib_buffer_get_current (b0);
1038               th0 = ip4_next_header (ip40);
1039               n_advance_bytes0 = (ip4_header_bytes (ip40)
1040                                   + tcp_header_bytes (th0));
1041               n_data_bytes0 = clib_net_to_host_u16 (ip40->length)
1042                 - n_advance_bytes0;
1043             }
1044           else
1045             {
1046               ip60 = vlib_buffer_get_current (b0);
1047               th0 = ip6_next_header (ip60);
1048               n_advance_bytes0 = tcp_header_bytes (th0);
1049               n_data_bytes0 = clib_net_to_host_u16 (ip60->payload_length)
1050                 - n_advance_bytes0;
1051               n_advance_bytes0 += sizeof (ip60[0]);
1052             }
1053
1054           /* SYNs, FINs and data consume sequence numbers */
1055           vnet_buffer (b0)->tcp.seq_end = vnet_buffer (b0)->tcp.seq_number
1056             + tcp_is_syn (th0) + tcp_is_fin (th0) + n_data_bytes0;
1057
1058           /* TODO header prediction fast path */
1059
1060           /* 1-4: check SEQ, RST, SYN */
1061           if (PREDICT_FALSE (tcp_segment_validate (vm, tc0, b0, th0, &next0)))
1062             {
1063               error0 = TCP_ERROR_SEGMENT_INVALID;
1064               goto drop;
1065             }
1066
1067           /* 5: check the ACK field  */
1068           if (tcp_rcv_ack (tc0, b0, th0, &next0, &error0))
1069             {
1070               goto drop;
1071             }
1072
1073           /* 6: check the URG bit TODO */
1074
1075           /* 7: process the segment text */
1076           vlib_buffer_advance (b0, n_advance_bytes0);
1077           error0 = tcp_segment_rcv (tm, tc0, b0, n_data_bytes0, &next0);
1078
1079           /* 8: check the FIN bit */
1080           if (tcp_fin (th0))
1081             {
1082               /* Enter CLOSE-WAIT and notify session. Don't send ACK, instead
1083                * wait for session to call close. To avoid lingering
1084                * in CLOSE-WAIT, set timer (reuse WAITCLOSE). */
1085               tc0->state = TCP_STATE_CLOSE_WAIT;
1086               TCP_EVT_DBG (TCP_EVT_FIN_RCVD, tc0);
1087               stream_session_disconnect_notify (&tc0->connection);
1088               tcp_timer_set (tc0, TCP_TIMER_WAITCLOSE, TCP_CLOSEWAIT_TIME);
1089             }
1090
1091         drop:
1092           b0->error = node->errors[error0];
1093           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1094             {
1095
1096             }
1097
1098           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
1099                                            n_left_to_next, bi0, next0);
1100         }
1101
1102       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1103     }
1104
1105   errors = session_manager_flush_enqueue_events (my_thread_index);
1106   if (errors)
1107     {
1108       if (is_ip4)
1109         vlib_node_increment_counter (vm, tcp4_established_node.index,
1110                                      TCP_ERROR_EVENT_FIFO_FULL, errors);
1111       else
1112         vlib_node_increment_counter (vm, tcp6_established_node.index,
1113                                      TCP_ERROR_EVENT_FIFO_FULL, errors);
1114     }
1115
1116   delack_timers_init (tm, my_thread_index);
1117
1118   return from_frame->n_vectors;
1119 }
1120
1121 static uword
1122 tcp4_established (vlib_main_t * vm, vlib_node_runtime_t * node,
1123                   vlib_frame_t * from_frame)
1124 {
1125   return tcp46_established_inline (vm, node, from_frame, 1 /* is_ip4 */ );
1126 }
1127
1128 static uword
1129 tcp6_established (vlib_main_t * vm, vlib_node_runtime_t * node,
1130                   vlib_frame_t * from_frame)
1131 {
1132   return tcp46_established_inline (vm, node, from_frame, 0 /* is_ip4 */ );
1133 }
1134
1135 /* *INDENT-OFF* */
1136 VLIB_REGISTER_NODE (tcp4_established_node) =
1137 {
1138   .function = tcp4_established,
1139   .name = "tcp4-established",
1140   /* Takes a vector of packets. */
1141   .vector_size = sizeof (u32),
1142   .n_errors = TCP_N_ERROR,
1143   .error_strings = tcp_error_strings,
1144   .n_next_nodes = TCP_ESTABLISHED_N_NEXT,
1145   .next_nodes =
1146   {
1147 #define _(s,n) [TCP_ESTABLISHED_NEXT_##s] = n,
1148     foreach_tcp_state_next
1149 #undef _
1150   },
1151 };
1152 /* *INDENT-ON* */
1153
1154 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_established_node, tcp4_established);
1155
1156 /* *INDENT-OFF* */
1157 VLIB_REGISTER_NODE (tcp6_established_node) =
1158 {
1159   .function = tcp6_established,
1160   .name = "tcp6-established",
1161   /* Takes a vector of packets. */
1162   .vector_size = sizeof (u32),
1163   .n_errors = TCP_N_ERROR,
1164   .error_strings = tcp_error_strings,
1165   .n_next_nodes = TCP_ESTABLISHED_N_NEXT,
1166   .next_nodes =
1167   {
1168 #define _(s,n) [TCP_ESTABLISHED_NEXT_##s] = n,
1169     foreach_tcp_state_next
1170 #undef _
1171   },
1172 };
1173 /* *INDENT-ON* */
1174
1175
1176 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_established_node, tcp6_established);
1177
1178 vlib_node_registration_t tcp4_syn_sent_node;
1179 vlib_node_registration_t tcp6_syn_sent_node;
1180
1181 always_inline uword
1182 tcp46_syn_sent_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
1183                        vlib_frame_t * from_frame, int is_ip4)
1184 {
1185   tcp_main_t *tm = vnet_get_tcp_main ();
1186   u32 n_left_from, next_index, *from, *to_next;
1187   u32 my_thread_index = vm->cpu_index, errors = 0;
1188   u8 sst = is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
1189
1190   from = vlib_frame_vector_args (from_frame);
1191   n_left_from = from_frame->n_vectors;
1192
1193   next_index = node->cached_next_index;
1194
1195   while (n_left_from > 0)
1196     {
1197       u32 n_left_to_next;
1198
1199       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1200
1201       while (n_left_from > 0 && n_left_to_next > 0)
1202         {
1203           u32 bi0, ack0, seq0;
1204           vlib_buffer_t *b0;
1205           tcp_header_t *tcp0 = 0;
1206           tcp_connection_t *tc0;
1207           ip4_header_t *ip40;
1208           ip6_header_t *ip60;
1209           u32 n_advance_bytes0, n_data_bytes0;
1210           tcp_connection_t *new_tc0;
1211           u32 next0 = TCP_SYN_SENT_NEXT_DROP, error0 = TCP_ERROR_ENQUEUED;
1212
1213           bi0 = from[0];
1214           to_next[0] = bi0;
1215           from += 1;
1216           to_next += 1;
1217           n_left_from -= 1;
1218           n_left_to_next -= 1;
1219
1220           b0 = vlib_get_buffer (vm, bi0);
1221           tc0 =
1222             tcp_half_open_connection_get (vnet_buffer (b0)->
1223                                           tcp.connection_index);
1224
1225           ack0 = vnet_buffer (b0)->tcp.ack_number;
1226           seq0 = vnet_buffer (b0)->tcp.seq_number;
1227
1228           /* Checksum computed by ipx_local no need to compute again */
1229
1230           if (is_ip4)
1231             {
1232               ip40 = vlib_buffer_get_current (b0);
1233               tcp0 = ip4_next_header (ip40);
1234               n_advance_bytes0 = (ip4_header_bytes (ip40)
1235                                   + tcp_header_bytes (tcp0));
1236               n_data_bytes0 = clib_net_to_host_u16 (ip40->length)
1237                 - n_advance_bytes0;
1238             }
1239           else
1240             {
1241               ip60 = vlib_buffer_get_current (b0);
1242               tcp0 = ip6_next_header (ip60);
1243               n_advance_bytes0 = tcp_header_bytes (tcp0);
1244               n_data_bytes0 = clib_net_to_host_u16 (ip60->payload_length)
1245                 - n_advance_bytes0;
1246               n_advance_bytes0 += sizeof (ip60[0]);
1247             }
1248
1249           if (PREDICT_FALSE
1250               (!tcp_ack (tcp0) && !tcp_rst (tcp0) && !tcp_syn (tcp0)))
1251             goto drop;
1252
1253           /* SYNs, FINs and data consume sequence numbers */
1254           vnet_buffer (b0)->tcp.seq_end = seq0 + tcp_is_syn (tcp0)
1255             + tcp_is_fin (tcp0) + n_data_bytes0;
1256
1257           /*
1258            *  1. check the ACK bit
1259            */
1260
1261           /*
1262            *   If the ACK bit is set
1263            *     If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send a reset (unless
1264            *     the RST bit is set, if so drop the segment and return)
1265            *       <SEQ=SEG.ACK><CTL=RST>
1266            *     and discard the segment.  Return.
1267            *     If SND.UNA =< SEG.ACK =< SND.NXT then the ACK is acceptable.
1268            */
1269           if (tcp_ack (tcp0))
1270             {
1271               if (ack0 <= tc0->iss || ack0 > tc0->snd_nxt)
1272                 {
1273                   if (!tcp_rst (tcp0))
1274                     tcp_send_reset (b0, is_ip4);
1275
1276                   goto drop;
1277                 }
1278
1279               /* Make sure ACK is valid */
1280               if (tc0->snd_una > ack0)
1281                 goto drop;
1282             }
1283
1284           /*
1285            * 2. check the RST bit
1286            */
1287
1288           if (tcp_rst (tcp0))
1289             {
1290               /* If ACK is acceptable, signal client that peer is not
1291                * willing to accept connection and drop connection*/
1292               if (tcp_ack (tcp0))
1293                 {
1294                   stream_session_connect_notify (&tc0->connection, sst,
1295                                                  1 /* fail */ );
1296                   tcp_connection_cleanup (tc0);
1297                 }
1298               goto drop;
1299             }
1300
1301           /*
1302            * 3. check the security and precedence (skipped)
1303            */
1304
1305           /*
1306            * 4. check the SYN bit
1307            */
1308
1309           /* No SYN flag. Drop. */
1310           if (!tcp_syn (tcp0))
1311             goto drop;
1312
1313           /* Stop connection establishment and retransmit timers */
1314           tcp_timer_reset (tc0, TCP_TIMER_ESTABLISH);
1315           tcp_timer_reset (tc0, TCP_TIMER_RETRANSMIT_SYN);
1316
1317           /* Valid SYN or SYN-ACK. Move connection from half-open pool to
1318            * current thread pool. */
1319           pool_get (tm->connections[my_thread_index], new_tc0);
1320           clib_memcpy (new_tc0, tc0, sizeof (*new_tc0));
1321
1322           new_tc0->c_thread_index = my_thread_index;
1323
1324           /* Cleanup half-open connection XXX lock */
1325           pool_put (tm->half_open_connections, tc0);
1326
1327           new_tc0->rcv_nxt = vnet_buffer (b0)->tcp.seq_end;
1328           new_tc0->irs = seq0;
1329
1330           /* Parse options */
1331           tcp_options_parse (tcp0, &new_tc0->opt);
1332
1333           if (tcp_opts_tstamp (&new_tc0->opt))
1334             {
1335               new_tc0->tsval_recent = new_tc0->opt.tsval;
1336               new_tc0->tsval_recent_age = tcp_time_now ();
1337             }
1338
1339           if (tcp_opts_wscale (&new_tc0->opt))
1340             new_tc0->snd_wscale = new_tc0->opt.wscale;
1341
1342           /* No scaling */
1343           new_tc0->snd_wnd = clib_net_to_host_u16 (tcp0->window);
1344           new_tc0->snd_wl1 = seq0;
1345           new_tc0->snd_wl2 = ack0;
1346
1347           tcp_connection_init_vars (new_tc0);
1348
1349           /* SYN-ACK: See if we can switch to ESTABLISHED state */
1350           if (tcp_ack (tcp0))
1351             {
1352               /* Our SYN is ACKed: we have iss < ack = snd_una */
1353
1354               /* TODO Dequeue acknowledged segments if we support Fast Open */
1355               new_tc0->snd_una = ack0;
1356               new_tc0->state = TCP_STATE_ESTABLISHED;
1357
1358               /* Make sure las is initialized for the wnd computation */
1359               new_tc0->rcv_las = new_tc0->rcv_nxt;
1360
1361               /* Notify app that we have connection */
1362               stream_session_connect_notify (&new_tc0->connection, sst, 0);
1363
1364               /* Make sure after data segment processing ACK is sent */
1365               new_tc0->flags |= TCP_CONN_SNDACK;
1366             }
1367           /* SYN: Simultaneous open. Change state to SYN-RCVD and send SYN-ACK */
1368           else
1369             {
1370               new_tc0->state = TCP_STATE_SYN_RCVD;
1371
1372               /* Notify app that we have connection */
1373               stream_session_connect_notify (&new_tc0->connection, sst, 0);
1374
1375               tcp_make_synack (new_tc0, b0);
1376               next0 = tcp_next_output (is_ip4);
1377
1378               goto drop;
1379             }
1380
1381           /* Read data, if any */
1382           if (n_data_bytes0)
1383             {
1384               error0 =
1385                 tcp_segment_rcv (tm, new_tc0, b0, n_data_bytes0, &next0);
1386               if (error0 == TCP_ERROR_PURE_ACK)
1387                 error0 = TCP_ERROR_SYN_ACKS_RCVD;
1388             }
1389           else
1390             {
1391               tcp_make_ack (new_tc0, b0);
1392               next0 = tcp_next_output (new_tc0->c_is_ip4);
1393             }
1394
1395         drop:
1396
1397           b0->error = error0 ? node->errors[error0] : 0;
1398           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1399             {
1400
1401             }
1402
1403           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
1404                                            n_left_to_next, bi0, next0);
1405         }
1406
1407       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1408     }
1409
1410   errors = session_manager_flush_enqueue_events (my_thread_index);
1411   if (errors)
1412     {
1413       if (is_ip4)
1414         vlib_node_increment_counter (vm, tcp4_established_node.index,
1415                                      TCP_ERROR_EVENT_FIFO_FULL, errors);
1416       else
1417         vlib_node_increment_counter (vm, tcp6_established_node.index,
1418                                      TCP_ERROR_EVENT_FIFO_FULL, errors);
1419     }
1420
1421   return from_frame->n_vectors;
1422 }
1423
1424 static uword
1425 tcp4_syn_sent (vlib_main_t * vm, vlib_node_runtime_t * node,
1426                vlib_frame_t * from_frame)
1427 {
1428   return tcp46_syn_sent_inline (vm, node, from_frame, 1 /* is_ip4 */ );
1429 }
1430
1431 static uword
1432 tcp6_syn_sent_rcv (vlib_main_t * vm, vlib_node_runtime_t * node,
1433                    vlib_frame_t * from_frame)
1434 {
1435   return tcp46_syn_sent_inline (vm, node, from_frame, 0 /* is_ip4 */ );
1436 }
1437
1438 /* *INDENT-OFF* */
1439 VLIB_REGISTER_NODE (tcp4_syn_sent_node) =
1440 {
1441   .function = tcp4_syn_sent,
1442   .name = "tcp4-syn-sent",
1443   /* Takes a vector of packets. */
1444   .vector_size = sizeof (u32),
1445   .n_errors = TCP_N_ERROR,
1446   .error_strings = tcp_error_strings,
1447   .n_next_nodes = TCP_SYN_SENT_N_NEXT,
1448   .next_nodes =
1449   {
1450 #define _(s,n) [TCP_SYN_SENT_NEXT_##s] = n,
1451     foreach_tcp_state_next
1452 #undef _
1453   },
1454 };
1455 /* *INDENT-ON* */
1456
1457 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_syn_sent_node, tcp4_syn_sent);
1458
1459 /* *INDENT-OFF* */
1460 VLIB_REGISTER_NODE (tcp6_syn_sent_node) =
1461 {
1462   .function = tcp6_syn_sent_rcv,
1463   .name = "tcp6-syn-sent",
1464   /* Takes a vector of packets. */
1465   .vector_size = sizeof (u32),
1466   .n_errors = TCP_N_ERROR,
1467   .error_strings = tcp_error_strings,
1468   .n_next_nodes = TCP_SYN_SENT_N_NEXT,
1469   .next_nodes =
1470   {
1471 #define _(s,n) [TCP_SYN_SENT_NEXT_##s] = n,
1472     foreach_tcp_state_next
1473 #undef _
1474   }
1475 ,};
1476 /* *INDENT-ON* */
1477
1478 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_syn_sent_node, tcp6_syn_sent_rcv);
1479 /**
1480  * Handles reception for all states except LISTEN, SYN-SENT and ESTABLISHED
1481  * as per RFC793 p. 64
1482  */
1483 always_inline uword
1484 tcp46_rcv_process_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
1485                           vlib_frame_t * from_frame, int is_ip4)
1486 {
1487   tcp_main_t *tm = vnet_get_tcp_main ();
1488   u32 n_left_from, next_index, *from, *to_next;
1489   u32 my_thread_index = vm->cpu_index, errors = 0;
1490
1491   from = vlib_frame_vector_args (from_frame);
1492   n_left_from = from_frame->n_vectors;
1493
1494   next_index = node->cached_next_index;
1495
1496   while (n_left_from > 0)
1497     {
1498       u32 n_left_to_next;
1499
1500       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1501
1502       while (n_left_from > 0 && n_left_to_next > 0)
1503         {
1504           u32 bi0;
1505           vlib_buffer_t *b0;
1506           tcp_header_t *tcp0 = 0;
1507           tcp_connection_t *tc0;
1508           ip4_header_t *ip40;
1509           ip6_header_t *ip60;
1510           u32 n_advance_bytes0, n_data_bytes0;
1511           u32 next0 = TCP_RCV_PROCESS_NEXT_DROP, error0 = TCP_ERROR_ENQUEUED;
1512
1513           bi0 = from[0];
1514           to_next[0] = bi0;
1515           from += 1;
1516           to_next += 1;
1517           n_left_from -= 1;
1518           n_left_to_next -= 1;
1519
1520           b0 = vlib_get_buffer (vm, bi0);
1521           tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
1522                                     my_thread_index);
1523           if (PREDICT_FALSE (tc0 == 0))
1524             {
1525               error0 = TCP_ERROR_INVALID_CONNECTION;
1526               goto drop;
1527             }
1528
1529           /* Checksum computed by ipx_local no need to compute again */
1530
1531           if (is_ip4)
1532             {
1533               ip40 = vlib_buffer_get_current (b0);
1534               tcp0 = ip4_next_header (ip40);
1535               n_advance_bytes0 = (ip4_header_bytes (ip40)
1536                                   + tcp_header_bytes (tcp0));
1537               n_data_bytes0 = clib_net_to_host_u16 (ip40->length)
1538                 - n_advance_bytes0;
1539             }
1540           else
1541             {
1542               ip60 = vlib_buffer_get_current (b0);
1543               tcp0 = ip6_next_header (ip60);
1544               n_advance_bytes0 = tcp_header_bytes (tcp0);
1545               n_data_bytes0 = clib_net_to_host_u16 (ip60->payload_length)
1546                 - n_advance_bytes0;
1547               n_advance_bytes0 += sizeof (ip60[0]);
1548             }
1549
1550           /* SYNs, FINs and data consume sequence numbers */
1551           vnet_buffer (b0)->tcp.seq_end = vnet_buffer (b0)->tcp.seq_number
1552             + tcp_is_syn (tcp0) + tcp_is_fin (tcp0) + n_data_bytes0;
1553
1554           /*
1555            * Special treatment for CLOSED
1556            */
1557           switch (tc0->state)
1558             {
1559             case TCP_STATE_CLOSED:
1560               goto drop;
1561               break;
1562             }
1563
1564           /*
1565            * For all other states (except LISTEN)
1566            */
1567
1568           /* 1-4: check SEQ, RST, SYN */
1569           if (PREDICT_FALSE
1570               (tcp_segment_validate (vm, tc0, b0, tcp0, &next0)))
1571             {
1572               error0 = TCP_ERROR_SEGMENT_INVALID;
1573               goto drop;
1574             }
1575
1576           /* 5: check the ACK field  */
1577           switch (tc0->state)
1578             {
1579             case TCP_STATE_SYN_RCVD:
1580               /*
1581                * If the segment acknowledgment is not acceptable, form a
1582                * reset segment,
1583                *  <SEQ=SEG.ACK><CTL=RST>
1584                * and send it.
1585                */
1586               if (!tcp_rcv_ack_is_acceptable (tc0, b0))
1587                 {
1588                   tcp_send_reset (b0, is_ip4);
1589                   goto drop;
1590                 }
1591               /* Switch state to ESTABLISHED */
1592               tc0->state = TCP_STATE_ESTABLISHED;
1593
1594               /* Initialize session variables */
1595               tc0->snd_una = vnet_buffer (b0)->tcp.ack_number;
1596               tc0->snd_wnd = clib_net_to_host_u16 (tcp0->window)
1597                 << tc0->opt.wscale;
1598               tc0->snd_wl1 = vnet_buffer (b0)->tcp.seq_number;
1599               tc0->snd_wl2 = vnet_buffer (b0)->tcp.ack_number;
1600
1601               /* Shoulder tap the server */
1602               stream_session_accept_notify (&tc0->connection);
1603
1604               /* Reset SYN-ACK retransmit timer */
1605               tcp_timer_reset (tc0, TCP_TIMER_RETRANSMIT);
1606               break;
1607             case TCP_STATE_ESTABLISHED:
1608               /* We can get packets in established state here because they
1609                * were enqueued before state change */
1610               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
1611                 goto drop;
1612
1613               break;
1614             case TCP_STATE_FIN_WAIT_1:
1615               /* In addition to the processing for the ESTABLISHED state, if
1616                * our FIN is now acknowledged then enter FIN-WAIT-2 and
1617                * continue processing in that state. */
1618               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
1619                 goto drop;
1620
1621               /* If FIN is ACKed */
1622               if (tc0->snd_una == tc0->snd_una_max)
1623                 {
1624                   tc0->state = TCP_STATE_FIN_WAIT_2;
1625                   /* Stop all timers, 2MSL will be set lower */
1626                   tcp_connection_timers_reset (tc0);
1627                 }
1628               break;
1629             case TCP_STATE_FIN_WAIT_2:
1630               /* In addition to the processing for the ESTABLISHED state, if
1631                * the retransmission queue is empty, the user's CLOSE can be
1632                * acknowledged ("ok") but do not delete the TCB. */
1633               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
1634                 goto drop;
1635               /* check if rtx queue is empty and ack CLOSE TODO */
1636               break;
1637             case TCP_STATE_CLOSE_WAIT:
1638               /* Do the same processing as for the ESTABLISHED state. */
1639               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
1640                 goto drop;
1641               break;
1642             case TCP_STATE_CLOSING:
1643               /* In addition to the processing for the ESTABLISHED state, if
1644                * the ACK acknowledges our FIN then enter the TIME-WAIT state,
1645                * otherwise ignore the segment. */
1646               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
1647                 goto drop;
1648
1649               /* XXX test that send queue empty */
1650               tc0->state = TCP_STATE_TIME_WAIT;
1651               goto drop;
1652
1653               break;
1654             case TCP_STATE_LAST_ACK:
1655               /* The only thing that can arrive in this state is an
1656                * acknowledgment of our FIN. If our FIN is now acknowledged,
1657                * delete the TCB, enter the CLOSED state, and return. */
1658
1659               if (!tcp_rcv_ack_is_acceptable (tc0, b0))
1660                 goto drop;
1661
1662               tc0->state = TCP_STATE_CLOSED;
1663
1664               /* Don't delete the connection/session yet. Instead, wait a
1665                * reasonable amount of time until the pipes are cleared. In
1666                * particular, this makes sure that we won't have dead sessions
1667                * when processing events on the tx path */
1668               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_CLEANUP_TIME);
1669
1670               /* Stop retransmit */
1671               tcp_timer_reset (tc0, TCP_TIMER_RETRANSMIT);
1672
1673               goto drop;
1674
1675               break;
1676             case TCP_STATE_TIME_WAIT:
1677               /* The only thing that can arrive in this state is a
1678                * retransmission of the remote FIN. Acknowledge it, and restart
1679                * the 2 MSL timeout. */
1680
1681               /* TODO */
1682               goto drop;
1683               break;
1684             default:
1685               ASSERT (0);
1686             }
1687
1688           /* 6: check the URG bit TODO */
1689
1690           /* 7: process the segment text */
1691           switch (tc0->state)
1692             {
1693             case TCP_STATE_ESTABLISHED:
1694             case TCP_STATE_FIN_WAIT_1:
1695             case TCP_STATE_FIN_WAIT_2:
1696               error0 = tcp_segment_rcv (tm, tc0, b0, n_data_bytes0, &next0);
1697               break;
1698             case TCP_STATE_CLOSE_WAIT:
1699             case TCP_STATE_CLOSING:
1700             case TCP_STATE_LAST_ACK:
1701             case TCP_STATE_TIME_WAIT:
1702               /* This should not occur, since a FIN has been received from the
1703                * remote side.  Ignore the segment text. */
1704               break;
1705             }
1706
1707           /* 8: check the FIN bit */
1708           if (!tcp_fin (tcp0))
1709             goto drop;
1710
1711           switch (tc0->state)
1712             {
1713             case TCP_STATE_ESTABLISHED:
1714             case TCP_STATE_SYN_RCVD:
1715               /* Send FIN-ACK notify app and enter CLOSE-WAIT */
1716               tcp_connection_timers_reset (tc0);
1717               tcp_make_fin (tc0, b0);
1718               next0 = tcp_next_output (tc0->c_is_ip4);
1719               stream_session_disconnect_notify (&tc0->connection);
1720               tc0->state = TCP_STATE_CLOSE_WAIT;
1721               break;
1722             case TCP_STATE_CLOSE_WAIT:
1723             case TCP_STATE_CLOSING:
1724             case TCP_STATE_LAST_ACK:
1725               /* move along .. */
1726               break;
1727             case TCP_STATE_FIN_WAIT_1:
1728               tc0->state = TCP_STATE_TIME_WAIT;
1729               tcp_connection_timers_reset (tc0);
1730               tcp_timer_set (tc0, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
1731               break;
1732             case TCP_STATE_FIN_WAIT_2:
1733               /* Got FIN, send ACK! */
1734               tc0->state = TCP_STATE_TIME_WAIT;
1735               tcp_timer_set (tc0, TCP_TIMER_WAITCLOSE, TCP_CLOSEWAIT_TIME);
1736               tcp_make_ack (tc0, b0);
1737               next0 = tcp_next_output (is_ip4);
1738               break;
1739             case TCP_STATE_TIME_WAIT:
1740               /* Remain in the TIME-WAIT state. Restart the 2 MSL time-wait
1741                * timeout.
1742                */
1743               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
1744               break;
1745             }
1746           TCP_EVT_DBG (TCP_EVT_FIN_RCVD, tc0);
1747
1748           b0->error = error0 ? node->errors[error0] : 0;
1749
1750         drop:
1751           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1752             {
1753
1754             }
1755
1756           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
1757                                            n_left_to_next, bi0, next0);
1758         }
1759
1760       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1761     }
1762
1763   errors = session_manager_flush_enqueue_events (my_thread_index);
1764   if (errors)
1765     {
1766       if (is_ip4)
1767         vlib_node_increment_counter (vm, tcp4_established_node.index,
1768                                      TCP_ERROR_EVENT_FIFO_FULL, errors);
1769       else
1770         vlib_node_increment_counter (vm, tcp6_established_node.index,
1771                                      TCP_ERROR_EVENT_FIFO_FULL, errors);
1772     }
1773
1774   return from_frame->n_vectors;
1775 }
1776
1777 static uword
1778 tcp4_rcv_process (vlib_main_t * vm, vlib_node_runtime_t * node,
1779                   vlib_frame_t * from_frame)
1780 {
1781   return tcp46_rcv_process_inline (vm, node, from_frame, 1 /* is_ip4 */ );
1782 }
1783
1784 static uword
1785 tcp6_rcv_process (vlib_main_t * vm, vlib_node_runtime_t * node,
1786                   vlib_frame_t * from_frame)
1787 {
1788   return tcp46_rcv_process_inline (vm, node, from_frame, 0 /* is_ip4 */ );
1789 }
1790
1791 /* *INDENT-OFF* */
1792 VLIB_REGISTER_NODE (tcp4_rcv_process_node) =
1793 {
1794   .function = tcp4_rcv_process,
1795   .name = "tcp4-rcv-process",
1796   /* Takes a vector of packets. */
1797   .vector_size = sizeof (u32),
1798   .n_errors = TCP_N_ERROR,
1799   .error_strings = tcp_error_strings,
1800   .n_next_nodes = TCP_RCV_PROCESS_N_NEXT,
1801   .next_nodes =
1802   {
1803 #define _(s,n) [TCP_RCV_PROCESS_NEXT_##s] = n,
1804     foreach_tcp_state_next
1805 #undef _
1806   },
1807 };
1808 /* *INDENT-ON* */
1809
1810 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_rcv_process_node, tcp4_rcv_process);
1811
1812 /* *INDENT-OFF* */
1813 VLIB_REGISTER_NODE (tcp6_rcv_process_node) =
1814 {
1815   .function = tcp6_rcv_process,
1816   .name = "tcp6-rcv-process",
1817   /* Takes a vector of packets. */
1818   .vector_size = sizeof (u32),
1819   .n_errors = TCP_N_ERROR,
1820   .error_strings = tcp_error_strings,
1821   .n_next_nodes = TCP_RCV_PROCESS_N_NEXT,
1822   .next_nodes =
1823   {
1824 #define _(s,n) [TCP_RCV_PROCESS_NEXT_##s] = n,
1825     foreach_tcp_state_next
1826 #undef _
1827   },
1828 };
1829 /* *INDENT-ON* */
1830
1831 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_rcv_process_node, tcp6_rcv_process);
1832
1833 vlib_node_registration_t tcp4_listen_node;
1834 vlib_node_registration_t tcp6_listen_node;
1835
1836 /**
1837  * LISTEN state processing as per RFC 793 p. 65
1838  */
1839 always_inline uword
1840 tcp46_listen_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
1841                      vlib_frame_t * from_frame, int is_ip4)
1842 {
1843   u32 n_left_from, next_index, *from, *to_next;
1844   u32 my_thread_index = vm->cpu_index;
1845   tcp_main_t *tm = vnet_get_tcp_main ();
1846   u8 sst = is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
1847
1848   from = vlib_frame_vector_args (from_frame);
1849   n_left_from = from_frame->n_vectors;
1850
1851   next_index = node->cached_next_index;
1852
1853   while (n_left_from > 0)
1854     {
1855       u32 n_left_to_next;
1856
1857       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1858
1859       while (n_left_from > 0 && n_left_to_next > 0)
1860         {
1861           u32 bi0;
1862           vlib_buffer_t *b0;
1863           tcp_header_t *th0 = 0;
1864           tcp_connection_t *lc0;
1865           ip4_header_t *ip40;
1866           ip6_header_t *ip60;
1867           tcp_connection_t *child0;
1868           u32 error0 = TCP_ERROR_SYNS_RCVD, next0 = TCP_LISTEN_NEXT_DROP;
1869
1870           bi0 = from[0];
1871           to_next[0] = bi0;
1872           from += 1;
1873           to_next += 1;
1874           n_left_from -= 1;
1875           n_left_to_next -= 1;
1876
1877           b0 = vlib_get_buffer (vm, bi0);
1878           lc0 = tcp_listener_get (vnet_buffer (b0)->tcp.connection_index);
1879
1880           if (is_ip4)
1881             {
1882               ip40 = vlib_buffer_get_current (b0);
1883               th0 = ip4_next_header (ip40);
1884             }
1885           else
1886             {
1887               ip60 = vlib_buffer_get_current (b0);
1888               th0 = ip6_next_header (ip60);
1889             }
1890
1891           /* Create child session. For syn-flood protection use filter */
1892
1893           /* 1. first check for an RST */
1894           if (tcp_rst (th0))
1895             goto drop;
1896
1897           /* 2. second check for an ACK */
1898           if (tcp_ack (th0))
1899             {
1900               tcp_send_reset (b0, is_ip4);
1901               goto drop;
1902             }
1903
1904           /* 3. check for a SYN (did that already) */
1905
1906           /* Create child session and send SYN-ACK */
1907           pool_get (tm->connections[my_thread_index], child0);
1908           memset (child0, 0, sizeof (*child0));
1909
1910           child0->c_c_index = child0 - tm->connections[my_thread_index];
1911           child0->c_lcl_port = lc0->c_lcl_port;
1912           child0->c_rmt_port = th0->src_port;
1913           child0->c_is_ip4 = is_ip4;
1914           child0->c_thread_index = my_thread_index;
1915
1916           if (is_ip4)
1917             {
1918               child0->c_lcl_ip4.as_u32 = ip40->dst_address.as_u32;
1919               child0->c_rmt_ip4.as_u32 = ip40->src_address.as_u32;
1920             }
1921           else
1922             {
1923               clib_memcpy (&child0->c_lcl_ip6, &ip60->dst_address,
1924                            sizeof (ip6_address_t));
1925               clib_memcpy (&child0->c_rmt_ip6, &ip60->src_address,
1926                            sizeof (ip6_address_t));
1927             }
1928
1929           if (stream_session_accept (&child0->connection, lc0->c_s_index, sst,
1930                                      0 /* notify */ ))
1931             {
1932               error0 = TCP_ERROR_CREATE_SESSION_FAIL;
1933               goto drop;
1934             }
1935
1936           tcp_options_parse (th0, &child0->opt);
1937
1938           child0->irs = vnet_buffer (b0)->tcp.seq_number;
1939           child0->rcv_nxt = vnet_buffer (b0)->tcp.seq_number + 1;
1940           child0->state = TCP_STATE_SYN_RCVD;
1941
1942           /* RFC1323: TSval timestamps sent on {SYN} and {SYN,ACK}
1943            * segments are used to initialize PAWS. */
1944           if (tcp_opts_tstamp (&child0->opt))
1945             {
1946               child0->tsval_recent = child0->opt.tsval;
1947               child0->tsval_recent_age = tcp_time_now ();
1948             }
1949
1950           if (tcp_opts_wscale (&child0->opt))
1951             child0->snd_wscale = child0->opt.wscale;
1952
1953           /* No scaling */
1954           child0->snd_wnd = clib_net_to_host_u16 (th0->window);
1955           child0->snd_wl1 = vnet_buffer (b0)->tcp.seq_number;
1956           child0->snd_wl2 = vnet_buffer (b0)->tcp.ack_number;
1957
1958           tcp_connection_init_vars (child0);
1959
1960           TCP_EVT_DBG (TCP_EVT_SYN_RCVD, child0);
1961
1962           /* Reuse buffer to make syn-ack and send */
1963           tcp_make_synack (child0, b0);
1964           next0 = tcp_next_output (is_ip4);
1965
1966         drop:
1967           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1968             {
1969
1970             }
1971
1972           b0->error = node->errors[error0];
1973
1974           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
1975                                            n_left_to_next, bi0, next0);
1976         }
1977
1978       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1979     }
1980   return from_frame->n_vectors;
1981 }
1982
1983 static uword
1984 tcp4_listen (vlib_main_t * vm, vlib_node_runtime_t * node,
1985              vlib_frame_t * from_frame)
1986 {
1987   return tcp46_listen_inline (vm, node, from_frame, 1 /* is_ip4 */ );
1988 }
1989
1990 static uword
1991 tcp6_listen (vlib_main_t * vm, vlib_node_runtime_t * node,
1992              vlib_frame_t * from_frame)
1993 {
1994   return tcp46_listen_inline (vm, node, from_frame, 0 /* is_ip4 */ );
1995 }
1996
1997 /* *INDENT-OFF* */
1998 VLIB_REGISTER_NODE (tcp4_listen_node) =
1999 {
2000   .function = tcp4_listen,
2001   .name = "tcp4-listen",
2002   /* Takes a vector of packets. */
2003   .vector_size = sizeof (u32),
2004   .n_errors = TCP_N_ERROR,
2005   .error_strings = tcp_error_strings,
2006   .n_next_nodes = TCP_LISTEN_N_NEXT,
2007   .next_nodes =
2008   {
2009 #define _(s,n) [TCP_LISTEN_NEXT_##s] = n,
2010     foreach_tcp_state_next
2011 #undef _
2012   },
2013 };
2014 /* *INDENT-ON* */
2015
2016 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_listen_node, tcp4_listen);
2017
2018 /* *INDENT-OFF* */
2019 VLIB_REGISTER_NODE (tcp6_listen_node) =
2020 {
2021   .function = tcp6_listen,
2022   .name = "tcp6-listen",
2023   /* Takes a vector of packets. */
2024   .vector_size = sizeof (u32),
2025   .n_errors = TCP_N_ERROR,
2026   .error_strings = tcp_error_strings,
2027   .n_next_nodes = TCP_LISTEN_N_NEXT,
2028   .next_nodes =
2029   {
2030 #define _(s,n) [TCP_LISTEN_NEXT_##s] = n,
2031     foreach_tcp_state_next
2032 #undef _
2033   },
2034 };
2035 /* *INDENT-ON* */
2036
2037 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_listen_node, tcp6_listen);
2038
2039 vlib_node_registration_t tcp4_input_node;
2040 vlib_node_registration_t tcp6_input_node;
2041
2042 typedef enum _tcp_input_next
2043 {
2044   TCP_INPUT_NEXT_DROP,
2045   TCP_INPUT_NEXT_LISTEN,
2046   TCP_INPUT_NEXT_RCV_PROCESS,
2047   TCP_INPUT_NEXT_SYN_SENT,
2048   TCP_INPUT_NEXT_ESTABLISHED,
2049   TCP_INPUT_NEXT_RESET,
2050   TCP_INPUT_N_NEXT
2051 } tcp_input_next_t;
2052
2053 #define foreach_tcp4_input_next                 \
2054   _ (DROP, "error-drop")                        \
2055   _ (LISTEN, "tcp4-listen")                     \
2056   _ (RCV_PROCESS, "tcp4-rcv-process")           \
2057   _ (SYN_SENT, "tcp4-syn-sent")                 \
2058   _ (ESTABLISHED, "tcp4-established")           \
2059   _ (RESET, "tcp4-reset")
2060
2061 #define foreach_tcp6_input_next                 \
2062   _ (DROP, "error-drop")                        \
2063   _ (LISTEN, "tcp6-listen")                     \
2064   _ (RCV_PROCESS, "tcp6-rcv-process")           \
2065   _ (SYN_SENT, "tcp6-syn-sent")                 \
2066   _ (ESTABLISHED, "tcp6-established")           \
2067   _ (RESET, "tcp6-reset")
2068
2069 typedef struct
2070 {
2071   u16 src_port;
2072   u16 dst_port;
2073   u8 state;
2074 } tcp_rx_trace_t;
2075
2076 u8 *
2077 format_tcp_rx_trace (u8 * s, va_list * args)
2078 {
2079   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
2080   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
2081   tcp_rx_trace_t *t = va_arg (*args, tcp_rx_trace_t *);
2082
2083   s = format (s, "TCP: src-port %d dst-port %U%s\n",
2084               clib_net_to_host_u16 (t->src_port),
2085               clib_net_to_host_u16 (t->dst_port), format_tcp_state, t->state);
2086
2087   return s;
2088 }
2089
2090 #define filter_flags (TCP_FLAG_SYN|TCP_FLAG_ACK|TCP_FLAG_RST|TCP_FLAG_FIN)
2091
2092 always_inline uword
2093 tcp46_input_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
2094                     vlib_frame_t * from_frame, int is_ip4)
2095 {
2096   u32 n_left_from, next_index, *from, *to_next;
2097   u32 my_thread_index = vm->cpu_index;
2098   tcp_main_t *tm = vnet_get_tcp_main ();
2099
2100   from = vlib_frame_vector_args (from_frame);
2101   n_left_from = from_frame->n_vectors;
2102
2103   next_index = node->cached_next_index;
2104
2105   while (n_left_from > 0)
2106     {
2107       u32 n_left_to_next;
2108
2109       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
2110
2111       while (n_left_from > 0 && n_left_to_next > 0)
2112         {
2113           u32 bi0;
2114           vlib_buffer_t *b0;
2115           tcp_header_t *tcp0 = 0;
2116           tcp_connection_t *tc0;
2117           ip4_header_t *ip40;
2118           ip6_header_t *ip60;
2119           u32 error0 = TCP_ERROR_NO_LISTENER, next0 = TCP_INPUT_NEXT_DROP;
2120           u8 flags0;
2121
2122           bi0 = from[0];
2123           to_next[0] = bi0;
2124           from += 1;
2125           to_next += 1;
2126           n_left_from -= 1;
2127           n_left_to_next -= 1;
2128
2129           b0 = vlib_get_buffer (vm, bi0);
2130           vnet_buffer (b0)->tcp.flags = 0;
2131
2132           if (is_ip4)
2133             {
2134               ip40 = vlib_buffer_get_current (b0);
2135               tcp0 = ip4_next_header (ip40);
2136
2137               /* lookup session */
2138               tc0 =
2139                 (tcp_connection_t *)
2140                 stream_session_lookup_transport4 (&ip40->dst_address,
2141                                                   &ip40->src_address,
2142                                                   tcp0->dst_port,
2143                                                   tcp0->src_port,
2144                                                   SESSION_TYPE_IP4_TCP,
2145                                                   my_thread_index);
2146             }
2147           else
2148             {
2149               ip60 = vlib_buffer_get_current (b0);
2150               tcp0 = ip6_next_header (ip60);
2151               tc0 =
2152                 (tcp_connection_t *)
2153                 stream_session_lookup_transport6 (&ip60->src_address,
2154                                                   &ip60->dst_address,
2155                                                   tcp0->src_port,
2156                                                   tcp0->dst_port,
2157                                                   SESSION_TYPE_IP6_TCP,
2158                                                   my_thread_index);
2159             }
2160
2161           /* Session exists */
2162           if (PREDICT_TRUE (0 != tc0))
2163             {
2164               /* Save connection index */
2165               vnet_buffer (b0)->tcp.connection_index = tc0->c_c_index;
2166               vnet_buffer (b0)->tcp.seq_number =
2167                 clib_net_to_host_u32 (tcp0->seq_number);
2168               vnet_buffer (b0)->tcp.ack_number =
2169                 clib_net_to_host_u32 (tcp0->ack_number);
2170
2171               flags0 = tcp0->flags & filter_flags;
2172               next0 = tm->dispatch_table[tc0->state][flags0].next;
2173               error0 = tm->dispatch_table[tc0->state][flags0].error;
2174
2175               if (PREDICT_FALSE (error0 == TCP_ERROR_DISPATCH))
2176                 {
2177                   /* Overload tcp flags to store state */
2178                   vnet_buffer (b0)->tcp.flags = tc0->state;
2179                 }
2180             }
2181           else
2182             {
2183               /* Send reset */
2184               next0 = TCP_INPUT_NEXT_RESET;
2185               error0 = TCP_ERROR_NO_LISTENER;
2186             }
2187
2188           b0->error = error0 ? node->errors[error0] : 0;
2189
2190           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
2191             {
2192
2193             }
2194
2195           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
2196                                            n_left_to_next, bi0, next0);
2197         }
2198
2199       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
2200     }
2201
2202   return from_frame->n_vectors;
2203 }
2204
2205 static uword
2206 tcp4_input (vlib_main_t * vm, vlib_node_runtime_t * node,
2207             vlib_frame_t * from_frame)
2208 {
2209   return tcp46_input_inline (vm, node, from_frame, 1 /* is_ip4 */ );
2210 }
2211
2212 static uword
2213 tcp6_input (vlib_main_t * vm, vlib_node_runtime_t * node,
2214             vlib_frame_t * from_frame)
2215 {
2216   return tcp46_input_inline (vm, node, from_frame, 0 /* is_ip4 */ );
2217 }
2218
2219 /* *INDENT-OFF* */
2220 VLIB_REGISTER_NODE (tcp4_input_node) =
2221 {
2222   .function = tcp4_input,
2223   .name = "tcp4-input",
2224   /* Takes a vector of packets. */
2225   .vector_size = sizeof (u32),
2226   .n_errors = TCP_N_ERROR,
2227   .error_strings = tcp_error_strings,
2228   .n_next_nodes = TCP_INPUT_N_NEXT,
2229   .next_nodes =
2230   {
2231 #define _(s,n) [TCP_INPUT_NEXT_##s] = n,
2232     foreach_tcp4_input_next
2233 #undef _
2234   },
2235   .format_buffer = format_tcp_header,
2236   .format_trace = format_tcp_rx_trace,
2237 };
2238 /* *INDENT-ON* */
2239
2240 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_input_node, tcp4_input);
2241
2242 /* *INDENT-OFF* */
2243 VLIB_REGISTER_NODE (tcp6_input_node) =
2244 {
2245   .function = tcp6_input,
2246   .name = "tcp6-input",
2247   /* Takes a vector of packets. */
2248   .vector_size = sizeof (u32),
2249   .n_errors = TCP_N_ERROR,
2250   .error_strings = tcp_error_strings,
2251   .n_next_nodes = TCP_INPUT_N_NEXT,
2252   .next_nodes =
2253   {
2254 #define _(s,n) [TCP_INPUT_NEXT_##s] = n,
2255     foreach_tcp6_input_next
2256 #undef _
2257   },
2258   .format_buffer = format_tcp_header,
2259   .format_trace = format_tcp_rx_trace,
2260 };
2261 /* *INDENT-ON* */
2262
2263 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_input_node, tcp6_input);
2264 void
2265 tcp_update_time (f64 now, u32 thread_index)
2266 {
2267   tcp_main_t *tm = vnet_get_tcp_main ();
2268   tw_timer_expire_timers_16t_2w_512sl (&tm->timer_wheels[thread_index], now);
2269 }
2270
2271 static void
2272 tcp_dispatch_table_init (tcp_main_t * tm)
2273 {
2274   int i, j;
2275   for (i = 0; i < ARRAY_LEN (tm->dispatch_table); i++)
2276     for (j = 0; j < ARRAY_LEN (tm->dispatch_table[i]); j++)
2277       {
2278         tm->dispatch_table[i][j].next = TCP_INPUT_NEXT_DROP;
2279         tm->dispatch_table[i][j].error = TCP_ERROR_DISPATCH;
2280       }
2281
2282 #define _(t,f,n,e)                                              \
2283 do {                                                            \
2284     tm->dispatch_table[TCP_STATE_##t][f].next = (n);            \
2285     tm->dispatch_table[TCP_STATE_##t][f].error = (e);           \
2286 } while (0)
2287
2288   /* SYNs for new connections -> tcp-listen. */
2289   _(LISTEN, TCP_FLAG_SYN, TCP_INPUT_NEXT_LISTEN, TCP_ERROR_NONE);
2290   /* ACK for for a SYN-ACK -> tcp-rcv-process. */
2291   _(SYN_RCVD, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
2292   /* SYN-ACK for a SYN */
2293   _(SYN_SENT, TCP_FLAG_SYN | TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT,
2294     TCP_ERROR_NONE);
2295   _(SYN_SENT, TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT, TCP_ERROR_NONE);
2296   _(SYN_SENT, TCP_FLAG_RST, TCP_INPUT_NEXT_SYN_SENT, TCP_ERROR_NONE);
2297   _(SYN_SENT, TCP_FLAG_RST | TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT,
2298     TCP_ERROR_NONE);
2299   /* ACK for for established connection -> tcp-established. */
2300   _(ESTABLISHED, TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
2301   /* FIN for for established connection -> tcp-established. */
2302   _(ESTABLISHED, TCP_FLAG_FIN, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
2303   _(ESTABLISHED, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED,
2304     TCP_ERROR_NONE);
2305   _(ESTABLISHED, TCP_FLAG_RST, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
2306   /* ACK or FIN-ACK to our FIN */
2307   _(FIN_WAIT_1, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
2308   _(FIN_WAIT_1, TCP_FLAG_ACK | TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS,
2309     TCP_ERROR_NONE);
2310   /* FIN in reply to our FIN from the other side */
2311   _(FIN_WAIT_1, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
2312   /* FIN confirming that the peer (app) has closed */
2313   _(FIN_WAIT_2, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
2314   _(FIN_WAIT_2, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
2315     TCP_ERROR_NONE);
2316   _(LAST_ACK, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
2317 #undef _
2318 }
2319
2320 clib_error_t *
2321 tcp_input_init (vlib_main_t * vm)
2322 {
2323   clib_error_t *error = 0;
2324   tcp_main_t *tm = vnet_get_tcp_main ();
2325
2326   if ((error = vlib_call_init_function (vm, tcp_init)))
2327     return error;
2328
2329   /* Initialize dispatch table. */
2330   tcp_dispatch_table_init (tm);
2331
2332   return error;
2333 }
2334
2335 VLIB_INIT_FUNCTION (tcp_input_init);
2336
2337 /*
2338  * fd.io coding-style-patch-verification: ON
2339  *
2340  * Local Variables:
2341  * eval: (c-set-style "gnu")
2342  * End:
2343  */