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