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