tcp: accept fins if in recovery
[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   _ (DROP4, "ip4-drop")                         \
31   _ (DROP6, "ip6-drop")                         \
32   _ (TCP4_OUTPUT, "tcp4-output")                \
33   _ (TCP6_OUTPUT, "tcp6-output")
34
35 typedef enum _tcp_established_next
36 {
37 #define _(s,n) TCP_ESTABLISHED_NEXT_##s,
38   foreach_tcp_state_next
39 #undef _
40     TCP_ESTABLISHED_N_NEXT,
41 } tcp_established_next_t;
42
43 typedef enum _tcp_rcv_process_next
44 {
45 #define _(s,n) TCP_RCV_PROCESS_NEXT_##s,
46   foreach_tcp_state_next
47 #undef _
48     TCP_RCV_PROCESS_N_NEXT,
49 } tcp_rcv_process_next_t;
50
51 typedef enum _tcp_syn_sent_next
52 {
53 #define _(s,n) TCP_SYN_SENT_NEXT_##s,
54   foreach_tcp_state_next
55 #undef _
56     TCP_SYN_SENT_N_NEXT,
57 } tcp_syn_sent_next_t;
58
59 typedef enum _tcp_listen_next
60 {
61 #define _(s,n) TCP_LISTEN_NEXT_##s,
62   foreach_tcp_state_next
63 #undef _
64     TCP_LISTEN_N_NEXT,
65 } tcp_listen_next_t;
66
67 /* Generic, state independent indices */
68 typedef enum _tcp_state_next
69 {
70 #define _(s,n) TCP_NEXT_##s,
71   foreach_tcp_state_next
72 #undef _
73     TCP_STATE_N_NEXT,
74 } tcp_state_next_t;
75
76 #define tcp_next_output(is_ip4) (is_ip4 ? TCP_NEXT_TCP4_OUTPUT          \
77                                         : TCP_NEXT_TCP6_OUTPUT)
78
79 #define tcp_next_drop(is_ip4) (is_ip4 ? TCP_NEXT_DROP4                  \
80                                       : TCP_NEXT_DROP6)
81
82 vlib_node_registration_t tcp4_established_node;
83 vlib_node_registration_t tcp6_established_node;
84
85 /**
86  * Validate segment sequence number. As per RFC793:
87  *
88  * Segment Receive Test
89  *      Length  Window
90  *      ------- -------  -------------------------------------------
91  *      0       0       SEG.SEQ = RCV.NXT
92  *      0       >0      RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
93  *      >0      0       not acceptable
94  *      >0      >0      RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
95  *                      or RCV.NXT =< SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND
96  *
97  * This ultimately consists in checking if segment falls within the window.
98  * The one important difference compared to RFC793 is that we use rcv_las,
99  * or the rcv_nxt at last ack sent instead of rcv_nxt since that's the
100  * peer's reference when computing our receive window.
101  *
102  * This:
103  *  seq_leq (end_seq, tc->rcv_las + tc->rcv_wnd) && seq_geq (seq, tc->rcv_las)
104  * however, is too strict when we have retransmits. Instead we just check that
105  * the seq is not beyond the right edge and that the end of the segment is not
106  * less than the left edge.
107  *
108  * N.B. rcv_nxt and rcv_wnd are both updated in this node if acks are sent, so
109  * use rcv_nxt in the right edge window test instead of rcv_las.
110  *
111  */
112 always_inline u8
113 tcp_segment_in_rcv_wnd (tcp_connection_t * tc, u32 seq, u32 end_seq)
114 {
115   return (seq_geq (end_seq, tc->rcv_las)
116           && seq_leq (seq, tc->rcv_nxt + tc->rcv_wnd));
117 }
118
119 /**
120  * Parse TCP header options.
121  *
122  * @param th TCP header
123  * @param to TCP options data structure to be populated
124  * @return -1 if parsing failed
125  */
126 static int
127 tcp_options_parse (tcp_header_t * th, tcp_options_t * to)
128 {
129   const u8 *data;
130   u8 opt_len, opts_len, kind;
131   int j;
132   sack_block_t b;
133
134   opts_len = (tcp_doff (th) << 2) - sizeof (tcp_header_t);
135   data = (const u8 *) (th + 1);
136
137   /* Zero out all flags but those set in SYN */
138   to->flags &= (TCP_OPTS_FLAG_SACK_PERMITTED | TCP_OPTS_FLAG_WSCALE);
139
140   for (; opts_len > 0; opts_len -= opt_len, data += opt_len)
141     {
142       kind = data[0];
143
144       /* Get options length */
145       if (kind == TCP_OPTION_EOL)
146         break;
147       else if (kind == TCP_OPTION_NOOP)
148         {
149           opt_len = 1;
150           continue;
151         }
152       else
153         {
154           /* broken options */
155           if (opts_len < 2)
156             return -1;
157           opt_len = data[1];
158
159           /* weird option length */
160           if (opt_len < 2 || opt_len > opts_len)
161             return -1;
162         }
163
164       /* Parse options */
165       switch (kind)
166         {
167         case TCP_OPTION_MSS:
168           if ((opt_len == TCP_OPTION_LEN_MSS) && tcp_syn (th))
169             {
170               to->flags |= TCP_OPTS_FLAG_MSS;
171               to->mss = clib_net_to_host_u16 (*(u16 *) (data + 2));
172             }
173           break;
174         case TCP_OPTION_WINDOW_SCALE:
175           if ((opt_len == TCP_OPTION_LEN_WINDOW_SCALE) && tcp_syn (th))
176             {
177               to->flags |= TCP_OPTS_FLAG_WSCALE;
178               to->wscale = data[2];
179               if (to->wscale > TCP_MAX_WND_SCALE)
180                 {
181                   clib_warning ("Illegal window scaling value: %d",
182                                 to->wscale);
183                   to->wscale = TCP_MAX_WND_SCALE;
184                 }
185             }
186           break;
187         case TCP_OPTION_TIMESTAMP:
188           if (opt_len == TCP_OPTION_LEN_TIMESTAMP)
189             {
190               to->flags |= TCP_OPTS_FLAG_TSTAMP;
191               to->tsval = clib_net_to_host_u32 (*(u32 *) (data + 2));
192               to->tsecr = clib_net_to_host_u32 (*(u32 *) (data + 6));
193             }
194           break;
195         case TCP_OPTION_SACK_PERMITTED:
196           if (opt_len == TCP_OPTION_LEN_SACK_PERMITTED && tcp_syn (th))
197             to->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
198           break;
199         case TCP_OPTION_SACK_BLOCK:
200           /* If SACK permitted was not advertised or a SYN, break */
201           if ((to->flags & TCP_OPTS_FLAG_SACK_PERMITTED) == 0 || tcp_syn (th))
202             break;
203
204           /* If too short or not correctly formatted, break */
205           if (opt_len < 10 || ((opt_len - 2) % TCP_OPTION_LEN_SACK_BLOCK))
206             break;
207
208           to->flags |= TCP_OPTS_FLAG_SACK;
209           to->n_sack_blocks = (opt_len - 2) / TCP_OPTION_LEN_SACK_BLOCK;
210           vec_reset_length (to->sacks);
211           for (j = 0; j < to->n_sack_blocks; j++)
212             {
213               b.start = clib_net_to_host_u32 (*(u32 *) (data + 2 + 8 * j));
214               b.end = clib_net_to_host_u32 (*(u32 *) (data + 6 + 8 * j));
215               vec_add1 (to->sacks, b);
216             }
217           break;
218         default:
219           /* Nothing to see here */
220           continue;
221         }
222     }
223   return 0;
224 }
225
226 /**
227  * RFC1323: Check against wrapped sequence numbers (PAWS). If we have
228  * timestamp to echo and it's less than tsval_recent, drop segment
229  * but still send an ACK in order to retain TCP's mechanism for detecting
230  * and recovering from half-open connections
231  *
232  * Or at least that's what the theory says. It seems that this might not work
233  * very well with packet reordering and fast retransmit. XXX
234  */
235 always_inline int
236 tcp_segment_check_paws (tcp_connection_t * tc)
237 {
238   return tcp_opts_tstamp (&tc->rcv_opts) && tc->tsval_recent
239     && timestamp_lt (tc->rcv_opts.tsval, tc->tsval_recent);
240 }
241
242 /**
243  * Update tsval recent
244  */
245 always_inline void
246 tcp_update_timestamp (tcp_connection_t * tc, u32 seq, u32 seq_end)
247 {
248   /*
249    * RFC1323: If Last.ACK.sent falls within the range of sequence numbers
250    * of an incoming segment:
251    *    SEG.SEQ <= Last.ACK.sent < SEG.SEQ + SEG.LEN
252    * then the TSval from the segment is copied to TS.Recent;
253    * otherwise, the TSval is ignored.
254    */
255   if (tcp_opts_tstamp (&tc->rcv_opts) && seq_leq (seq, tc->rcv_las)
256       && seq_leq (tc->rcv_las, seq_end))
257     {
258       ASSERT (timestamp_leq (tc->tsval_recent, tc->rcv_opts.tsval));
259       tc->tsval_recent = tc->rcv_opts.tsval;
260       tc->tsval_recent_age = tcp_time_now ();
261     }
262 }
263
264 /**
265  * Validate incoming segment as per RFC793 p. 69 and RFC1323 p. 19
266  *
267  * It first verifies if segment has a wrapped sequence number (PAWS) and then
268  * does the processing associated to the first four steps (ignoring security
269  * and precedence): sequence number, rst bit and syn bit checks.
270  *
271  * @return 0 if segments passes validation.
272  */
273 static int
274 tcp_segment_validate (vlib_main_t * vm, tcp_connection_t * tc0,
275                       vlib_buffer_t * b0, tcp_header_t * th0,
276                       u32 * next0, u32 * error0)
277 {
278   /* We could get a burst of RSTs interleaved with acks */
279   if (PREDICT_FALSE (tc0->state == TCP_STATE_CLOSED))
280     {
281       tcp_send_reset (tc0);
282       *error0 = TCP_ERROR_CONNECTION_CLOSED;
283       goto drop;
284     }
285
286   if (PREDICT_FALSE (!tcp_ack (th0) && !tcp_rst (th0) && !tcp_syn (th0)))
287     {
288       *error0 = TCP_ERROR_SEGMENT_INVALID;
289       goto drop;
290     }
291
292   if (PREDICT_FALSE (tcp_options_parse (th0, &tc0->rcv_opts)))
293     {
294       clib_warning ("options parse error");
295       *error0 = TCP_ERROR_OPTIONS;
296       goto drop;
297     }
298
299   if (PREDICT_FALSE (tcp_segment_check_paws (tc0)))
300     {
301       *error0 = TCP_ERROR_PAWS;
302       if (CLIB_DEBUG > 2)
303         clib_warning ("paws failed\n%U", format_tcp_connection, tc0, 2);
304       TCP_EVT_DBG (TCP_EVT_PAWS_FAIL, tc0, vnet_buffer (b0)->tcp.seq_number,
305                    vnet_buffer (b0)->tcp.seq_end);
306
307       /* If it just so happens that a segment updates tsval_recent for a
308        * segment over 24 days old, invalidate tsval_recent. */
309       if (timestamp_lt (tc0->tsval_recent_age + TCP_PAWS_IDLE,
310                         tcp_time_now ()))
311         {
312           /* Age isn't reset until we get a valid tsval (bsd inspired) */
313           tc0->tsval_recent = 0;
314           clib_warning ("paws failed - really old segment. REALLY?");
315         }
316       else
317         {
318           /* Drop after ack if not rst */
319           if (!tcp_rst (th0))
320             {
321               tcp_make_ack (tc0, b0);
322               TCP_EVT_DBG (TCP_EVT_DUPACK_SENT, tc0, vnet_buffer (b0)->tcp);
323               goto error;
324             }
325         }
326       goto drop;
327     }
328
329   /* 1st: check sequence number */
330   if (!tcp_segment_in_rcv_wnd (tc0, vnet_buffer (b0)->tcp.seq_number,
331                                vnet_buffer (b0)->tcp.seq_end))
332     {
333       *error0 = TCP_ERROR_RCV_WND;
334       /* If our window is 0 and the packet is in sequence, let it pass
335        * through for ack processing. It should be dropped later. */
336       if (!(tc0->rcv_wnd == 0
337             && tc0->rcv_nxt == vnet_buffer (b0)->tcp.seq_number))
338         {
339           /* If not RST, send dup ack */
340           if (!tcp_rst (th0))
341             {
342               tcp_make_ack (tc0, b0);
343               TCP_EVT_DBG (TCP_EVT_DUPACK_SENT, tc0, vnet_buffer (b0)->tcp);
344               goto error;
345             }
346           goto drop;
347         }
348     }
349
350   /* 2nd: check the RST bit */
351   if (PREDICT_FALSE (tcp_rst (th0)))
352     {
353       tcp_connection_reset (tc0);
354       *error0 = TCP_ERROR_RST_RCVD;
355       goto drop;
356     }
357
358   /* 3rd: check security and precedence (skip) */
359
360   /* 4th: check the SYN bit */
361   if (PREDICT_FALSE (tcp_syn (th0)))
362     {
363       /* TODO implement RFC 5961 */
364       if (tc0->state == TCP_STATE_SYN_RCVD)
365         {
366           tcp_make_synack (tc0, b0);
367           TCP_EVT_DBG (TCP_EVT_SYN_RCVD, tc0, 0);
368         }
369       else
370         {
371           tcp_make_ack (tc0, b0);
372           TCP_EVT_DBG (TCP_EVT_SYNACK_RCVD, tc0);
373         }
374       goto error;
375     }
376
377   /* If segment in window, save timestamp */
378   tcp_update_timestamp (tc0, vnet_buffer (b0)->tcp.seq_number,
379                         vnet_buffer (b0)->tcp.seq_end);
380   return 0;
381
382 drop:
383   *next0 = tcp_next_drop (tc0->c_is_ip4);
384   return -1;
385 error:
386   *next0 = tcp_next_output (tc0->c_is_ip4);
387   return -1;
388 }
389
390 always_inline int
391 tcp_rcv_ack_is_acceptable (tcp_connection_t * tc0, vlib_buffer_t * tb0)
392 {
393   /* SND.UNA =< SEG.ACK =< SND.NXT */
394   return (seq_leq (tc0->snd_una, vnet_buffer (tb0)->tcp.ack_number)
395           && seq_leq (vnet_buffer (tb0)->tcp.ack_number, tc0->snd_nxt));
396 }
397
398 /**
399  * Compute smoothed RTT as per VJ's '88 SIGCOMM and RFC6298
400  *
401  * Note that although the original article, srtt and rttvar are scaled
402  * to minimize round-off errors, here we don't. Instead, we rely on
403  * better precision time measurements.
404  *
405  * TODO support us rtt resolution
406  */
407 static void
408 tcp_estimate_rtt (tcp_connection_t * tc, u32 mrtt)
409 {
410   int err, diff;
411
412   if (tc->srtt != 0)
413     {
414       err = mrtt - tc->srtt;
415
416       /* XXX Drop in RTT results in RTTVAR increase and bigger RTO.
417        * The increase should be bound */
418       tc->srtt = clib_max ((int) tc->srtt + (err >> 3), 1);
419       diff = (clib_abs (err) - (int) tc->rttvar) >> 2;
420       tc->rttvar = clib_max ((int) tc->rttvar + diff, 1);
421     }
422   else
423     {
424       /* First measurement. */
425       tc->srtt = mrtt;
426       tc->rttvar = mrtt >> 1;
427     }
428 }
429
430 void
431 tcp_update_rto (tcp_connection_t * tc)
432 {
433   tc->rto = clib_min (tc->srtt + (tc->rttvar << 2), TCP_RTO_MAX);
434   tc->rto = clib_max (tc->rto, TCP_RTO_MIN);
435 }
436
437 /**
438  * Update RTT estimate and RTO timer
439  *
440  * Measure RTT: We have two sources of RTT measurements: TSOPT and ACK
441  * timing. Middle boxes are known to fiddle with TCP options so we
442  * should give higher priority to ACK timing.
443  *
444  * This should be called only if previously sent bytes have been acked.
445  *
446  * return 1 if valid rtt 0 otherwise
447  */
448 static int
449 tcp_update_rtt (tcp_connection_t * tc, u32 ack)
450 {
451   u32 mrtt = 0;
452
453   /* Karn's rule, part 1. Don't use retransmitted segments to estimate
454    * RTT because they're ambiguous. */
455   if (tcp_in_cong_recovery (tc) || tc->sack_sb.sacked_bytes)
456     {
457       if (tcp_in_recovery (tc))
458         return 0;
459       goto done;
460     }
461
462   if (tc->rtt_ts && seq_geq (ack, tc->rtt_seq))
463     {
464       mrtt = tcp_time_now () - tc->rtt_ts;
465     }
466   /* As per RFC7323 TSecr can be used for RTTM only if the segment advances
467    * snd_una, i.e., the left side of the send window:
468    * seq_lt (tc->snd_una, ack). This is a condition for calling update_rtt */
469   else if (tcp_opts_tstamp (&tc->rcv_opts) && tc->rcv_opts.tsecr)
470     {
471       mrtt = tcp_time_now () - tc->rcv_opts.tsecr;
472     }
473
474   /* Ignore dubious measurements */
475   if (mrtt == 0 || mrtt > TCP_RTT_MAX)
476     goto done;
477
478   tcp_estimate_rtt (tc, mrtt);
479
480 done:
481
482   /* Allow measuring of a new RTT */
483   tc->rtt_ts = 0;
484
485   /* If we got here something must've been ACKed so make sure boff is 0,
486    * even if mrtt is not valid since we update the rto lower */
487   tc->rto_boff = 0;
488   tcp_update_rto (tc);
489
490   return 0;
491 }
492
493 /**
494  * Dequeue bytes that have been acked and while at it update RTT estimates.
495  */
496 static void
497 tcp_dequeue_acked (tcp_connection_t * tc, u32 ack)
498 {
499   /* Dequeue the newly ACKed add SACKed bytes */
500   stream_session_dequeue_drop (&tc->connection,
501                                tc->bytes_acked + tc->sack_sb.snd_una_adv);
502
503   tcp_validate_txf_size (tc, tc->snd_una_max - tc->snd_una);
504
505   /* Update rtt and rto */
506   tcp_update_rtt (tc, ack);
507
508   /* If everything has been acked, stop retransmit timer
509    * otherwise update. */
510   tcp_retransmit_timer_update (tc);
511 }
512
513 /**
514  * Check if duplicate ack as per RFC5681 Sec. 2
515  */
516 static u8
517 tcp_ack_is_dupack (tcp_connection_t * tc, vlib_buffer_t * b, u32 prev_snd_wnd,
518                    u32 prev_snd_una)
519 {
520   return ((vnet_buffer (b)->tcp.ack_number == prev_snd_una)
521           && seq_gt (tc->snd_una_max, tc->snd_una)
522           && (vnet_buffer (b)->tcp.seq_end == vnet_buffer (b)->tcp.seq_number)
523           && (prev_snd_wnd == tc->snd_wnd));
524 }
525
526 /**
527  * Checks if ack is a congestion control event.
528  */
529 static u8
530 tcp_ack_is_cc_event (tcp_connection_t * tc, vlib_buffer_t * b,
531                      u32 prev_snd_wnd, u32 prev_snd_una, u8 * is_dack)
532 {
533   /* Check if ack is duplicate. Per RFC 6675, ACKs that SACK new data are
534    * defined to be 'duplicate' */
535   *is_dack = tc->sack_sb.last_sacked_bytes
536     || tcp_ack_is_dupack (tc, b, prev_snd_wnd, prev_snd_una);
537
538   return ((*is_dack || tcp_in_cong_recovery (tc)) && !tcp_is_lost_fin (tc));
539 }
540
541 static u32
542 scoreboard_hole_index (sack_scoreboard_t * sb, sack_scoreboard_hole_t * hole)
543 {
544   ASSERT (!pool_is_free_index (sb->holes, hole - sb->holes));
545   return hole - sb->holes;
546 }
547
548 static u32
549 scoreboard_hole_bytes (sack_scoreboard_hole_t * hole)
550 {
551   return hole->end - hole->start;
552 }
553
554 sack_scoreboard_hole_t *
555 scoreboard_get_hole (sack_scoreboard_t * sb, u32 index)
556 {
557   if (index != TCP_INVALID_SACK_HOLE_INDEX)
558     return pool_elt_at_index (sb->holes, index);
559   return 0;
560 }
561
562 sack_scoreboard_hole_t *
563 scoreboard_next_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * hole)
564 {
565   if (hole->next != TCP_INVALID_SACK_HOLE_INDEX)
566     return pool_elt_at_index (sb->holes, hole->next);
567   return 0;
568 }
569
570 sack_scoreboard_hole_t *
571 scoreboard_prev_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * hole)
572 {
573   if (hole->prev != TCP_INVALID_SACK_HOLE_INDEX)
574     return pool_elt_at_index (sb->holes, hole->prev);
575   return 0;
576 }
577
578 sack_scoreboard_hole_t *
579 scoreboard_first_hole (sack_scoreboard_t * sb)
580 {
581   if (sb->head != TCP_INVALID_SACK_HOLE_INDEX)
582     return pool_elt_at_index (sb->holes, sb->head);
583   return 0;
584 }
585
586 sack_scoreboard_hole_t *
587 scoreboard_last_hole (sack_scoreboard_t * sb)
588 {
589   if (sb->tail != TCP_INVALID_SACK_HOLE_INDEX)
590     return pool_elt_at_index (sb->holes, sb->tail);
591   return 0;
592 }
593
594 static void
595 scoreboard_remove_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * hole)
596 {
597   sack_scoreboard_hole_t *next, *prev;
598
599   if (hole->next != TCP_INVALID_SACK_HOLE_INDEX)
600     {
601       next = pool_elt_at_index (sb->holes, hole->next);
602       next->prev = hole->prev;
603     }
604   else
605     {
606       sb->tail = hole->prev;
607     }
608
609   if (hole->prev != TCP_INVALID_SACK_HOLE_INDEX)
610     {
611       prev = pool_elt_at_index (sb->holes, hole->prev);
612       prev->next = hole->next;
613     }
614   else
615     {
616       sb->head = hole->next;
617     }
618
619   if (scoreboard_hole_index (sb, hole) == sb->cur_rxt_hole)
620     sb->cur_rxt_hole = TCP_INVALID_SACK_HOLE_INDEX;
621
622   /* Poison the entry */
623   if (CLIB_DEBUG > 0)
624     memset (hole, 0xfe, sizeof (*hole));
625
626   pool_put (sb->holes, hole);
627 }
628
629 static sack_scoreboard_hole_t *
630 scoreboard_insert_hole (sack_scoreboard_t * sb, u32 prev_index,
631                         u32 start, u32 end)
632 {
633   sack_scoreboard_hole_t *hole, *next, *prev;
634   u32 hole_index;
635
636   pool_get (sb->holes, hole);
637   memset (hole, 0, sizeof (*hole));
638
639   hole->start = start;
640   hole->end = end;
641   hole_index = scoreboard_hole_index (sb, hole);
642
643   prev = scoreboard_get_hole (sb, prev_index);
644   if (prev)
645     {
646       hole->prev = prev_index;
647       hole->next = prev->next;
648
649       if ((next = scoreboard_next_hole (sb, hole)))
650         next->prev = hole_index;
651       else
652         sb->tail = hole_index;
653
654       prev->next = hole_index;
655     }
656   else
657     {
658       sb->head = hole_index;
659       hole->prev = TCP_INVALID_SACK_HOLE_INDEX;
660       hole->next = TCP_INVALID_SACK_HOLE_INDEX;
661     }
662
663   return hole;
664 }
665
666 static void
667 scoreboard_update_bytes (tcp_connection_t * tc, sack_scoreboard_t * sb)
668 {
669   sack_scoreboard_hole_t *hole, *prev;
670   u32 bytes = 0, blks = 0;
671
672   sb->lost_bytes = 0;
673   sb->sacked_bytes = 0;
674   hole = scoreboard_last_hole (sb);
675   if (!hole)
676     return;
677
678   if (seq_gt (sb->high_sacked, hole->end))
679     {
680       bytes = sb->high_sacked - hole->end;
681       blks = 1;
682     }
683
684   while ((prev = scoreboard_prev_hole (sb, hole))
685          && (bytes < (TCP_DUPACK_THRESHOLD - 1) * tc->snd_mss
686              && blks < TCP_DUPACK_THRESHOLD))
687     {
688       bytes += hole->start - prev->end;
689       blks++;
690       hole = prev;
691     }
692
693   while (hole)
694     {
695       sb->lost_bytes += scoreboard_hole_bytes (hole);
696       hole->is_lost = 1;
697       prev = hole;
698       hole = scoreboard_prev_hole (sb, hole);
699       if (hole)
700         bytes += prev->start - hole->end;
701     }
702   sb->sacked_bytes = bytes;
703 }
704
705 /**
706  * Figure out the next hole to retransmit
707  *
708  * Follows logic proposed in RFC6675 Sec. 4, NextSeg()
709  */
710 sack_scoreboard_hole_t *
711 scoreboard_next_rxt_hole (sack_scoreboard_t * sb,
712                           sack_scoreboard_hole_t * start,
713                           u8 have_sent_1_smss,
714                           u8 * can_rescue, u8 * snd_limited)
715 {
716   sack_scoreboard_hole_t *hole = 0;
717
718   hole = start ? start : scoreboard_first_hole (sb);
719   while (hole && seq_leq (hole->end, sb->high_rxt) && hole->is_lost)
720     hole = scoreboard_next_hole (sb, hole);
721
722   /* Nothing, return */
723   if (!hole)
724     {
725       sb->cur_rxt_hole = TCP_INVALID_SACK_HOLE_INDEX;
726       return 0;
727     }
728
729   /* Rule (1): if higher than rxt, less than high_sacked and lost */
730   if (hole->is_lost && seq_lt (hole->start, sb->high_sacked))
731     {
732       sb->cur_rxt_hole = scoreboard_hole_index (sb, hole);
733     }
734   else
735     {
736       /* Rule (2): output takes care of transmitting new data */
737       if (!have_sent_1_smss)
738         {
739           hole = 0;
740           sb->cur_rxt_hole = TCP_INVALID_SACK_HOLE_INDEX;
741         }
742       /* Rule (3): if hole not lost */
743       else if (seq_lt (hole->start, sb->high_sacked))
744         {
745           *snd_limited = 1;
746           sb->cur_rxt_hole = scoreboard_hole_index (sb, hole);
747         }
748       /* Rule (4): if hole beyond high_sacked */
749       else
750         {
751           ASSERT (seq_geq (hole->start, sb->high_sacked));
752           *snd_limited = 1;
753           *can_rescue = 1;
754           /* HighRxt MUST NOT be updated */
755           return 0;
756         }
757     }
758
759   if (hole && seq_lt (sb->high_rxt, hole->start))
760     sb->high_rxt = hole->start;
761
762   return hole;
763 }
764
765 static void
766 scoreboard_init_high_rxt (sack_scoreboard_t * sb, u32 seq)
767 {
768   sack_scoreboard_hole_t *hole;
769   hole = scoreboard_first_hole (sb);
770   if (hole)
771     {
772       seq = seq_gt (seq, hole->start) ? seq : hole->start;
773       sb->cur_rxt_hole = sb->head;
774     }
775   sb->high_rxt = seq;
776 }
777
778 void
779 scoreboard_init (sack_scoreboard_t * sb)
780 {
781   sb->head = TCP_INVALID_SACK_HOLE_INDEX;
782   sb->tail = TCP_INVALID_SACK_HOLE_INDEX;
783   sb->cur_rxt_hole = TCP_INVALID_SACK_HOLE_INDEX;
784 }
785
786 void
787 scoreboard_clear (sack_scoreboard_t * sb)
788 {
789   sack_scoreboard_hole_t *hole;
790   while ((hole = scoreboard_first_hole (sb)))
791     {
792       scoreboard_remove_hole (sb, hole);
793     }
794   ASSERT (sb->head == sb->tail && sb->head == TCP_INVALID_SACK_HOLE_INDEX);
795   ASSERT (pool_elts (sb->holes) == 0);
796   sb->sacked_bytes = 0;
797   sb->last_sacked_bytes = 0;
798   sb->last_bytes_delivered = 0;
799   sb->snd_una_adv = 0;
800   sb->high_sacked = 0;
801   sb->high_rxt = 0;
802   sb->lost_bytes = 0;
803   sb->cur_rxt_hole = TCP_INVALID_SACK_HOLE_INDEX;
804 }
805
806 /**
807  * Test that scoreboard is sane after recovery
808  *
809  * Returns 1 if scoreboard is empty or if first hole beyond
810  * snd_una.
811  */
812 static u8
813 tcp_scoreboard_is_sane_post_recovery (tcp_connection_t * tc)
814 {
815   sack_scoreboard_hole_t *hole;
816   hole = scoreboard_first_hole (&tc->sack_sb);
817   return (!hole || seq_geq (hole->start, tc->snd_una));
818 }
819
820 void
821 tcp_rcv_sacks (tcp_connection_t * tc, u32 ack)
822 {
823   sack_scoreboard_t *sb = &tc->sack_sb;
824   sack_block_t *blk, tmp;
825   sack_scoreboard_hole_t *hole, *next_hole, *last_hole;
826   u32 blk_index = 0, old_sacked_bytes, hole_index;
827   int i, j;
828
829   sb->last_sacked_bytes = 0;
830   sb->last_bytes_delivered = 0;
831   sb->snd_una_adv = 0;
832
833   if (!tcp_opts_sack (&tc->rcv_opts)
834       && sb->head == TCP_INVALID_SACK_HOLE_INDEX)
835     return;
836
837   old_sacked_bytes = sb->sacked_bytes;
838
839   /* Remove invalid blocks */
840   blk = tc->rcv_opts.sacks;
841   while (blk < vec_end (tc->rcv_opts.sacks))
842     {
843       if (seq_lt (blk->start, blk->end)
844           && seq_gt (blk->start, tc->snd_una)
845           && seq_gt (blk->start, ack) && seq_leq (blk->end, tc->snd_una_max))
846         {
847           blk++;
848           continue;
849         }
850       vec_del1 (tc->rcv_opts.sacks, blk - tc->rcv_opts.sacks);
851     }
852
853   /* Add block for cumulative ack */
854   if (seq_gt (ack, tc->snd_una))
855     {
856       tmp.start = tc->snd_una;
857       tmp.end = ack;
858       vec_add1 (tc->rcv_opts.sacks, tmp);
859     }
860
861   if (vec_len (tc->rcv_opts.sacks) == 0)
862     return;
863
864   tcp_scoreboard_trace_add (tc, ack);
865
866   /* Make sure blocks are ordered */
867   for (i = 0; i < vec_len (tc->rcv_opts.sacks); i++)
868     for (j = i + 1; j < vec_len (tc->rcv_opts.sacks); j++)
869       if (seq_lt (tc->rcv_opts.sacks[j].start, tc->rcv_opts.sacks[i].start))
870         {
871           tmp = tc->rcv_opts.sacks[i];
872           tc->rcv_opts.sacks[i] = tc->rcv_opts.sacks[j];
873           tc->rcv_opts.sacks[j] = tmp;
874         }
875
876   if (sb->head == TCP_INVALID_SACK_HOLE_INDEX)
877     {
878       /* If no holes, insert the first that covers all outstanding bytes */
879       last_hole = scoreboard_insert_hole (sb, TCP_INVALID_SACK_HOLE_INDEX,
880                                           tc->snd_una, tc->snd_una_max);
881       sb->tail = scoreboard_hole_index (sb, last_hole);
882       tmp = tc->rcv_opts.sacks[vec_len (tc->rcv_opts.sacks) - 1];
883       sb->high_sacked = tmp.end;
884     }
885   else
886     {
887       /* If we have holes but snd_una_max is beyond the last hole, update
888        * last hole end */
889       tmp = tc->rcv_opts.sacks[vec_len (tc->rcv_opts.sacks) - 1];
890       last_hole = scoreboard_last_hole (sb);
891       if (seq_gt (tc->snd_una_max, last_hole->end))
892         {
893           if (seq_geq (last_hole->start, sb->high_sacked))
894             {
895               last_hole->end = tc->snd_una_max;
896             }
897           /* New hole after high sacked block */
898           else if (seq_lt (sb->high_sacked, tc->snd_una_max))
899             {
900               scoreboard_insert_hole (sb, sb->tail, sb->high_sacked,
901                                       tc->snd_una_max);
902             }
903         }
904       /* Keep track of max byte sacked for when the last hole
905        * is acked */
906       if (seq_gt (tmp.end, sb->high_sacked))
907         sb->high_sacked = tmp.end;
908     }
909
910   /* Walk the holes with the SACK blocks */
911   hole = pool_elt_at_index (sb->holes, sb->head);
912   while (hole && blk_index < vec_len (tc->rcv_opts.sacks))
913     {
914       blk = &tc->rcv_opts.sacks[blk_index];
915       if (seq_leq (blk->start, hole->start))
916         {
917           /* Block covers hole. Remove hole */
918           if (seq_geq (blk->end, hole->end))
919             {
920               next_hole = scoreboard_next_hole (sb, hole);
921
922               /* Byte accounting: snd_una needs to be advanced */
923               if (blk->end == ack)
924                 {
925                   if (next_hole)
926                     {
927                       if (seq_lt (ack, next_hole->start))
928                         sb->snd_una_adv = next_hole->start - ack;
929                       sb->last_bytes_delivered +=
930                         next_hole->start - hole->end;
931                     }
932                   else
933                     {
934                       ASSERT (seq_geq (sb->high_sacked, ack));
935                       sb->snd_una_adv = sb->high_sacked - ack;
936                       sb->last_bytes_delivered += sb->high_sacked - hole->end;
937                     }
938                 }
939
940               scoreboard_remove_hole (sb, hole);
941               hole = next_hole;
942             }
943           /* Partial 'head' overlap */
944           else
945             {
946               if (seq_gt (blk->end, hole->start))
947                 {
948                   hole->start = blk->end;
949                 }
950               blk_index++;
951             }
952         }
953       else
954         {
955           /* Hole must be split */
956           if (seq_lt (blk->end, hole->end))
957             {
958               hole_index = scoreboard_hole_index (sb, hole);
959               next_hole = scoreboard_insert_hole (sb, hole_index, blk->end,
960                                                   hole->end);
961
962               /* Pool might've moved */
963               hole = scoreboard_get_hole (sb, hole_index);
964               hole->end = blk->start;
965               blk_index++;
966               ASSERT (hole->next == scoreboard_hole_index (sb, next_hole));
967             }
968           else if (seq_lt (blk->start, hole->end))
969             {
970               hole->end = blk->start;
971             }
972           hole = scoreboard_next_hole (sb, hole);
973         }
974     }
975
976   scoreboard_update_bytes (tc, sb);
977   sb->last_sacked_bytes = sb->sacked_bytes
978     - (old_sacked_bytes - sb->last_bytes_delivered);
979   ASSERT (sb->last_sacked_bytes <= sb->sacked_bytes || tcp_in_recovery (tc));
980   ASSERT (sb->sacked_bytes == 0
981           || sb->sacked_bytes < tc->snd_una_max - seq_max (tc->snd_una, ack));
982   ASSERT (sb->last_sacked_bytes + sb->lost_bytes <= tc->snd_una_max
983           - seq_max (tc->snd_una, ack));
984   ASSERT (sb->head == TCP_INVALID_SACK_HOLE_INDEX || tcp_in_recovery (tc)
985           || sb->holes[sb->head].start == ack + sb->snd_una_adv);
986   TCP_EVT_DBG (TCP_EVT_CC_SCOREBOARD, tc);
987 }
988
989 /**
990  * Try to update snd_wnd based on feedback received from peer.
991  *
992  * If successful, and new window is 'effectively' 0, activate persist
993  * timer.
994  */
995 static void
996 tcp_update_snd_wnd (tcp_connection_t * tc, u32 seq, u32 ack, u32 snd_wnd)
997 {
998   /* If (SND.WL1 < SEG.SEQ or (SND.WL1 = SEG.SEQ and SND.WL2 =< SEG.ACK)), set
999    * SND.WND <- SEG.WND, set SND.WL1 <- SEG.SEQ, and set SND.WL2 <- SEG.ACK */
1000   if (seq_lt (tc->snd_wl1, seq)
1001       || (tc->snd_wl1 == seq && seq_leq (tc->snd_wl2, ack)))
1002     {
1003       tc->snd_wnd = snd_wnd;
1004       tc->snd_wl1 = seq;
1005       tc->snd_wl2 = ack;
1006       TCP_EVT_DBG (TCP_EVT_SND_WND, tc);
1007
1008       if (tc->snd_wnd < tc->snd_mss)
1009         {
1010           /* Set persist timer if not set and we just got 0 wnd */
1011           if (!tcp_timer_is_active (tc, TCP_TIMER_PERSIST)
1012               && !tcp_timer_is_active (tc, TCP_TIMER_RETRANSMIT))
1013             tcp_persist_timer_set (tc);
1014         }
1015       else
1016         {
1017           tcp_persist_timer_reset (tc);
1018           if (!tcp_in_recovery (tc) && tc->rto_boff > 0)
1019             {
1020               tc->rto_boff = 0;
1021               tcp_update_rto (tc);
1022             }
1023         }
1024     }
1025 }
1026
1027 /**
1028  * Init loss recovery/fast recovery.
1029  *
1030  * Triggered by dup acks as opposed to timer timeout. Note that cwnd is
1031  * updated in @ref tcp_cc_handle_event after fast retransmit
1032  */
1033 void
1034 tcp_cc_init_congestion (tcp_connection_t * tc)
1035 {
1036   tcp_fastrecovery_on (tc);
1037   tc->snd_congestion = tc->snd_una_max;
1038   tc->cwnd_acc_bytes = 0;
1039   tc->cc_algo->congestion (tc);
1040   TCP_EVT_DBG (TCP_EVT_CC_EVT, tc, 4);
1041 }
1042
1043 static void
1044 tcp_cc_recovery_exit (tcp_connection_t * tc)
1045 {
1046   tc->rto_boff = 0;
1047   tcp_update_rto (tc);
1048   tc->snd_rxt_ts = 0;
1049   tc->snd_nxt = tc->snd_una_max;
1050   tcp_recovery_off (tc);
1051   TCP_EVT_DBG (TCP_EVT_CC_EVT, tc, 3);
1052 }
1053
1054 void
1055 tcp_cc_fastrecovery_exit (tcp_connection_t * tc)
1056 {
1057   tc->cc_algo->recovered (tc);
1058   tc->snd_rxt_bytes = 0;
1059   tc->rcv_dupacks = 0;
1060   tc->snd_nxt = tc->snd_una_max;
1061   tcp_fastrecovery_off (tc);
1062   tcp_fastrecovery_1_smss_off (tc);
1063   TCP_EVT_DBG (TCP_EVT_CC_EVT, tc, 3);
1064 }
1065
1066 static void
1067 tcp_cc_congestion_undo (tcp_connection_t * tc)
1068 {
1069   tc->cwnd = tc->prev_cwnd;
1070   tc->ssthresh = tc->prev_ssthresh;
1071   tc->snd_nxt = tc->snd_una_max;
1072   tc->rcv_dupacks = 0;
1073   if (tcp_in_recovery (tc))
1074     tcp_cc_recovery_exit (tc);
1075   ASSERT (tc->rto_boff == 0);
1076   TCP_EVT_DBG (TCP_EVT_CC_EVT, tc, 5);
1077   /* TODO extend for fastrecovery */
1078 }
1079
1080 static u8
1081 tcp_cc_is_spurious_retransmit (tcp_connection_t * tc)
1082 {
1083   return (tcp_in_recovery (tc) && tc->rto_boff == 1
1084           && tc->snd_rxt_ts
1085           && tcp_opts_tstamp (&tc->rcv_opts)
1086           && timestamp_lt (tc->rcv_opts.tsecr, tc->snd_rxt_ts));
1087 }
1088
1089 static int
1090 tcp_cc_recover (tcp_connection_t * tc)
1091 {
1092   ASSERT (tcp_in_cong_recovery (tc));
1093   if (tcp_cc_is_spurious_retransmit (tc))
1094     {
1095       tcp_cc_congestion_undo (tc);
1096       return 1;
1097     }
1098
1099   if (tcp_in_recovery (tc))
1100     tcp_cc_recovery_exit (tc);
1101   else if (tcp_in_fastrecovery (tc))
1102     tcp_cc_fastrecovery_exit (tc);
1103
1104   ASSERT (tc->rto_boff == 0);
1105   ASSERT (!tcp_in_cong_recovery (tc));
1106   ASSERT (tcp_scoreboard_is_sane_post_recovery (tc));
1107   return 0;
1108 }
1109
1110 static void
1111 tcp_cc_update (tcp_connection_t * tc, vlib_buffer_t * b)
1112 {
1113   ASSERT (!tcp_in_cong_recovery (tc) || tcp_is_lost_fin (tc));
1114
1115   /* Congestion avoidance */
1116   tc->cc_algo->rcv_ack (tc);
1117   tc->tsecr_last_ack = tc->rcv_opts.tsecr;
1118
1119   /* If a cumulative ack, make sure dupacks is 0 */
1120   tc->rcv_dupacks = 0;
1121
1122   /* When dupacks hits the threshold we only enter fast retransmit if
1123    * cumulative ack covers more than snd_congestion. Should snd_una
1124    * wrap this test may fail under otherwise valid circumstances.
1125    * Therefore, proactively update snd_congestion when wrap detected. */
1126   if (PREDICT_FALSE
1127       (seq_leq (tc->snd_congestion, tc->snd_una - tc->bytes_acked)
1128        && seq_gt (tc->snd_congestion, tc->snd_una)))
1129     tc->snd_congestion = tc->snd_una - 1;
1130 }
1131
1132 static u8
1133 tcp_should_fastrecover_sack (tcp_connection_t * tc)
1134 {
1135   return (TCP_DUPACK_THRESHOLD - 1) * tc->snd_mss < tc->sack_sb.sacked_bytes;
1136 }
1137
1138 static u8
1139 tcp_should_fastrecover (tcp_connection_t * tc)
1140 {
1141   return (tc->rcv_dupacks == TCP_DUPACK_THRESHOLD
1142           || tcp_should_fastrecover_sack (tc));
1143 }
1144
1145 /**
1146  * One function to rule them all ... and in the darkness bind them
1147  */
1148 static void
1149 tcp_cc_handle_event (tcp_connection_t * tc, u32 is_dack)
1150 {
1151   u32 rxt_delivered;
1152
1153   if (tcp_in_fastrecovery (tc) && tcp_opts_sack_permitted (&tc->rcv_opts))
1154     {
1155       if (tc->bytes_acked)
1156         goto partial_ack;
1157       tcp_fast_retransmit (tc);
1158       return;
1159     }
1160   /*
1161    * Duplicate ACK. Check if we should enter fast recovery, or if already in
1162    * it account for the bytes that left the network.
1163    */
1164   else if (is_dack && !tcp_in_recovery (tc))
1165     {
1166       TCP_EVT_DBG (TCP_EVT_DUPACK_RCVD, tc, 1);
1167       ASSERT (tc->snd_una != tc->snd_una_max
1168               || tc->sack_sb.last_sacked_bytes);
1169
1170       tc->rcv_dupacks++;
1171
1172       /* Pure duplicate ack. If some data got acked, it's handled lower */
1173       if (tc->rcv_dupacks > TCP_DUPACK_THRESHOLD && !tc->bytes_acked)
1174         {
1175           ASSERT (tcp_in_fastrecovery (tc));
1176           tc->cc_algo->rcv_cong_ack (tc, TCP_CC_DUPACK);
1177           return;
1178         }
1179       else if (tcp_should_fastrecover (tc))
1180         {
1181           ASSERT (!tcp_in_fastrecovery (tc));
1182
1183           /* If of of the two conditions lower hold, reset dupacks because
1184            * we're probably after timeout (RFC6582 heuristics).
1185            * If Cumulative ack does not cover more than congestion threshold,
1186            * and:
1187            * 1) The following doesn't hold: The congestion window is greater
1188            *    than SMSS bytes and the difference between highest_ack
1189            *    and prev_highest_ack is at most 4*SMSS bytes
1190            * 2) Echoed timestamp in the last non-dup ack does not equal the
1191            *    stored timestamp
1192            */
1193           if (seq_leq (tc->snd_una, tc->snd_congestion)
1194               && ((!(tc->cwnd > tc->snd_mss
1195                      && tc->bytes_acked <= 4 * tc->snd_mss))
1196                   || (tc->rcv_opts.tsecr != tc->tsecr_last_ack)))
1197             {
1198               tc->rcv_dupacks = 0;
1199               return;
1200             }
1201
1202           tcp_cc_init_congestion (tc);
1203           tc->cc_algo->rcv_cong_ack (tc, TCP_CC_DUPACK);
1204
1205           /* The first segment MUST be retransmitted */
1206           tcp_retransmit_first_unacked (tc);
1207
1208           /* Post retransmit update cwnd to ssthresh and account for the
1209            * three segments that have left the network and should've been
1210            * buffered at the receiver XXX */
1211           tc->cwnd = tc->ssthresh + tc->rcv_dupacks * tc->snd_mss;
1212           ASSERT (tc->cwnd >= tc->snd_mss);
1213
1214           /* If cwnd allows, send more data */
1215           if (tcp_opts_sack_permitted (&tc->rcv_opts))
1216             {
1217               scoreboard_init_high_rxt (&tc->sack_sb,
1218                                         tc->snd_una + tc->snd_mss);
1219               tcp_fast_retransmit_sack (tc);
1220             }
1221           else
1222             {
1223               tcp_fast_retransmit_no_sack (tc);
1224             }
1225           return;
1226         }
1227       else if (!tc->bytes_acked
1228                || (tc->bytes_acked && !tcp_in_cong_recovery (tc)))
1229         {
1230           tc->cc_algo->rcv_cong_ack (tc, TCP_CC_DUPACK);
1231           return;
1232         }
1233       else
1234         goto partial_ack;
1235     }
1236
1237   if (!tc->bytes_acked)
1238     return;
1239
1240 partial_ack:
1241   TCP_EVT_DBG (TCP_EVT_CC_PACK, tc);
1242
1243   /*
1244    * Legitimate ACK. 1) See if we can exit recovery
1245    */
1246   /* XXX limit this only to first partial ack? */
1247   if (seq_lt (tc->snd_una, tc->snd_congestion))
1248     tcp_retransmit_timer_force_update (tc);
1249   else
1250     tcp_retransmit_timer_update (tc);
1251
1252   if (seq_geq (tc->snd_una, tc->snd_congestion))
1253     {
1254       /* If spurious return, we've already updated everything */
1255       if (tcp_cc_recover (tc))
1256         {
1257           tc->tsecr_last_ack = tc->rcv_opts.tsecr;
1258           return;
1259         }
1260
1261       tc->snd_nxt = tc->snd_una_max;
1262
1263       /* Treat as congestion avoidance ack */
1264       tc->cc_algo->rcv_ack (tc);
1265       tc->tsecr_last_ack = tc->rcv_opts.tsecr;
1266       return;
1267     }
1268
1269   /*
1270    * Legitimate ACK. 2) If PARTIAL ACK try to retransmit
1271    */
1272
1273   /* RFC6675: If the incoming ACK is a cumulative acknowledgment,
1274    * reset dupacks to 0. Also needed if in congestion recovery */
1275   tc->rcv_dupacks = 0;
1276
1277   /* Post RTO timeout don't try anything fancy */
1278   if (tcp_in_recovery (tc))
1279     {
1280       tc->cc_algo->rcv_ack (tc);
1281       tc->tsecr_last_ack = tc->rcv_opts.tsecr;
1282       transport_add_tx_event (&tc->connection);
1283       return;
1284     }
1285
1286   /* Remove retransmitted bytes that have been delivered */
1287   ASSERT (tc->bytes_acked + tc->sack_sb.snd_una_adv
1288           >= tc->sack_sb.last_bytes_delivered
1289           || (tc->flags & TCP_CONN_FINSNT));
1290
1291   if (seq_lt (tc->snd_una, tc->sack_sb.high_rxt))
1292     {
1293       /* If we have sacks and we haven't gotten an ack beyond high_rxt,
1294        * remove sacked bytes delivered */
1295       rxt_delivered = tc->bytes_acked + tc->sack_sb.snd_una_adv
1296         - tc->sack_sb.last_bytes_delivered;
1297       ASSERT (tc->snd_rxt_bytes >= rxt_delivered);
1298       tc->snd_rxt_bytes -= rxt_delivered;
1299     }
1300   else
1301     {
1302       /* Either all retransmitted holes have been acked, or we're
1303        * "in the blind" and retransmitting segment by segment */
1304       tc->snd_rxt_bytes = 0;
1305     }
1306
1307   tc->cc_algo->rcv_cong_ack (tc, TCP_CC_PARTIALACK);
1308
1309   /*
1310    * Since this was a partial ack, try to retransmit some more data
1311    */
1312   tcp_fast_retransmit (tc);
1313 }
1314
1315 /**
1316  * Process incoming ACK
1317  */
1318 static int
1319 tcp_rcv_ack (tcp_connection_t * tc, vlib_buffer_t * b,
1320              tcp_header_t * th, u32 * next, u32 * error)
1321 {
1322   u32 prev_snd_wnd, prev_snd_una;
1323   u8 is_dack;
1324
1325   TCP_EVT_DBG (TCP_EVT_CC_STAT, tc);
1326
1327   /* If the ACK acks something not yet sent (SEG.ACK > SND.NXT) */
1328   if (PREDICT_FALSE (seq_gt (vnet_buffer (b)->tcp.ack_number, tc->snd_nxt)))
1329     {
1330       /* When we entered recovery, we reset snd_nxt to snd_una. Seems peer
1331        * still has the data so accept the ack */
1332       if (tcp_in_recovery (tc)
1333           && seq_leq (vnet_buffer (b)->tcp.ack_number, tc->snd_congestion))
1334         {
1335           tc->snd_nxt = vnet_buffer (b)->tcp.ack_number;
1336           if (seq_gt (tc->snd_nxt, tc->snd_una_max))
1337             tc->snd_una_max = tc->snd_nxt;
1338           goto process_ack;
1339         }
1340
1341       /* If we have outstanding data and this is within the window, accept it,
1342        * probably retransmit has timed out. Otherwise ACK segment and then
1343        * drop it */
1344       if (seq_gt (vnet_buffer (b)->tcp.ack_number, tc->snd_una_max))
1345         {
1346           tcp_make_ack (tc, b);
1347           *next = tcp_next_output (tc->c_is_ip4);
1348           *error = TCP_ERROR_ACK_INVALID;
1349           TCP_EVT_DBG (TCP_EVT_ACK_RCV_ERR, tc, 0,
1350                        vnet_buffer (b)->tcp.ack_number);
1351           return -1;
1352         }
1353
1354       TCP_EVT_DBG (TCP_EVT_ACK_RCV_ERR, tc, 2,
1355                    vnet_buffer (b)->tcp.ack_number);
1356
1357       tc->snd_nxt = vnet_buffer (b)->tcp.ack_number;
1358       *error = TCP_ERROR_ACK_FUTURE;
1359     }
1360
1361   /* If old ACK, probably it's an old dupack */
1362   if (PREDICT_FALSE (seq_lt (vnet_buffer (b)->tcp.ack_number, tc->snd_una)))
1363     {
1364       *error = TCP_ERROR_ACK_OLD;
1365       TCP_EVT_DBG (TCP_EVT_ACK_RCV_ERR, tc, 1,
1366                    vnet_buffer (b)->tcp.ack_number);
1367       if (tcp_in_fastrecovery (tc) && tc->rcv_dupacks == TCP_DUPACK_THRESHOLD)
1368         tcp_cc_handle_event (tc, 1);
1369       /* Don't drop yet */
1370       return 0;
1371     }
1372
1373   /*
1374    * Looks okay, process feedback
1375    */
1376 process_ack:
1377   if (tcp_opts_sack_permitted (&tc->rcv_opts))
1378     tcp_rcv_sacks (tc, vnet_buffer (b)->tcp.ack_number);
1379
1380   prev_snd_wnd = tc->snd_wnd;
1381   prev_snd_una = tc->snd_una;
1382   tcp_update_snd_wnd (tc, vnet_buffer (b)->tcp.seq_number,
1383                       vnet_buffer (b)->tcp.ack_number,
1384                       clib_net_to_host_u16 (th->window) << tc->snd_wscale);
1385   tc->bytes_acked = vnet_buffer (b)->tcp.ack_number - tc->snd_una;
1386   tc->snd_una = vnet_buffer (b)->tcp.ack_number + tc->sack_sb.snd_una_adv;
1387   tcp_validate_txf_size (tc, tc->bytes_acked);
1388
1389   if (tc->bytes_acked)
1390     tcp_dequeue_acked (tc, vnet_buffer (b)->tcp.ack_number);
1391
1392   TCP_EVT_DBG (TCP_EVT_ACK_RCVD, tc);
1393
1394   /*
1395    * Check if we have congestion event
1396    */
1397
1398   if (tcp_ack_is_cc_event (tc, b, prev_snd_wnd, prev_snd_una, &is_dack))
1399     {
1400       tcp_cc_handle_event (tc, is_dack);
1401       if (!tcp_in_cong_recovery (tc))
1402         return 0;
1403       *error = TCP_ERROR_ACK_DUP;
1404       if (vnet_buffer (b)->tcp.data_len || tcp_is_fin (th))
1405         return 0;
1406       return -1;
1407     }
1408
1409   /*
1410    * Update congestion control (slow start/congestion avoidance)
1411    */
1412   tcp_cc_update (tc, b);
1413   *error = TCP_ERROR_ACK_OK;
1414   return 0;
1415 }
1416
1417 static u8
1418 tcp_sack_vector_is_sane (sack_block_t * sacks)
1419 {
1420   int i;
1421   for (i = 1; i < vec_len (sacks); i++)
1422     {
1423       if (sacks[i - 1].end == sacks[i].start)
1424         return 0;
1425     }
1426   return 1;
1427 }
1428
1429 /**
1430  * Build SACK list as per RFC2018.
1431  *
1432  * Makes sure the first block contains the segment that generated the current
1433  * ACK and the following ones are the ones most recently reported in SACK
1434  * blocks.
1435  *
1436  * @param tc TCP connection for which the SACK list is updated
1437  * @param start Start sequence number of the newest SACK block
1438  * @param end End sequence of the newest SACK block
1439  */
1440 void
1441 tcp_update_sack_list (tcp_connection_t * tc, u32 start, u32 end)
1442 {
1443   sack_block_t *new_list = 0, *block = 0;
1444   int i;
1445
1446   /* If the first segment is ooo add it to the list. Last write might've moved
1447    * rcv_nxt over the first segment. */
1448   if (seq_lt (tc->rcv_nxt, start))
1449     {
1450       vec_add2 (new_list, block, 1);
1451       block->start = start;
1452       block->end = end;
1453     }
1454
1455   /* Find the blocks still worth keeping. */
1456   for (i = 0; i < vec_len (tc->snd_sacks); i++)
1457     {
1458       /* Discard if rcv_nxt advanced beyond current block */
1459       if (seq_leq (tc->snd_sacks[i].start, tc->rcv_nxt))
1460         continue;
1461
1462       /* Merge or drop if segment overlapped by the new segment */
1463       if (block && (seq_geq (tc->snd_sacks[i].end, new_list[0].start)
1464                     && seq_leq (tc->snd_sacks[i].start, new_list[0].end)))
1465         {
1466           if (seq_lt (tc->snd_sacks[i].start, new_list[0].start))
1467             new_list[0].start = tc->snd_sacks[i].start;
1468           if (seq_lt (new_list[0].end, tc->snd_sacks[i].end))
1469             new_list[0].end = tc->snd_sacks[i].end;
1470           continue;
1471         }
1472
1473       /* Save to new SACK list if we have space. */
1474       if (vec_len (new_list) < TCP_MAX_SACK_BLOCKS)
1475         {
1476           vec_add1 (new_list, tc->snd_sacks[i]);
1477         }
1478       else
1479         {
1480           clib_warning ("sack discarded");
1481         }
1482     }
1483
1484   ASSERT (vec_len (new_list) <= TCP_MAX_SACK_BLOCKS);
1485
1486   /* Replace old vector with new one */
1487   vec_free (tc->snd_sacks);
1488   tc->snd_sacks = new_list;
1489
1490   /* Segments should not 'touch' */
1491   ASSERT (tcp_sack_vector_is_sane (tc->snd_sacks));
1492 }
1493
1494 u32
1495 tcp_sack_list_bytes (tcp_connection_t * tc)
1496 {
1497   u32 bytes = 0, i;
1498   for (i = 0; i < vec_len (tc->snd_sacks); i++)
1499     bytes += tc->snd_sacks[i].end - tc->snd_sacks[i].start;
1500   return bytes;
1501 }
1502
1503 /** Enqueue data for delivery to application */
1504 static int
1505 tcp_session_enqueue_data (tcp_connection_t * tc, vlib_buffer_t * b,
1506                           u16 data_len)
1507 {
1508   int written, error = TCP_ERROR_ENQUEUED;
1509
1510   ASSERT (seq_geq (vnet_buffer (b)->tcp.seq_number, tc->rcv_nxt));
1511   ASSERT (data_len);
1512   written = session_enqueue_stream_connection (&tc->connection, b, 0,
1513                                                1 /* queue event */ , 1);
1514
1515   TCP_EVT_DBG (TCP_EVT_INPUT, tc, 0, data_len, written);
1516
1517   /* Update rcv_nxt */
1518   if (PREDICT_TRUE (written == data_len))
1519     {
1520       tc->rcv_nxt += written;
1521     }
1522   /* If more data written than expected, account for out-of-order bytes. */
1523   else if (written > data_len)
1524     {
1525       tc->rcv_nxt += written;
1526
1527       /* Send ACK confirming the update */
1528       tc->flags |= TCP_CONN_SNDACK;
1529       TCP_EVT_DBG (TCP_EVT_CC_INPUT, tc, data_len, written);
1530     }
1531   else if (written > 0)
1532     {
1533       /* We've written something but FIFO is probably full now */
1534       tc->rcv_nxt += written;
1535
1536       /* Depending on how fast the app is, all remaining buffers in burst will
1537        * not be enqueued. Inform peer */
1538       tc->flags |= TCP_CONN_SNDACK;
1539
1540       error = TCP_ERROR_PARTIALLY_ENQUEUED;
1541     }
1542   else
1543     {
1544       tc->flags |= TCP_CONN_SNDACK;
1545       return TCP_ERROR_FIFO_FULL;
1546     }
1547
1548   /* Update SACK list if need be */
1549   if (tcp_opts_sack_permitted (&tc->rcv_opts))
1550     {
1551       /* Remove SACK blocks that have been delivered */
1552       tcp_update_sack_list (tc, tc->rcv_nxt, tc->rcv_nxt);
1553     }
1554
1555   return error;
1556 }
1557
1558 /** Enqueue out-of-order data */
1559 static int
1560 tcp_session_enqueue_ooo (tcp_connection_t * tc, vlib_buffer_t * b,
1561                          u16 data_len)
1562 {
1563   stream_session_t *s0;
1564   int rv, offset;
1565
1566   ASSERT (seq_gt (vnet_buffer (b)->tcp.seq_number, tc->rcv_nxt));
1567   ASSERT (data_len);
1568
1569   /* Enqueue out-of-order data with relative offset */
1570   rv = session_enqueue_stream_connection (&tc->connection, b,
1571                                           vnet_buffer (b)->tcp.seq_number -
1572                                           tc->rcv_nxt, 0 /* queue event */ ,
1573                                           0);
1574
1575   /* Nothing written */
1576   if (rv)
1577     {
1578       TCP_EVT_DBG (TCP_EVT_INPUT, tc, 1, data_len, 0);
1579       return TCP_ERROR_FIFO_FULL;
1580     }
1581
1582   TCP_EVT_DBG (TCP_EVT_INPUT, tc, 1, data_len, data_len);
1583
1584   /* Update SACK list if in use */
1585   if (tcp_opts_sack_permitted (&tc->rcv_opts))
1586     {
1587       ooo_segment_t *newest;
1588       u32 start, end;
1589
1590       s0 = session_get (tc->c_s_index, tc->c_thread_index);
1591
1592       /* Get the newest segment from the fifo */
1593       newest = svm_fifo_newest_ooo_segment (s0->server_rx_fifo);
1594       if (newest)
1595         {
1596           offset = ooo_segment_offset (s0->server_rx_fifo, newest);
1597           ASSERT (offset <= vnet_buffer (b)->tcp.seq_number - tc->rcv_nxt);
1598           start = tc->rcv_nxt + offset;
1599           end = start + ooo_segment_length (s0->server_rx_fifo, newest);
1600           tcp_update_sack_list (tc, start, end);
1601           svm_fifo_newest_ooo_segment_reset (s0->server_rx_fifo);
1602           TCP_EVT_DBG (TCP_EVT_CC_SACKS, tc);
1603         }
1604     }
1605
1606   return TCP_ERROR_ENQUEUED_OOO;
1607 }
1608
1609 /**
1610  * Check if ACK could be delayed. If ack can be delayed, it should return
1611  * true for a full frame. If we're always acking return 0.
1612  */
1613 always_inline int
1614 tcp_can_delack (tcp_connection_t * tc)
1615 {
1616   /* Send ack if ... */
1617   if (TCP_ALWAYS_ACK
1618       /* just sent a rcv wnd 0 */
1619       || (tc->flags & TCP_CONN_SENT_RCV_WND0) != 0
1620       /* constrained to send ack */
1621       || (tc->flags & TCP_CONN_SNDACK) != 0
1622       /* we're almost out of tx wnd */
1623       || tcp_available_cc_snd_space (tc) < 4 * tc->snd_mss)
1624     return 0;
1625
1626   return 1;
1627 }
1628
1629 static int
1630 tcp_buffer_discard_bytes (vlib_buffer_t * b, u32 n_bytes_to_drop)
1631 {
1632   u32 discard, first = b->current_length;
1633   vlib_main_t *vm = vlib_get_main ();
1634
1635   /* Handle multi-buffer segments */
1636   if (n_bytes_to_drop > b->current_length)
1637     {
1638       if (!(b->flags & VLIB_BUFFER_NEXT_PRESENT))
1639         return -1;
1640       do
1641         {
1642           discard = clib_min (n_bytes_to_drop, b->current_length);
1643           vlib_buffer_advance (b, discard);
1644           b = vlib_get_buffer (vm, b->next_buffer);
1645           n_bytes_to_drop -= discard;
1646         }
1647       while (n_bytes_to_drop);
1648       if (n_bytes_to_drop > first)
1649         b->total_length_not_including_first_buffer -= n_bytes_to_drop - first;
1650     }
1651   else
1652     vlib_buffer_advance (b, n_bytes_to_drop);
1653   vnet_buffer (b)->tcp.data_len -= n_bytes_to_drop;
1654   return 0;
1655 }
1656
1657 /**
1658  * Receive buffer for connection and handle acks
1659  *
1660  * It handles both in order or out-of-order data.
1661  */
1662 static int
1663 tcp_segment_rcv (tcp_connection_t * tc, vlib_buffer_t * b, u32 * next0)
1664 {
1665   u32 error, n_bytes_to_drop, n_data_bytes;
1666
1667   vlib_buffer_advance (b, vnet_buffer (b)->tcp.data_offset);
1668   n_data_bytes = vnet_buffer (b)->tcp.data_len;
1669   ASSERT (n_data_bytes);
1670
1671   /* Handle out-of-order data */
1672   if (PREDICT_FALSE (vnet_buffer (b)->tcp.seq_number != tc->rcv_nxt))
1673     {
1674       /* Old sequence numbers allowed through because they overlapped
1675        * the rx window */
1676       if (seq_lt (vnet_buffer (b)->tcp.seq_number, tc->rcv_nxt))
1677         {
1678           /* Completely in the past (possible retransmit). Ack
1679            * retransmissions since we may not have any data to send */
1680           if (seq_leq (vnet_buffer (b)->tcp.seq_end, tc->rcv_nxt))
1681             {
1682               tcp_make_ack (tc, b);
1683               error = TCP_ERROR_SEGMENT_OLD;
1684               *next0 = tcp_next_output (tc->c_is_ip4);
1685               goto done;
1686             }
1687
1688           /* Chop off the bytes in the past and see if what is left
1689            * can be enqueued in order */
1690           n_bytes_to_drop = tc->rcv_nxt - vnet_buffer (b)->tcp.seq_number;
1691           n_data_bytes -= n_bytes_to_drop;
1692           vnet_buffer (b)->tcp.seq_number = tc->rcv_nxt;
1693           if (tcp_buffer_discard_bytes (b, n_bytes_to_drop))
1694             {
1695               error = TCP_ERROR_SEGMENT_OLD;
1696               *next0 = tcp_next_drop (tc->c_is_ip4);
1697               goto done;
1698             }
1699           goto in_order;
1700         }
1701
1702       /* RFC2581: Enqueue and send DUPACK for fast retransmit */
1703       error = tcp_session_enqueue_ooo (tc, b, n_data_bytes);
1704       *next0 = tcp_next_output (tc->c_is_ip4);
1705       tcp_make_ack (tc, b);
1706       vnet_buffer (b)->tcp.flags = TCP_BUF_FLAG_DUPACK;
1707       TCP_EVT_DBG (TCP_EVT_DUPACK_SENT, tc, vnet_buffer (b)->tcp);
1708       goto done;
1709     }
1710
1711 in_order:
1712
1713   /* In order data, enqueue. Fifo figures out by itself if any out-of-order
1714    * segments can be enqueued after fifo tail offset changes. */
1715   error = tcp_session_enqueue_data (tc, b, n_data_bytes);
1716   if (tcp_can_delack (tc))
1717     {
1718       *next0 = tcp_next_drop (tc->c_is_ip4);
1719       if (!tcp_timer_is_active (tc, TCP_TIMER_DELACK))
1720         tcp_timer_set (tc, TCP_TIMER_DELACK, TCP_DELACK_TIME);
1721       goto done;
1722     }
1723
1724   *next0 = tcp_next_output (tc->c_is_ip4);
1725   tcp_make_ack (tc, b);
1726
1727 done:
1728   return error;
1729 }
1730
1731 typedef struct
1732 {
1733   tcp_header_t tcp_header;
1734   tcp_connection_t tcp_connection;
1735 } tcp_rx_trace_t;
1736
1737 static u8 *
1738 format_tcp_rx_trace (u8 * s, va_list * args)
1739 {
1740   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1741   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1742   tcp_rx_trace_t *t = va_arg (*args, tcp_rx_trace_t *);
1743   u32 indent = format_get_indent (s);
1744
1745   s = format (s, "%U\n%U%U",
1746               format_tcp_header, &t->tcp_header, 128,
1747               format_white_space, indent,
1748               format_tcp_connection, &t->tcp_connection, 1);
1749
1750   return s;
1751 }
1752
1753 static u8 *
1754 format_tcp_rx_trace_short (u8 * s, va_list * args)
1755 {
1756   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1757   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1758   tcp_rx_trace_t *t = va_arg (*args, tcp_rx_trace_t *);
1759
1760   s = format (s, "%d -> %d (%U)",
1761               clib_net_to_host_u16 (t->tcp_header.dst_port),
1762               clib_net_to_host_u16 (t->tcp_header.src_port), format_tcp_state,
1763               t->tcp_connection.state);
1764
1765   return s;
1766 }
1767
1768 static void
1769 tcp_set_rx_trace_data (tcp_rx_trace_t * t0, tcp_connection_t * tc0,
1770                        tcp_header_t * th0, vlib_buffer_t * b0, u8 is_ip4)
1771 {
1772   if (tc0)
1773     {
1774       clib_memcpy (&t0->tcp_connection, tc0, sizeof (t0->tcp_connection));
1775     }
1776   else
1777     {
1778       th0 = tcp_buffer_hdr (b0);
1779     }
1780   clib_memcpy (&t0->tcp_header, th0, sizeof (t0->tcp_header));
1781 }
1782
1783 static void
1784 tcp_established_trace_frame (vlib_main_t * vm, vlib_node_runtime_t * node,
1785                              vlib_frame_t * frame, u8 is_ip4)
1786 {
1787   u32 *from, n_left;
1788
1789   n_left = frame->n_vectors;
1790   from = vlib_frame_vector_args (frame);
1791
1792   while (n_left >= 1)
1793     {
1794       tcp_connection_t *tc0;
1795       tcp_rx_trace_t *t0;
1796       tcp_header_t *th0;
1797       vlib_buffer_t *b0;
1798       u32 bi0;
1799
1800       bi0 = from[0];
1801       b0 = vlib_get_buffer (vm, bi0);
1802
1803       if (b0->flags & VLIB_BUFFER_IS_TRACED)
1804         {
1805           t0 = vlib_add_trace (vm, node, b0, sizeof (*t0));
1806           tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
1807                                     vm->thread_index);
1808           th0 = tcp_buffer_hdr (b0);
1809           tcp_set_rx_trace_data (t0, tc0, th0, b0, is_ip4);
1810         }
1811
1812       from += 1;
1813       n_left -= 1;
1814     }
1815 }
1816
1817 always_inline void
1818 tcp_node_inc_counter_i (vlib_main_t * vm, u32 tcp4_node, u32 tcp6_node,
1819                         u8 is_ip4, u32 evt, u32 val)
1820 {
1821   if (is_ip4)
1822     vlib_node_increment_counter (vm, tcp4_node, evt, val);
1823   else
1824     vlib_node_increment_counter (vm, tcp6_node, evt, val);
1825 }
1826
1827 #define tcp_maybe_inc_counter(node_id, err, count)                      \
1828 {                                                                       \
1829   if (next0 != tcp_next_drop (is_ip4))                                  \
1830     tcp_node_inc_counter_i (vm, tcp4_##node_id##_node.index,            \
1831                             tcp6_##node_id##_node.index, is_ip4, err,   \
1832                             1);                                         \
1833 }
1834 #define tcp_inc_counter(node_id, err, count)                            \
1835   tcp_node_inc_counter_i (vm, tcp4_##node_id##_node.index,              \
1836                            tcp6_##node_id##_node.index, is_ip4,         \
1837                            err, count)
1838 #define tcp_maybe_inc_err_counter(cnts, err)                            \
1839 {                                                                       \
1840   cnts[err] += (next0 != tcp_next_drop (is_ip4));                       \
1841 }
1842 #define tcp_inc_err_counter(cnts, err, val)                             \
1843 {                                                                       \
1844   cnts[err] += val;                                                     \
1845 }
1846 #define tcp_store_err_counters(node_id, cnts)                           \
1847 {                                                                       \
1848   int i;                                                                \
1849   for (i = 0; i < TCP_N_ERROR; i++)                                     \
1850     if (cnts[i])                                                        \
1851       tcp_inc_counter(node_id, i, cnts[i]);                             \
1852 }
1853
1854
1855 always_inline uword
1856 tcp46_established_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
1857                           vlib_frame_t * frame, int is_ip4)
1858 {
1859   u32 thread_index = vm->thread_index, errors = 0;
1860   u32 n_left_from, next_index, *from, *to_next;
1861   u16 err_counters[TCP_N_ERROR] = { 0 };
1862   u8 is_fin = 0;
1863
1864   if (node->flags & VLIB_NODE_FLAG_TRACE)
1865     tcp_established_trace_frame (vm, node, frame, is_ip4);
1866
1867   from = vlib_frame_vector_args (frame);
1868   n_left_from = frame->n_vectors;
1869   next_index = node->cached_next_index;
1870
1871   while (n_left_from > 0)
1872     {
1873       u32 n_left_to_next;
1874
1875       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1876       while (n_left_from > 0 && n_left_to_next > 0)
1877         {
1878           u32 bi0;
1879           vlib_buffer_t *b0;
1880           tcp_header_t *th0 = 0;
1881           tcp_connection_t *tc0;
1882           u32 next0 = tcp_next_drop (is_ip4), error0 = TCP_ERROR_ACK_OK;
1883
1884           if (n_left_from > 1)
1885             {
1886               vlib_buffer_t *pb;
1887               pb = vlib_get_buffer (vm, from[1]);
1888               vlib_prefetch_buffer_header (pb, LOAD);
1889               CLIB_PREFETCH (pb->data, 2 * CLIB_CACHE_LINE_BYTES, LOAD);
1890             }
1891
1892           bi0 = from[0];
1893           to_next[0] = bi0;
1894           from += 1;
1895           to_next += 1;
1896           n_left_from -= 1;
1897           n_left_to_next -= 1;
1898
1899           b0 = vlib_get_buffer (vm, bi0);
1900           tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
1901                                     thread_index);
1902
1903           if (PREDICT_FALSE (tc0 == 0))
1904             {
1905               error0 = TCP_ERROR_INVALID_CONNECTION;
1906               goto done;
1907             }
1908
1909           th0 = tcp_buffer_hdr (b0);
1910           /* N.B. buffer is rewritten if segment is ooo. Thus, th0 becomes a
1911            * dangling reference. */
1912           is_fin = tcp_is_fin (th0);
1913
1914           /* SYNs, FINs and data consume sequence numbers */
1915           vnet_buffer (b0)->tcp.seq_end = vnet_buffer (b0)->tcp.seq_number
1916             + tcp_is_syn (th0) + is_fin + vnet_buffer (b0)->tcp.data_len;
1917
1918           /* TODO header prediction fast path */
1919
1920           /* 1-4: check SEQ, RST, SYN */
1921           if (PREDICT_FALSE (tcp_segment_validate (vm, tc0, b0, th0, &next0,
1922                                                    &error0)))
1923             {
1924               tcp_maybe_inc_err_counter (err_counters, error0);
1925               TCP_EVT_DBG (TCP_EVT_SEG_INVALID, tc0, vnet_buffer (b0)->tcp);
1926               goto done;
1927             }
1928
1929           /* 5: check the ACK field  */
1930           if (PREDICT_FALSE (tcp_rcv_ack (tc0, b0, th0, &next0, &error0)))
1931             {
1932               tcp_maybe_inc_err_counter (err_counters, error0);
1933               goto done;
1934             }
1935
1936           /* 6: check the URG bit TODO */
1937
1938           /* 7: process the segment text */
1939           if (vnet_buffer (b0)->tcp.data_len)
1940             {
1941               error0 = tcp_segment_rcv (tc0, b0, &next0);
1942               tcp_maybe_inc_err_counter (err_counters, error0);
1943             }
1944
1945           /* 8: check the FIN bit */
1946           if (PREDICT_FALSE (is_fin))
1947             {
1948               /* Enter CLOSE-WAIT and notify session. To avoid lingering
1949                * in CLOSE-WAIT, set timer (reuse WAITCLOSE). */
1950               /* Account for the FIN if nothing else was received */
1951               if (vnet_buffer (b0)->tcp.data_len == 0)
1952                 tc0->rcv_nxt += 1;
1953               tcp_make_ack (tc0, b0);
1954               next0 = tcp_next_output (tc0->c_is_ip4);
1955               tc0->state = TCP_STATE_CLOSE_WAIT;
1956               stream_session_disconnect_notify (&tc0->connection);
1957               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_CLOSEWAIT_TIME);
1958               TCP_EVT_DBG (TCP_EVT_FIN_RCVD, tc0);
1959               tcp_inc_err_counter (err_counters, TCP_ERROR_FIN_RCVD, 1);
1960             }
1961
1962         done:
1963           b0->error = node->errors[error0];
1964           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
1965                                            n_left_to_next, bi0, next0);
1966         }
1967
1968       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1969     }
1970
1971   errors = session_manager_flush_enqueue_events (TRANSPORT_PROTO_TCP,
1972                                                  thread_index);
1973   err_counters[TCP_ERROR_EVENT_FIFO_FULL] = errors;
1974   tcp_store_err_counters (established, err_counters);
1975   tcp_flush_frame_to_output (vm, thread_index, is_ip4);
1976
1977   return frame->n_vectors;
1978 }
1979
1980 static uword
1981 tcp4_established (vlib_main_t * vm, vlib_node_runtime_t * node,
1982                   vlib_frame_t * from_frame)
1983 {
1984   return tcp46_established_inline (vm, node, from_frame, 1 /* is_ip4 */ );
1985 }
1986
1987 static uword
1988 tcp6_established (vlib_main_t * vm, vlib_node_runtime_t * node,
1989                   vlib_frame_t * from_frame)
1990 {
1991   return tcp46_established_inline (vm, node, from_frame, 0 /* is_ip4 */ );
1992 }
1993
1994 /* *INDENT-OFF* */
1995 VLIB_REGISTER_NODE (tcp4_established_node) =
1996 {
1997   .function = tcp4_established,
1998   .name = "tcp4-established",
1999   /* Takes a vector of packets. */
2000   .vector_size = sizeof (u32),
2001   .n_errors = TCP_N_ERROR,
2002   .error_strings = tcp_error_strings,
2003   .n_next_nodes = TCP_ESTABLISHED_N_NEXT,
2004   .next_nodes =
2005   {
2006 #define _(s,n) [TCP_ESTABLISHED_NEXT_##s] = n,
2007     foreach_tcp_state_next
2008 #undef _
2009   },
2010   .format_trace = format_tcp_rx_trace_short,
2011 };
2012 /* *INDENT-ON* */
2013
2014 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_established_node, tcp4_established);
2015
2016 /* *INDENT-OFF* */
2017 VLIB_REGISTER_NODE (tcp6_established_node) =
2018 {
2019   .function = tcp6_established,
2020   .name = "tcp6-established",
2021   /* Takes a vector of packets. */
2022   .vector_size = sizeof (u32),
2023   .n_errors = TCP_N_ERROR,
2024   .error_strings = tcp_error_strings,
2025   .n_next_nodes = TCP_ESTABLISHED_N_NEXT,
2026   .next_nodes =
2027   {
2028 #define _(s,n) [TCP_ESTABLISHED_NEXT_##s] = n,
2029     foreach_tcp_state_next
2030 #undef _
2031   },
2032   .format_trace = format_tcp_rx_trace_short,
2033 };
2034 /* *INDENT-ON* */
2035
2036
2037 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_established_node, tcp6_established);
2038
2039 vlib_node_registration_t tcp4_syn_sent_node;
2040 vlib_node_registration_t tcp6_syn_sent_node;
2041
2042 static u8
2043 tcp_lookup_is_valid (tcp_connection_t * tc, tcp_header_t * hdr)
2044 {
2045   transport_connection_t *tmp = 0;
2046   u64 handle;
2047
2048   if (!tc)
2049     return 1;
2050
2051   /* Proxy case */
2052   if (tc->c_lcl_port == 0 && tc->state == TCP_STATE_LISTEN)
2053     return 1;
2054
2055   u8 is_valid = (tc->c_lcl_port == hdr->dst_port
2056                  && (tc->state == TCP_STATE_LISTEN
2057                      || tc->c_rmt_port == hdr->src_port));
2058
2059   if (!is_valid)
2060     {
2061       handle = session_lookup_half_open_handle (&tc->connection);
2062       tmp = session_lookup_half_open_connection (handle & 0xFFFFFFFF,
2063                                                  tc->c_proto, tc->c_is_ip4);
2064
2065       if (tmp)
2066         {
2067           if (tmp->lcl_port == hdr->dst_port
2068               && tmp->rmt_port == hdr->src_port)
2069             {
2070               TCP_DBG ("half-open is valid!");
2071             }
2072         }
2073     }
2074   return is_valid;
2075 }
2076
2077 /**
2078  * Lookup transport connection
2079  */
2080 static tcp_connection_t *
2081 tcp_lookup_connection (u32 fib_index, vlib_buffer_t * b, u8 thread_index,
2082                        u8 is_ip4)
2083 {
2084   tcp_header_t *tcp;
2085   transport_connection_t *tconn;
2086   tcp_connection_t *tc;
2087   u8 is_filtered = 0;
2088   if (is_ip4)
2089     {
2090       ip4_header_t *ip4;
2091       ip4 = vlib_buffer_get_current (b);
2092       tcp = ip4_next_header (ip4);
2093       tconn = session_lookup_connection_wt4 (fib_index,
2094                                              &ip4->dst_address,
2095                                              &ip4->src_address,
2096                                              tcp->dst_port,
2097                                              tcp->src_port,
2098                                              TRANSPORT_PROTO_TCP,
2099                                              thread_index, &is_filtered);
2100       tc = tcp_get_connection_from_transport (tconn);
2101       ASSERT (tcp_lookup_is_valid (tc, tcp));
2102     }
2103   else
2104     {
2105       ip6_header_t *ip6;
2106       ip6 = vlib_buffer_get_current (b);
2107       tcp = ip6_next_header (ip6);
2108       tconn = session_lookup_connection_wt6 (fib_index,
2109                                              &ip6->dst_address,
2110                                              &ip6->src_address,
2111                                              tcp->dst_port,
2112                                              tcp->src_port,
2113                                              TRANSPORT_PROTO_TCP,
2114                                              thread_index, &is_filtered);
2115       tc = tcp_get_connection_from_transport (tconn);
2116       ASSERT (tcp_lookup_is_valid (tc, tcp));
2117     }
2118   return tc;
2119 }
2120
2121 always_inline uword
2122 tcp46_syn_sent_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
2123                        vlib_frame_t * from_frame, int is_ip4)
2124 {
2125   tcp_main_t *tm = vnet_get_tcp_main ();
2126   u32 n_left_from, next_index, *from, *to_next;
2127   u32 my_thread_index = vm->thread_index, errors = 0;
2128
2129   from = vlib_frame_vector_args (from_frame);
2130   n_left_from = from_frame->n_vectors;
2131
2132   next_index = node->cached_next_index;
2133
2134   while (n_left_from > 0)
2135     {
2136       u32 n_left_to_next;
2137
2138       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
2139
2140       while (n_left_from > 0 && n_left_to_next > 0)
2141         {
2142           u32 bi0, ack0, seq0;
2143           vlib_buffer_t *b0;
2144           tcp_rx_trace_t *t0;
2145           tcp_header_t *tcp0 = 0;
2146           tcp_connection_t *tc0;
2147           tcp_connection_t *new_tc0;
2148           u32 next0 = tcp_next_drop (is_ip4), error0 = TCP_ERROR_ENQUEUED;
2149
2150           bi0 = from[0];
2151           to_next[0] = bi0;
2152           from += 1;
2153           to_next += 1;
2154           n_left_from -= 1;
2155           n_left_to_next -= 1;
2156
2157           b0 = vlib_get_buffer (vm, bi0);
2158           tc0 =
2159             tcp_half_open_connection_get (vnet_buffer (b0)->
2160                                           tcp.connection_index);
2161           if (PREDICT_FALSE (tc0 == 0))
2162             {
2163               error0 = TCP_ERROR_INVALID_CONNECTION;
2164               goto drop;
2165             }
2166
2167           /* Half-open completed recently but the connection was't removed
2168            * yet by the owning thread */
2169           if (PREDICT_FALSE (tc0->flags & TCP_CONN_HALF_OPEN_DONE))
2170             {
2171               /* Make sure the connection actually exists */
2172               ASSERT (tcp_lookup_connection (tc0->c_fib_index, b0,
2173                                              my_thread_index, is_ip4));
2174               goto drop;
2175             }
2176
2177           ack0 = vnet_buffer (b0)->tcp.ack_number;
2178           seq0 = vnet_buffer (b0)->tcp.seq_number;
2179           tcp0 = tcp_buffer_hdr (b0);
2180
2181           /* Crude check to see if the connection handle does not match
2182            * the packet. Probably connection just switched to established */
2183           if (PREDICT_FALSE (tcp0->dst_port != tc0->c_lcl_port
2184                              || tcp0->src_port != tc0->c_rmt_port))
2185             goto drop;
2186
2187           if (PREDICT_FALSE
2188               (!tcp_ack (tcp0) && !tcp_rst (tcp0) && !tcp_syn (tcp0)))
2189             goto drop;
2190
2191           /* SYNs, FINs and data consume sequence numbers */
2192           vnet_buffer (b0)->tcp.seq_end = seq0 + tcp_is_syn (tcp0)
2193             + tcp_is_fin (tcp0) + vnet_buffer (b0)->tcp.data_len;
2194
2195           /*
2196            *  1. check the ACK bit
2197            */
2198
2199           /*
2200            *   If the ACK bit is set
2201            *     If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send a reset (unless
2202            *     the RST bit is set, if so drop the segment and return)
2203            *       <SEQ=SEG.ACK><CTL=RST>
2204            *     and discard the segment.  Return.
2205            *     If SND.UNA =< SEG.ACK =< SND.NXT then the ACK is acceptable.
2206            */
2207           if (tcp_ack (tcp0))
2208             {
2209               if (seq_leq (ack0, tc0->iss) || seq_gt (ack0, tc0->snd_nxt))
2210                 {
2211                   clib_warning ("ack not in rcv wnd");
2212                   if (!tcp_rst (tcp0))
2213                     tcp_send_reset_w_pkt (tc0, b0, is_ip4);
2214                   goto drop;
2215                 }
2216
2217               /* Make sure ACK is valid */
2218               if (seq_gt (tc0->snd_una, ack0))
2219                 {
2220                   clib_warning ("ack invalid");
2221                   goto drop;
2222                 }
2223             }
2224
2225           /*
2226            * 2. check the RST bit
2227            */
2228
2229           if (tcp_rst (tcp0))
2230             {
2231               /* If ACK is acceptable, signal client that peer is not
2232                * willing to accept connection and drop connection*/
2233               if (tcp_ack (tcp0))
2234                 tcp_connection_reset (tc0);
2235               goto drop;
2236             }
2237
2238           /*
2239            * 3. check the security and precedence (skipped)
2240            */
2241
2242           /*
2243            * 4. check the SYN bit
2244            */
2245
2246           /* No SYN flag. Drop. */
2247           if (!tcp_syn (tcp0))
2248             {
2249               clib_warning ("not synack");
2250               goto drop;
2251             }
2252
2253           /* Parse options */
2254           if (tcp_options_parse (tcp0, &tc0->rcv_opts))
2255             {
2256               clib_warning ("options parse fail");
2257               goto drop;
2258             }
2259
2260           /* Valid SYN or SYN-ACK. Move connection from half-open pool to
2261            * current thread pool. */
2262           pool_get (tm->connections[my_thread_index], new_tc0);
2263           clib_memcpy (new_tc0, tc0, sizeof (*new_tc0));
2264           new_tc0->c_c_index = new_tc0 - tm->connections[my_thread_index];
2265           new_tc0->c_thread_index = my_thread_index;
2266           new_tc0->rcv_nxt = vnet_buffer (b0)->tcp.seq_end;
2267           new_tc0->irs = seq0;
2268           new_tc0->timers[TCP_TIMER_ESTABLISH] = TCP_TIMER_HANDLE_INVALID;
2269           new_tc0->timers[TCP_TIMER_RETRANSMIT_SYN] =
2270             TCP_TIMER_HANDLE_INVALID;
2271           new_tc0->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
2272
2273           /* If this is not the owning thread, wait for syn retransmit to
2274            * expire and cleanup then */
2275           if (tcp_half_open_connection_cleanup (tc0))
2276             tc0->flags |= TCP_CONN_HALF_OPEN_DONE;
2277
2278           if (tcp_opts_tstamp (&new_tc0->rcv_opts))
2279             {
2280               new_tc0->tsval_recent = new_tc0->rcv_opts.tsval;
2281               new_tc0->tsval_recent_age = tcp_time_now ();
2282             }
2283
2284           if (tcp_opts_wscale (&new_tc0->rcv_opts))
2285             new_tc0->snd_wscale = new_tc0->rcv_opts.wscale;
2286
2287           new_tc0->snd_wnd = clib_net_to_host_u16 (tcp0->window)
2288             << new_tc0->snd_wscale;
2289           new_tc0->snd_wl1 = seq0;
2290           new_tc0->snd_wl2 = ack0;
2291
2292           tcp_connection_init_vars (new_tc0);
2293
2294           /* SYN-ACK: See if we can switch to ESTABLISHED state */
2295           if (PREDICT_TRUE (tcp_ack (tcp0)))
2296             {
2297               /* Our SYN is ACKed: we have iss < ack = snd_una */
2298
2299               /* TODO Dequeue acknowledged segments if we support Fast Open */
2300               new_tc0->snd_una = ack0;
2301               new_tc0->state = TCP_STATE_ESTABLISHED;
2302
2303               /* Make sure las is initialized for the wnd computation */
2304               new_tc0->rcv_las = new_tc0->rcv_nxt;
2305
2306               /* Notify app that we have connection. If session layer can't
2307                * allocate session send reset */
2308               if (session_stream_connect_notify (&new_tc0->connection, 0))
2309                 {
2310                   clib_warning ("connect notify fail");
2311                   tcp_send_reset_w_pkt (new_tc0, b0, is_ip4);
2312                   tcp_connection_cleanup (new_tc0);
2313                   goto drop;
2314                 }
2315
2316               /* Make sure after data segment processing ACK is sent */
2317               new_tc0->flags |= TCP_CONN_SNDACK;
2318
2319               /* Update rtt with the syn-ack sample */
2320               tcp_update_rtt (new_tc0, vnet_buffer (b0)->tcp.ack_number);
2321               TCP_EVT_DBG (TCP_EVT_SYNACK_RCVD, new_tc0);
2322             }
2323           /* SYN: Simultaneous open. Change state to SYN-RCVD and send SYN-ACK */
2324           else
2325             {
2326               new_tc0->state = TCP_STATE_SYN_RCVD;
2327
2328               /* Notify app that we have connection */
2329               if (session_stream_connect_notify (&new_tc0->connection, 0))
2330                 {
2331                   tcp_connection_cleanup (new_tc0);
2332                   tcp_send_reset_w_pkt (tc0, b0, is_ip4);
2333                   TCP_EVT_DBG (TCP_EVT_RST_SENT, tc0);
2334                   goto drop;
2335                 }
2336
2337               tc0->rtt_ts = 0;
2338               tcp_init_snd_vars (tc0);
2339               tcp_make_synack (new_tc0, b0);
2340               next0 = tcp_next_output (is_ip4);
2341
2342               goto drop;
2343             }
2344
2345           /* Read data, if any */
2346           if (PREDICT_FALSE (vnet_buffer (b0)->tcp.data_len))
2347             {
2348               clib_warning ("rcvd data in syn-sent");
2349               error0 = tcp_segment_rcv (new_tc0, b0, &next0);
2350               if (error0 == TCP_ERROR_ACK_OK)
2351                 error0 = TCP_ERROR_SYN_ACKS_RCVD;
2352               tcp_maybe_inc_counter (syn_sent, error0, 1);
2353             }
2354           else
2355             {
2356               tcp_make_ack (new_tc0, b0);
2357               next0 = tcp_next_output (new_tc0->c_is_ip4);
2358             }
2359
2360         drop:
2361
2362           b0->error = error0 ? node->errors[error0] : 0;
2363           if (PREDICT_FALSE
2364               ((b0->flags & VLIB_BUFFER_IS_TRACED) && tcp0 != 0))
2365             {
2366               t0 = vlib_add_trace (vm, node, b0, sizeof (*t0));
2367               clib_memcpy (&t0->tcp_header, tcp0, sizeof (t0->tcp_header));
2368               clib_memcpy (&t0->tcp_connection, tc0,
2369                            sizeof (t0->tcp_connection));
2370             }
2371
2372           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
2373                                            n_left_to_next, bi0, next0);
2374         }
2375
2376       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
2377     }
2378
2379   errors = session_manager_flush_enqueue_events (TRANSPORT_PROTO_TCP,
2380                                                  my_thread_index);
2381   tcp_inc_counter (syn_sent, TCP_ERROR_EVENT_FIFO_FULL, errors);
2382   return from_frame->n_vectors;
2383 }
2384
2385 static uword
2386 tcp4_syn_sent (vlib_main_t * vm, vlib_node_runtime_t * node,
2387                vlib_frame_t * from_frame)
2388 {
2389   return tcp46_syn_sent_inline (vm, node, from_frame, 1 /* is_ip4 */ );
2390 }
2391
2392 static uword
2393 tcp6_syn_sent_rcv (vlib_main_t * vm, vlib_node_runtime_t * node,
2394                    vlib_frame_t * from_frame)
2395 {
2396   return tcp46_syn_sent_inline (vm, node, from_frame, 0 /* is_ip4 */ );
2397 }
2398
2399 /* *INDENT-OFF* */
2400 VLIB_REGISTER_NODE (tcp4_syn_sent_node) =
2401 {
2402   .function = tcp4_syn_sent,
2403   .name = "tcp4-syn-sent",
2404   /* Takes a vector of packets. */
2405   .vector_size = sizeof (u32),
2406   .n_errors = TCP_N_ERROR,
2407   .error_strings = tcp_error_strings,
2408   .n_next_nodes = TCP_SYN_SENT_N_NEXT,
2409   .next_nodes =
2410   {
2411 #define _(s,n) [TCP_SYN_SENT_NEXT_##s] = n,
2412     foreach_tcp_state_next
2413 #undef _
2414   },
2415   .format_trace = format_tcp_rx_trace_short,
2416 };
2417 /* *INDENT-ON* */
2418
2419 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_syn_sent_node, tcp4_syn_sent);
2420
2421 /* *INDENT-OFF* */
2422 VLIB_REGISTER_NODE (tcp6_syn_sent_node) =
2423 {
2424   .function = tcp6_syn_sent_rcv,
2425   .name = "tcp6-syn-sent",
2426   /* Takes a vector of packets. */
2427   .vector_size = sizeof (u32),
2428   .n_errors = TCP_N_ERROR,
2429   .error_strings = tcp_error_strings,
2430   .n_next_nodes = TCP_SYN_SENT_N_NEXT,
2431   .next_nodes =
2432   {
2433 #define _(s,n) [TCP_SYN_SENT_NEXT_##s] = n,
2434     foreach_tcp_state_next
2435 #undef _
2436   },
2437   .format_trace = format_tcp_rx_trace_short,
2438 };
2439 /* *INDENT-ON* */
2440
2441 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_syn_sent_node, tcp6_syn_sent_rcv);
2442
2443 vlib_node_registration_t tcp4_rcv_process_node;
2444 vlib_node_registration_t tcp6_rcv_process_node;
2445
2446 /**
2447  * Handles reception for all states except LISTEN, SYN-SENT and ESTABLISHED
2448  * as per RFC793 p. 64
2449  */
2450 always_inline uword
2451 tcp46_rcv_process_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
2452                           vlib_frame_t * from_frame, int is_ip4)
2453 {
2454   u32 n_left_from, next_index, *from, *to_next, n_fins = 0;
2455   u32 my_thread_index = vm->thread_index, errors = 0;
2456
2457   from = vlib_frame_vector_args (from_frame);
2458   n_left_from = from_frame->n_vectors;
2459   next_index = node->cached_next_index;
2460
2461   while (n_left_from > 0)
2462     {
2463       u32 n_left_to_next;
2464
2465       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
2466
2467       while (n_left_from > 0 && n_left_to_next > 0)
2468         {
2469           u32 bi0;
2470           vlib_buffer_t *b0;
2471           tcp_header_t *tcp0 = 0;
2472           tcp_connection_t *tc0;
2473           u32 next0 = tcp_next_drop (is_ip4), error0 = TCP_ERROR_NONE;
2474           u8 is_fin0;
2475
2476           bi0 = from[0];
2477           to_next[0] = bi0;
2478           from += 1;
2479           to_next += 1;
2480           n_left_from -= 1;
2481           n_left_to_next -= 1;
2482
2483           b0 = vlib_get_buffer (vm, bi0);
2484           tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
2485                                     my_thread_index);
2486           if (PREDICT_FALSE (tc0 == 0))
2487             {
2488               error0 = TCP_ERROR_INVALID_CONNECTION;
2489               goto drop;
2490             }
2491
2492           tcp0 = tcp_buffer_hdr (b0);
2493           is_fin0 = tcp_is_fin (tcp0);
2494
2495           /* SYNs, FINs and data consume sequence numbers */
2496           vnet_buffer (b0)->tcp.seq_end = vnet_buffer (b0)->tcp.seq_number
2497             + tcp_is_syn (tcp0) + is_fin0 + vnet_buffer (b0)->tcp.data_len;
2498
2499           if (CLIB_DEBUG)
2500             {
2501               tcp_connection_t *tmp;
2502               tmp = tcp_lookup_connection (tc0->c_fib_index, b0,
2503                                            my_thread_index, is_ip4);
2504               if (tmp->state != tc0->state)
2505                 {
2506                   clib_warning ("state changed");
2507                   goto drop;
2508                 }
2509             }
2510
2511           /*
2512            * Special treatment for CLOSED
2513            */
2514           if (PREDICT_FALSE (tc0->state == TCP_STATE_CLOSED))
2515             {
2516               error0 = TCP_ERROR_CONNECTION_CLOSED;
2517               goto drop;
2518             }
2519
2520           /*
2521            * For all other states (except LISTEN)
2522            */
2523
2524           /* 1-4: check SEQ, RST, SYN */
2525           if (PREDICT_FALSE (tcp_segment_validate (vm, tc0, b0, tcp0,
2526                                                    &next0, &error0)))
2527             {
2528               tcp_maybe_inc_counter (rcv_process, error0, 1);
2529               goto drop;
2530             }
2531
2532           /* 5: check the ACK field  */
2533           switch (tc0->state)
2534             {
2535             case TCP_STATE_SYN_RCVD:
2536               /*
2537                * If the segment acknowledgment is not acceptable, form a
2538                * reset segment,
2539                *  <SEQ=SEG.ACK><CTL=RST>
2540                * and send it.
2541                */
2542               if (!tcp_rcv_ack_is_acceptable (tc0, b0))
2543                 {
2544                   TCP_DBG ("connection not accepted");
2545                   tcp_send_reset_w_pkt (tc0, b0, is_ip4);
2546                   error0 = TCP_ERROR_ACK_INVALID;
2547                   goto drop;
2548                 }
2549
2550               /* Update rtt and rto */
2551               tcp_update_rtt (tc0, vnet_buffer (b0)->tcp.ack_number);
2552
2553               /* Switch state to ESTABLISHED */
2554               tc0->state = TCP_STATE_ESTABLISHED;
2555               TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc0);
2556
2557               /* Initialize session variables */
2558               tc0->snd_una = vnet_buffer (b0)->tcp.ack_number;
2559               tc0->snd_wnd = clib_net_to_host_u16 (tcp0->window)
2560                 << tc0->rcv_opts.wscale;
2561               tc0->snd_wl1 = vnet_buffer (b0)->tcp.seq_number;
2562               tc0->snd_wl2 = vnet_buffer (b0)->tcp.ack_number;
2563
2564               /* Reset SYN-ACK retransmit and SYN_RCV establish timers */
2565               tcp_retransmit_timer_reset (tc0);
2566               tcp_timer_reset (tc0, TCP_TIMER_ESTABLISH);
2567               stream_session_accept_notify (&tc0->connection);
2568               error0 = TCP_ERROR_ACK_OK;
2569               break;
2570             case TCP_STATE_ESTABLISHED:
2571               /* We can get packets in established state here because they
2572                * were enqueued before state change */
2573               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
2574                 {
2575                   tcp_maybe_inc_counter (rcv_process, error0, 1);
2576                   goto drop;
2577                 }
2578
2579               break;
2580             case TCP_STATE_FIN_WAIT_1:
2581               /* In addition to the processing for the ESTABLISHED state, if
2582                * our FIN is now acknowledged then enter FIN-WAIT-2 and
2583                * continue processing in that state. */
2584               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
2585                 {
2586                   tcp_maybe_inc_counter (rcv_process, error0, 1);
2587                   goto drop;
2588                 }
2589
2590               /* Still have to send the FIN */
2591               if (tc0->flags & TCP_CONN_FINPNDG)
2592                 {
2593                   /* TX fifo finally drained */
2594                   if (!session_tx_fifo_max_dequeue (&tc0->connection))
2595                     tcp_send_fin (tc0);
2596                 }
2597               /* If FIN is ACKed */
2598               else if (tc0->snd_una == tc0->snd_una_max)
2599                 {
2600                   tc0->state = TCP_STATE_FIN_WAIT_2;
2601                   TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc0);
2602
2603                   /* Stop all retransmit timers because we have nothing more
2604                    * to send. Enable waitclose though because we're willing to
2605                    * wait for peer's FIN but not indefinitely. */
2606                   tcp_connection_timers_reset (tc0);
2607                   tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
2608                 }
2609               break;
2610             case TCP_STATE_FIN_WAIT_2:
2611               /* In addition to the processing for the ESTABLISHED state, if
2612                * the retransmission queue is empty, the user's CLOSE can be
2613                * acknowledged ("ok") but do not delete the TCB. */
2614               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
2615                 {
2616                   tcp_maybe_inc_counter (rcv_process, error0, 1);
2617                   goto drop;
2618                 }
2619               break;
2620             case TCP_STATE_CLOSE_WAIT:
2621               /* Do the same processing as for the ESTABLISHED state. */
2622               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
2623                 {
2624                   tcp_maybe_inc_counter (rcv_process, error0, 1);
2625                   goto drop;
2626                 }
2627               if (tc0->flags & TCP_CONN_FINPNDG)
2628                 {
2629                   /* TX fifo finally drained */
2630                   if (!session_tx_fifo_max_dequeue (&tc0->connection))
2631                     {
2632                       tcp_send_fin (tc0);
2633                       tcp_connection_timers_reset (tc0);
2634                       tc0->state = TCP_STATE_LAST_ACK;
2635                       tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE,
2636                                         TCP_2MSL_TIME);
2637                     }
2638                 }
2639               break;
2640             case TCP_STATE_CLOSING:
2641               /* In addition to the processing for the ESTABLISHED state, if
2642                * the ACK acknowledges our FIN then enter the TIME-WAIT state,
2643                * otherwise ignore the segment. */
2644               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
2645                 {
2646                   tcp_maybe_inc_counter (rcv_process, error0, 1);
2647                   goto drop;
2648                 }
2649
2650               tc0->state = TCP_STATE_TIME_WAIT;
2651               TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc0);
2652               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_TIMEWAIT_TIME);
2653               goto drop;
2654
2655               break;
2656             case TCP_STATE_LAST_ACK:
2657               /* The only thing that [should] arrive in this state is an
2658                * acknowledgment of our FIN. If our FIN is now acknowledged,
2659                * delete the TCB, enter the CLOSED state, and return. */
2660
2661               if (!tcp_rcv_ack_is_acceptable (tc0, b0))
2662                 {
2663                   error0 = TCP_ERROR_ACK_INVALID;
2664                   goto drop;
2665                 }
2666               error0 = TCP_ERROR_ACK_OK;
2667               tc0->snd_una = vnet_buffer (b0)->tcp.ack_number;
2668               /* Apparently our ACK for the peer's FIN was lost */
2669               if (is_fin0 && tc0->snd_una != tc0->snd_una_max)
2670                 {
2671                   tcp_send_fin (tc0);
2672                   goto drop;
2673                 }
2674
2675               tc0->state = TCP_STATE_CLOSED;
2676               TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc0);
2677               /* Delete the connection/session since the pipes should be
2678                * clear by now */
2679               tcp_connection_del (tc0);
2680
2681               goto drop;
2682
2683               break;
2684             case TCP_STATE_TIME_WAIT:
2685               /* The only thing that can arrive in this state is a
2686                * retransmission of the remote FIN. Acknowledge it, and restart
2687                * the 2 MSL timeout. */
2688
2689               if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
2690                 {
2691                   tcp_maybe_inc_counter (rcv_process, error0, 1);
2692                   goto drop;
2693                 }
2694
2695               tcp_make_ack (tc0, b0);
2696               next0 = tcp_next_output (is_ip4);
2697               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_TIMEWAIT_TIME);
2698               goto drop;
2699
2700               break;
2701             default:
2702               ASSERT (0);
2703             }
2704
2705           /* 6: check the URG bit TODO */
2706
2707           /* 7: process the segment text */
2708           switch (tc0->state)
2709             {
2710             case TCP_STATE_ESTABLISHED:
2711             case TCP_STATE_FIN_WAIT_1:
2712             case TCP_STATE_FIN_WAIT_2:
2713               if (vnet_buffer (b0)->tcp.data_len)
2714                 {
2715                   error0 = tcp_segment_rcv (tc0, b0, &next0);
2716                   tcp_maybe_inc_counter (rcv_process, error0, 1);
2717                 }
2718               else if (is_fin0)
2719                 tc0->rcv_nxt += 1;
2720               break;
2721             case TCP_STATE_CLOSE_WAIT:
2722             case TCP_STATE_CLOSING:
2723             case TCP_STATE_LAST_ACK:
2724             case TCP_STATE_TIME_WAIT:
2725               /* This should not occur, since a FIN has been received from the
2726                * remote side.  Ignore the segment text. */
2727               break;
2728             }
2729
2730           /* 8: check the FIN bit */
2731           if (!is_fin0)
2732             goto drop;
2733
2734           switch (tc0->state)
2735             {
2736             case TCP_STATE_ESTABLISHED:
2737             case TCP_STATE_SYN_RCVD:
2738               /* Send FIN-ACK notify app and enter CLOSE-WAIT */
2739               tcp_connection_timers_reset (tc0);
2740               tcp_make_fin (tc0, b0);
2741               tc0->snd_nxt += 1;
2742               tc0->snd_una_max = tc0->snd_nxt;
2743               tcp_retransmit_timer_set (tc0);
2744               next0 = tcp_next_output (tc0->c_is_ip4);
2745               stream_session_disconnect_notify (&tc0->connection);
2746               tc0->state = TCP_STATE_CLOSE_WAIT;
2747               TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc0);
2748               break;
2749             case TCP_STATE_CLOSE_WAIT:
2750             case TCP_STATE_CLOSING:
2751             case TCP_STATE_LAST_ACK:
2752               /* move along .. */
2753               break;
2754             case TCP_STATE_FIN_WAIT_1:
2755               tc0->state = TCP_STATE_CLOSING;
2756               tcp_make_ack (tc0, b0);
2757               next0 = tcp_next_output (is_ip4);
2758               TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc0);
2759               /* Wait for ACK but not forever */
2760               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_2MSL_TIME);
2761               break;
2762             case TCP_STATE_FIN_WAIT_2:
2763               /* Got FIN, send ACK! Be more aggressive with resource cleanup */
2764               tc0->state = TCP_STATE_TIME_WAIT;
2765               tcp_connection_timers_reset (tc0);
2766               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_TIMEWAIT_TIME);
2767               tcp_make_ack (tc0, b0);
2768               next0 = tcp_next_output (is_ip4);
2769               TCP_EVT_DBG (TCP_EVT_STATE_CHANGE, tc0);
2770               break;
2771             case TCP_STATE_TIME_WAIT:
2772               /* Remain in the TIME-WAIT state. Restart the time-wait
2773                * timeout.
2774                */
2775               tcp_timer_update (tc0, TCP_TIMER_WAITCLOSE, TCP_TIMEWAIT_TIME);
2776               break;
2777             }
2778           TCP_EVT_DBG (TCP_EVT_FIN_RCVD, tc0);
2779           n_fins += 1;
2780
2781         drop:
2782           b0->error = error0 ? node->errors[error0] : 0;
2783
2784           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
2785             {
2786               tcp_rx_trace_t *t0 =
2787                 vlib_add_trace (vm, node, b0, sizeof (*t0));
2788               tcp_set_rx_trace_data (t0, tc0, tcp0, b0, is_ip4);
2789             }
2790
2791           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
2792                                            n_left_to_next, bi0, next0);
2793         }
2794
2795       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
2796     }
2797
2798   errors = session_manager_flush_enqueue_events (TRANSPORT_PROTO_TCP,
2799                                                  my_thread_index);
2800   tcp_inc_counter (rcv_process, TCP_ERROR_EVENT_FIFO_FULL, errors);
2801   tcp_inc_counter (rcv_process, TCP_ERROR_FIN_RCVD, n_fins);
2802   return from_frame->n_vectors;
2803 }
2804
2805 static uword
2806 tcp4_rcv_process (vlib_main_t * vm, vlib_node_runtime_t * node,
2807                   vlib_frame_t * from_frame)
2808 {
2809   return tcp46_rcv_process_inline (vm, node, from_frame, 1 /* is_ip4 */ );
2810 }
2811
2812 static uword
2813 tcp6_rcv_process (vlib_main_t * vm, vlib_node_runtime_t * node,
2814                   vlib_frame_t * from_frame)
2815 {
2816   return tcp46_rcv_process_inline (vm, node, from_frame, 0 /* is_ip4 */ );
2817 }
2818
2819 /* *INDENT-OFF* */
2820 VLIB_REGISTER_NODE (tcp4_rcv_process_node) =
2821 {
2822   .function = tcp4_rcv_process,
2823   .name = "tcp4-rcv-process",
2824   /* Takes a vector of packets. */
2825   .vector_size = sizeof (u32),
2826   .n_errors = TCP_N_ERROR,
2827   .error_strings = tcp_error_strings,
2828   .n_next_nodes = TCP_RCV_PROCESS_N_NEXT,
2829   .next_nodes =
2830   {
2831 #define _(s,n) [TCP_RCV_PROCESS_NEXT_##s] = n,
2832     foreach_tcp_state_next
2833 #undef _
2834   },
2835   .format_trace = format_tcp_rx_trace_short,
2836 };
2837 /* *INDENT-ON* */
2838
2839 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_rcv_process_node, tcp4_rcv_process);
2840
2841 /* *INDENT-OFF* */
2842 VLIB_REGISTER_NODE (tcp6_rcv_process_node) =
2843 {
2844   .function = tcp6_rcv_process,
2845   .name = "tcp6-rcv-process",
2846   /* Takes a vector of packets. */
2847   .vector_size = sizeof (u32),
2848   .n_errors = TCP_N_ERROR,
2849   .error_strings = tcp_error_strings,
2850   .n_next_nodes = TCP_RCV_PROCESS_N_NEXT,
2851   .next_nodes =
2852   {
2853 #define _(s,n) [TCP_RCV_PROCESS_NEXT_##s] = n,
2854     foreach_tcp_state_next
2855 #undef _
2856   },
2857   .format_trace = format_tcp_rx_trace_short,
2858 };
2859 /* *INDENT-ON* */
2860
2861 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_rcv_process_node, tcp6_rcv_process);
2862
2863 vlib_node_registration_t tcp4_listen_node;
2864 vlib_node_registration_t tcp6_listen_node;
2865
2866 /**
2867  * LISTEN state processing as per RFC 793 p. 65
2868  */
2869 always_inline uword
2870 tcp46_listen_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
2871                      vlib_frame_t * from_frame, int is_ip4)
2872 {
2873   u32 n_left_from, next_index, *from, *to_next, n_syns = 0;
2874   u32 my_thread_index = vm->thread_index;
2875
2876   from = vlib_frame_vector_args (from_frame);
2877   n_left_from = from_frame->n_vectors;
2878
2879   next_index = node->cached_next_index;
2880
2881   while (n_left_from > 0)
2882     {
2883       u32 n_left_to_next;
2884
2885       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
2886
2887       while (n_left_from > 0 && n_left_to_next > 0)
2888         {
2889           u32 bi0;
2890           vlib_buffer_t *b0;
2891           tcp_rx_trace_t *t0;
2892           tcp_header_t *th0 = 0;
2893           tcp_connection_t *lc0;
2894           ip4_header_t *ip40;
2895           ip6_header_t *ip60;
2896           tcp_connection_t *child0;
2897           u32 error0 = TCP_ERROR_NONE, next0 = tcp_next_drop (is_ip4);
2898
2899           bi0 = from[0];
2900           to_next[0] = bi0;
2901           from += 1;
2902           to_next += 1;
2903           n_left_from -= 1;
2904           n_left_to_next -= 1;
2905
2906           b0 = vlib_get_buffer (vm, bi0);
2907           lc0 = tcp_listener_get (vnet_buffer (b0)->tcp.connection_index);
2908
2909           if (is_ip4)
2910             {
2911               ip40 = vlib_buffer_get_current (b0);
2912               th0 = ip4_next_header (ip40);
2913             }
2914           else
2915             {
2916               ip60 = vlib_buffer_get_current (b0);
2917               th0 = ip6_next_header (ip60);
2918             }
2919
2920           /* Create child session. For syn-flood protection use filter */
2921
2922           /* 1. first check for an RST: handled in dispatch */
2923           /* if (tcp_rst (th0))
2924              goto drop; */
2925
2926           /* 2. second check for an ACK: handled in dispatch */
2927           /* if (tcp_ack (th0))
2928              {
2929              tcp_send_reset (b0, is_ip4);
2930              goto drop;
2931              } */
2932
2933           /* 3. check for a SYN (did that already) */
2934
2935           /* Make sure connection wasn't just created */
2936           child0 = tcp_lookup_connection (lc0->c_fib_index, b0,
2937                                           my_thread_index, is_ip4);
2938           if (PREDICT_FALSE (child0->state != TCP_STATE_LISTEN))
2939             {
2940               error0 = TCP_ERROR_CREATE_EXISTS;
2941               goto drop;
2942             }
2943
2944           /* Create child session and send SYN-ACK */
2945           child0 = tcp_connection_new (my_thread_index);
2946           child0->c_lcl_port = th0->dst_port;
2947           child0->c_rmt_port = th0->src_port;
2948           child0->c_is_ip4 = is_ip4;
2949           child0->state = TCP_STATE_SYN_RCVD;
2950           child0->c_fib_index = lc0->c_fib_index;
2951
2952           if (is_ip4)
2953             {
2954               child0->c_lcl_ip4.as_u32 = ip40->dst_address.as_u32;
2955               child0->c_rmt_ip4.as_u32 = ip40->src_address.as_u32;
2956             }
2957           else
2958             {
2959               clib_memcpy (&child0->c_lcl_ip6, &ip60->dst_address,
2960                            sizeof (ip6_address_t));
2961               clib_memcpy (&child0->c_rmt_ip6, &ip60->src_address,
2962                            sizeof (ip6_address_t));
2963             }
2964
2965           if (tcp_options_parse (th0, &child0->rcv_opts))
2966             {
2967               clib_warning ("options parse fail");
2968               goto drop;
2969             }
2970
2971           child0->irs = vnet_buffer (b0)->tcp.seq_number;
2972           child0->rcv_nxt = vnet_buffer (b0)->tcp.seq_number + 1;
2973           child0->rcv_las = child0->rcv_nxt;
2974           child0->sw_if_index = vnet_buffer (b0)->sw_if_index[VLIB_RX];
2975
2976           /* RFC1323: TSval timestamps sent on {SYN} and {SYN,ACK}
2977            * segments are used to initialize PAWS. */
2978           if (tcp_opts_tstamp (&child0->rcv_opts))
2979             {
2980               child0->tsval_recent = child0->rcv_opts.tsval;
2981               child0->tsval_recent_age = tcp_time_now ();
2982             }
2983
2984           if (tcp_opts_wscale (&child0->rcv_opts))
2985             child0->snd_wscale = child0->rcv_opts.wscale;
2986
2987           child0->snd_wnd = clib_net_to_host_u16 (th0->window)
2988             << child0->snd_wscale;
2989           child0->snd_wl1 = vnet_buffer (b0)->tcp.seq_number;
2990           child0->snd_wl2 = vnet_buffer (b0)->tcp.ack_number;
2991
2992           tcp_connection_init_vars (child0);
2993           TCP_EVT_DBG (TCP_EVT_SYN_RCVD, child0, 1);
2994
2995           if (stream_session_accept (&child0->connection, lc0->c_s_index,
2996                                      0 /* notify */ ))
2997             {
2998               clib_warning ("session accept fail");
2999               tcp_connection_cleanup (child0);
3000               error0 = TCP_ERROR_CREATE_SESSION_FAIL;
3001               goto drop;
3002             }
3003
3004           /* Reuse buffer to make syn-ack and send */
3005           tcp_make_synack (child0, b0);
3006           next0 = tcp_next_output (is_ip4);
3007           tcp_timer_set (child0, TCP_TIMER_ESTABLISH, TCP_SYN_RCVD_TIME);
3008
3009         drop:
3010           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
3011             {
3012               t0 = vlib_add_trace (vm, node, b0, sizeof (*t0));
3013               clib_memcpy (&t0->tcp_header, th0, sizeof (t0->tcp_header));
3014               clib_memcpy (&t0->tcp_connection, lc0,
3015                            sizeof (t0->tcp_connection));
3016             }
3017
3018           n_syns += (error0 == TCP_ERROR_NONE);
3019           b0->error = node->errors[error0];
3020
3021           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
3022                                            n_left_to_next, bi0, next0);
3023         }
3024
3025       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
3026     }
3027
3028   tcp_inc_counter (listen, TCP_ERROR_SYNS_RCVD, n_syns);
3029   return from_frame->n_vectors;
3030 }
3031
3032 static uword
3033 tcp4_listen (vlib_main_t * vm, vlib_node_runtime_t * node,
3034              vlib_frame_t * from_frame)
3035 {
3036   return tcp46_listen_inline (vm, node, from_frame, 1 /* is_ip4 */ );
3037 }
3038
3039 static uword
3040 tcp6_listen (vlib_main_t * vm, vlib_node_runtime_t * node,
3041              vlib_frame_t * from_frame)
3042 {
3043   return tcp46_listen_inline (vm, node, from_frame, 0 /* is_ip4 */ );
3044 }
3045
3046 /* *INDENT-OFF* */
3047 VLIB_REGISTER_NODE (tcp4_listen_node) =
3048 {
3049   .function = tcp4_listen,
3050   .name = "tcp4-listen",
3051   /* Takes a vector of packets. */
3052   .vector_size = sizeof (u32),
3053   .n_errors = TCP_N_ERROR,
3054   .error_strings = tcp_error_strings,
3055   .n_next_nodes = TCP_LISTEN_N_NEXT,
3056   .next_nodes =
3057   {
3058 #define _(s,n) [TCP_LISTEN_NEXT_##s] = n,
3059     foreach_tcp_state_next
3060 #undef _
3061   },
3062   .format_trace = format_tcp_rx_trace_short,
3063 };
3064 /* *INDENT-ON* */
3065
3066 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_listen_node, tcp4_listen);
3067
3068 /* *INDENT-OFF* */
3069 VLIB_REGISTER_NODE (tcp6_listen_node) =
3070 {
3071   .function = tcp6_listen,
3072   .name = "tcp6-listen",
3073   /* Takes a vector of packets. */
3074   .vector_size = sizeof (u32),
3075   .n_errors = TCP_N_ERROR,
3076   .error_strings = tcp_error_strings,
3077   .n_next_nodes = TCP_LISTEN_N_NEXT,
3078   .next_nodes =
3079   {
3080 #define _(s,n) [TCP_LISTEN_NEXT_##s] = n,
3081     foreach_tcp_state_next
3082 #undef _
3083   },
3084   .format_trace = format_tcp_rx_trace_short,
3085 };
3086 /* *INDENT-ON* */
3087
3088 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_listen_node, tcp6_listen);
3089
3090 vlib_node_registration_t tcp4_input_node;
3091 vlib_node_registration_t tcp6_input_node;
3092
3093 typedef enum _tcp_input_next
3094 {
3095   TCP_INPUT_NEXT_DROP,
3096   TCP_INPUT_NEXT_LISTEN,
3097   TCP_INPUT_NEXT_RCV_PROCESS,
3098   TCP_INPUT_NEXT_SYN_SENT,
3099   TCP_INPUT_NEXT_ESTABLISHED,
3100   TCP_INPUT_NEXT_RESET,
3101   TCP_INPUT_NEXT_PUNT,
3102   TCP_INPUT_N_NEXT
3103 } tcp_input_next_t;
3104
3105 #define foreach_tcp4_input_next                 \
3106   _ (DROP, "ip4-drop")                          \
3107   _ (LISTEN, "tcp4-listen")                     \
3108   _ (RCV_PROCESS, "tcp4-rcv-process")           \
3109   _ (SYN_SENT, "tcp4-syn-sent")                 \
3110   _ (ESTABLISHED, "tcp4-established")           \
3111   _ (RESET, "tcp4-reset")                       \
3112   _ (PUNT, "ip4-punt")
3113
3114 #define foreach_tcp6_input_next                 \
3115   _ (DROP, "ip6-drop")                          \
3116   _ (LISTEN, "tcp6-listen")                     \
3117   _ (RCV_PROCESS, "tcp6-rcv-process")           \
3118   _ (SYN_SENT, "tcp6-syn-sent")                 \
3119   _ (ESTABLISHED, "tcp6-established")           \
3120   _ (RESET, "tcp6-reset")                       \
3121   _ (PUNT, "ip6-punt")
3122
3123 #define filter_flags (TCP_FLAG_SYN|TCP_FLAG_ACK|TCP_FLAG_RST|TCP_FLAG_FIN)
3124
3125 static void
3126 tcp_input_trace_frame (vlib_main_t * vm, vlib_node_runtime_t * node,
3127                        vlib_buffer_t ** bs, u32 n_bufs, u8 is_ip4)
3128 {
3129   tcp_connection_t *tc;
3130   tcp_header_t *tcp;
3131   tcp_rx_trace_t *t;
3132   int i;
3133
3134   for (i = 0; i < n_bufs; i++)
3135     {
3136       if (bs[i]->flags & VLIB_BUFFER_IS_TRACED)
3137         {
3138           t = vlib_add_trace (vm, node, bs[i], sizeof (*t));
3139           tc = tcp_connection_get (vnet_buffer (bs[i])->tcp.connection_index,
3140                                    vm->thread_index);
3141           tcp = vlib_buffer_get_current (bs[i]);
3142           tcp_set_rx_trace_data (t, tc, tcp, bs[i], is_ip4);
3143         }
3144     }
3145 }
3146
3147 static void
3148 tcp_input_set_error_next (tcp_main_t * tm, u16 * next, u32 * error, u8 is_ip4)
3149 {
3150   if (*error == TCP_ERROR_FILTERED)
3151     {
3152       *next = TCP_INPUT_NEXT_DROP;
3153     }
3154   else if ((is_ip4 && tm->punt_unknown4) || (!is_ip4 && tm->punt_unknown6))
3155     {
3156       *next = TCP_INPUT_NEXT_PUNT;
3157       *error = TCP_ERROR_PUNT;
3158     }
3159   else
3160     {
3161       *next = TCP_INPUT_NEXT_RESET;
3162       *error = TCP_ERROR_NO_LISTENER;
3163     }
3164 }
3165
3166 static inline tcp_connection_t *
3167 tcp_input_lookup_buffer (vlib_buffer_t * b, u8 thread_index, u32 * error,
3168                          u8 is_ip4)
3169 {
3170   u32 fib_index = vnet_buffer (b)->ip.fib_index;
3171   int n_advance_bytes, n_data_bytes;
3172   transport_connection_t *tc;
3173   tcp_header_t *tcp;
3174   u8 is_filtered = 0;
3175
3176   if (is_ip4)
3177     {
3178       ip4_header_t *ip4 = vlib_buffer_get_current (b);
3179       tcp = ip4_next_header (ip4);
3180       vnet_buffer (b)->tcp.hdr_offset = (u8 *) tcp - (u8 *) ip4;
3181       n_advance_bytes = (ip4_header_bytes (ip4) + tcp_header_bytes (tcp));
3182       n_data_bytes = clib_net_to_host_u16 (ip4->length) - n_advance_bytes;
3183
3184       /* Length check. Checksum computed by ipx_local no need to compute again */
3185       if (PREDICT_FALSE (n_advance_bytes < 0))
3186         {
3187           *error = TCP_ERROR_LENGTH;
3188           return 0;
3189         }
3190
3191       tc = session_lookup_connection_wt4 (fib_index, &ip4->dst_address,
3192                                           &ip4->src_address, tcp->dst_port,
3193                                           tcp->src_port, TRANSPORT_PROTO_TCP,
3194                                           thread_index, &is_filtered);
3195     }
3196   else
3197     {
3198       ip6_header_t *ip6 = vlib_buffer_get_current (b);
3199       tcp = ip6_next_header (ip6);
3200       vnet_buffer (b)->tcp.hdr_offset = (u8 *) tcp - (u8 *) ip6;
3201       n_advance_bytes = tcp_header_bytes (tcp);
3202       n_data_bytes = clib_net_to_host_u16 (ip6->payload_length)
3203         - n_advance_bytes;
3204       n_advance_bytes += sizeof (ip6[0]);
3205
3206       if (PREDICT_FALSE (n_advance_bytes < 0))
3207         {
3208           *error = TCP_ERROR_LENGTH;
3209           return 0;
3210         }
3211
3212       tc = session_lookup_connection_wt6 (fib_index, &ip6->dst_address,
3213                                           &ip6->src_address, tcp->dst_port,
3214                                           tcp->src_port, TRANSPORT_PROTO_TCP,
3215                                           thread_index, &is_filtered);
3216     }
3217
3218   vnet_buffer (b)->tcp.seq_number = clib_net_to_host_u32 (tcp->seq_number);
3219   vnet_buffer (b)->tcp.ack_number = clib_net_to_host_u32 (tcp->ack_number);
3220   vnet_buffer (b)->tcp.data_offset = n_advance_bytes;
3221   vnet_buffer (b)->tcp.data_len = n_data_bytes;
3222   vnet_buffer (b)->tcp.flags = 0;
3223
3224   *error = is_filtered ? TCP_ERROR_FILTERED : *error;
3225
3226   return tcp_get_connection_from_transport (tc);
3227 }
3228
3229 static inline void
3230 tcp_input_dispatch_buffer (tcp_main_t * tm, tcp_connection_t * tc,
3231                            vlib_buffer_t * b, u16 * next, u32 * error)
3232 {
3233   tcp_header_t *tcp;
3234   u8 flags;
3235
3236   tcp = tcp_buffer_hdr (b);
3237   flags = tcp->flags & filter_flags;
3238   *next = tm->dispatch_table[tc->state][flags].next;
3239   *error = tm->dispatch_table[tc->state][flags].error;
3240
3241   if (PREDICT_FALSE (*error == TCP_ERROR_DISPATCH
3242                      || *next == TCP_INPUT_NEXT_RESET))
3243     {
3244       /* Overload tcp flags to store state */
3245       tcp_state_t state = tc->state;
3246       vnet_buffer (b)->tcp.flags = tc->state;
3247
3248       if (*error == TCP_ERROR_DISPATCH)
3249         clib_warning ("disp error state %U flags %U", format_tcp_state,
3250                       state, format_tcp_flags, (int) flags);
3251     }
3252 }
3253
3254 always_inline uword
3255 tcp46_input_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
3256                     vlib_frame_t * frame, int is_ip4)
3257 {
3258   u32 n_left_from, *from, thread_index = vm->thread_index;
3259   tcp_main_t *tm = vnet_get_tcp_main ();
3260   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b;
3261   u16 nexts[VLIB_FRAME_SIZE], *next;
3262
3263   tcp_set_time_now (thread_index);
3264
3265   from = vlib_frame_vector_args (frame);
3266   n_left_from = frame->n_vectors;
3267   vlib_get_buffers (vm, from, bufs, n_left_from);
3268
3269   b = bufs;
3270   next = nexts;
3271
3272   while (n_left_from >= 4)
3273     {
3274       u32 error0 = TCP_ERROR_NO_LISTENER, error1 = TCP_ERROR_NO_LISTENER;
3275       tcp_connection_t *tc0, *tc1;
3276
3277       {
3278         vlib_prefetch_buffer_header (b[2], STORE);
3279         CLIB_PREFETCH (b[2]->data, 2 * CLIB_CACHE_LINE_BYTES, LOAD);
3280
3281         vlib_prefetch_buffer_header (b[3], STORE);
3282         CLIB_PREFETCH (b[3]->data, 2 * CLIB_CACHE_LINE_BYTES, LOAD);
3283       }
3284
3285       next[0] = next[1] = TCP_INPUT_NEXT_DROP;
3286
3287       tc0 = tcp_input_lookup_buffer (b[0], thread_index, &error0, is_ip4);
3288       tc1 = tcp_input_lookup_buffer (b[1], thread_index, &error1, is_ip4);
3289
3290       if (PREDICT_TRUE (!tc0 + !tc1 == 0))
3291         {
3292           ASSERT (tcp_lookup_is_valid (tc0, tcp_buffer_hdr (b[0])));
3293           ASSERT (tcp_lookup_is_valid (tc1, tcp_buffer_hdr (b[1])));
3294
3295           vnet_buffer (b[0])->tcp.connection_index = tc0->c_c_index;
3296           vnet_buffer (b[1])->tcp.connection_index = tc1->c_c_index;
3297
3298           tcp_input_dispatch_buffer (tm, tc0, b[0], &next[0], &error0);
3299           tcp_input_dispatch_buffer (tm, tc1, b[1], &next[1], &error1);
3300         }
3301       else
3302         {
3303           if (PREDICT_TRUE (tc0 != 0))
3304             {
3305               ASSERT (tcp_lookup_is_valid (tc0, tcp_buffer_hdr (b[0])));
3306               vnet_buffer (b[0])->tcp.connection_index = tc0->c_c_index;
3307               tcp_input_dispatch_buffer (tm, tc0, b[0], &next[0], &error0);
3308             }
3309           else
3310             tcp_input_set_error_next (tm, &next[0], &error0, is_ip4);
3311
3312           if (PREDICT_TRUE (tc1 != 0))
3313             {
3314               ASSERT (tcp_lookup_is_valid (tc1, tcp_buffer_hdr (b[1])));
3315               vnet_buffer (b[1])->tcp.connection_index = tc1->c_c_index;
3316               tcp_input_dispatch_buffer (tm, tc1, b[1], &next[1], &error1);
3317             }
3318           else
3319             tcp_input_set_error_next (tm, &next[1], &error1, is_ip4);
3320         }
3321
3322       b += 2;
3323       next += 2;
3324       n_left_from -= 2;
3325     }
3326   while (n_left_from > 0)
3327     {
3328       tcp_connection_t *tc0;
3329       u32 error0 = TCP_ERROR_NO_LISTENER;
3330
3331       if (n_left_from > 1)
3332         {
3333           vlib_prefetch_buffer_header (b[1], STORE);
3334           CLIB_PREFETCH (b[1]->data, 2 * CLIB_CACHE_LINE_BYTES, LOAD);
3335         }
3336
3337       next[0] = TCP_INPUT_NEXT_DROP;
3338       tc0 = tcp_input_lookup_buffer (b[0], thread_index, &error0, is_ip4);
3339       if (PREDICT_TRUE (tc0 != 0))
3340         {
3341           ASSERT (tcp_lookup_is_valid (tc0, tcp_buffer_hdr (b[0])));
3342           vnet_buffer (b[0])->tcp.connection_index = tc0->c_c_index;
3343           tcp_input_dispatch_buffer (tm, tc0, b[0], &next[0], &error0);
3344         }
3345       else
3346         tcp_input_set_error_next (tm, &next[0], &error0, is_ip4);
3347
3348       b += 1;
3349       next += 1;
3350       n_left_from -= 1;
3351     }
3352
3353   if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE))
3354     tcp_input_trace_frame (vm, node, bufs, frame->n_vectors, is_ip4);
3355
3356   vlib_buffer_enqueue_to_next (vm, node, from, nexts, frame->n_vectors);
3357   return frame->n_vectors;
3358 }
3359
3360 static uword
3361 tcp4_input (vlib_main_t * vm, vlib_node_runtime_t * node,
3362             vlib_frame_t * from_frame)
3363 {
3364   return tcp46_input_inline (vm, node, from_frame, 1 /* is_ip4 */ );
3365 }
3366
3367 static uword
3368 tcp6_input (vlib_main_t * vm, vlib_node_runtime_t * node,
3369             vlib_frame_t * from_frame)
3370 {
3371   return tcp46_input_inline (vm, node, from_frame, 0 /* is_ip4 */ );
3372 }
3373
3374 /* *INDENT-OFF* */
3375 VLIB_REGISTER_NODE (tcp4_input_node) =
3376 {
3377   .function = tcp4_input,
3378   .name = "tcp4-input",
3379   /* Takes a vector of packets. */
3380   .vector_size = sizeof (u32),
3381   .n_errors = TCP_N_ERROR,
3382   .error_strings = tcp_error_strings,
3383   .n_next_nodes = TCP_INPUT_N_NEXT,
3384   .next_nodes =
3385   {
3386 #define _(s,n) [TCP_INPUT_NEXT_##s] = n,
3387     foreach_tcp4_input_next
3388 #undef _
3389   },
3390   .format_buffer = format_tcp_header,
3391   .format_trace = format_tcp_rx_trace,
3392 };
3393 /* *INDENT-ON* */
3394
3395 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_input_node, tcp4_input);
3396
3397 /* *INDENT-OFF* */
3398 VLIB_REGISTER_NODE (tcp6_input_node) =
3399 {
3400   .function = tcp6_input,
3401   .name = "tcp6-input",
3402   /* Takes a vector of packets. */
3403   .vector_size = sizeof (u32),
3404   .n_errors = TCP_N_ERROR,
3405   .error_strings = tcp_error_strings,
3406   .n_next_nodes = TCP_INPUT_N_NEXT,
3407   .next_nodes =
3408   {
3409 #define _(s,n) [TCP_INPUT_NEXT_##s] = n,
3410     foreach_tcp6_input_next
3411 #undef _
3412   },
3413   .format_buffer = format_tcp_header,
3414   .format_trace = format_tcp_rx_trace,
3415 };
3416 /* *INDENT-ON* */
3417
3418 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_input_node, tcp6_input);
3419
3420 static void
3421 tcp_dispatch_table_init (tcp_main_t * tm)
3422 {
3423   int i, j;
3424   for (i = 0; i < ARRAY_LEN (tm->dispatch_table); i++)
3425     for (j = 0; j < ARRAY_LEN (tm->dispatch_table[i]); j++)
3426       {
3427         tm->dispatch_table[i][j].next = TCP_INPUT_NEXT_DROP;
3428         tm->dispatch_table[i][j].error = TCP_ERROR_DISPATCH;
3429       }
3430
3431 #define _(t,f,n,e)                                              \
3432 do {                                                            \
3433     tm->dispatch_table[TCP_STATE_##t][f].next = (n);            \
3434     tm->dispatch_table[TCP_STATE_##t][f].error = (e);           \
3435 } while (0)
3436
3437   /* SYNs for new connections -> tcp-listen. */
3438   _(LISTEN, TCP_FLAG_SYN, TCP_INPUT_NEXT_LISTEN, TCP_ERROR_NONE);
3439   _(LISTEN, TCP_FLAG_ACK, TCP_INPUT_NEXT_RESET, TCP_ERROR_NONE);
3440   _(LISTEN, TCP_FLAG_RST, TCP_INPUT_NEXT_DROP, TCP_ERROR_RST_RCVD);
3441   _(LISTEN, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RESET,
3442     TCP_ERROR_NONE);
3443   /* ACK for for a SYN-ACK -> tcp-rcv-process. */
3444   _(SYN_RCVD, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3445   _(SYN_RCVD, TCP_FLAG_RST, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3446   _(SYN_RCVD, TCP_FLAG_RST | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
3447     TCP_ERROR_NONE);
3448   _(SYN_RCVD, TCP_FLAG_SYN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3449   _(SYN_RCVD, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
3450     TCP_ERROR_NONE);
3451   /* SYN-ACK for a SYN */
3452   _(SYN_SENT, TCP_FLAG_SYN | TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT,
3453     TCP_ERROR_NONE);
3454   _(SYN_SENT, TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT, TCP_ERROR_NONE);
3455   _(SYN_SENT, TCP_FLAG_RST, TCP_INPUT_NEXT_SYN_SENT, TCP_ERROR_NONE);
3456   _(SYN_SENT, TCP_FLAG_RST | TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT,
3457     TCP_ERROR_NONE);
3458   /* ACK for for established connection -> tcp-established. */
3459   _(ESTABLISHED, TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
3460   /* FIN for for established connection -> tcp-established. */
3461   _(ESTABLISHED, TCP_FLAG_FIN, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
3462   _(ESTABLISHED, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED,
3463     TCP_ERROR_NONE);
3464   _(ESTABLISHED, TCP_FLAG_RST, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
3465   _(ESTABLISHED, TCP_FLAG_RST | TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED,
3466     TCP_ERROR_NONE);
3467   _(ESTABLISHED, TCP_FLAG_SYN, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
3468   _(ESTABLISHED, TCP_FLAG_SYN | TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED,
3469     TCP_ERROR_NONE);
3470   /* ACK or FIN-ACK to our FIN */
3471   _(FIN_WAIT_1, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3472   _(FIN_WAIT_1, TCP_FLAG_ACK | TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS,
3473     TCP_ERROR_NONE);
3474   /* FIN in reply to our FIN from the other side */
3475   _(FIN_WAIT_1, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3476   _(FIN_WAIT_1, TCP_FLAG_RST, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3477   _(CLOSING, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3478   /* FIN confirming that the peer (app) has closed */
3479   _(FIN_WAIT_2, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3480   _(FIN_WAIT_2, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3481   _(FIN_WAIT_2, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
3482     TCP_ERROR_NONE);
3483   _(CLOSE_WAIT, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3484   _(CLOSE_WAIT, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
3485     TCP_ERROR_NONE);
3486   _(LAST_ACK, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3487   _(LAST_ACK, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3488   _(LAST_ACK, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
3489     TCP_ERROR_NONE);
3490   _(LAST_ACK, TCP_FLAG_RST, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3491   _(TIME_WAIT, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3492   _(TIME_WAIT, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
3493     TCP_ERROR_NONE);
3494   _(TIME_WAIT, TCP_FLAG_RST, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3495   _(TIME_WAIT, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
3496   _(CLOSED, TCP_FLAG_ACK, TCP_INPUT_NEXT_DROP, TCP_ERROR_CONNECTION_CLOSED);
3497   _(CLOSED, TCP_FLAG_RST, TCP_INPUT_NEXT_DROP, TCP_ERROR_CONNECTION_CLOSED);
3498   _(CLOSED, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_DROP,
3499     TCP_ERROR_CONNECTION_CLOSED);
3500 #undef _
3501 }
3502
3503 static clib_error_t *
3504 tcp_input_init (vlib_main_t * vm)
3505 {
3506   clib_error_t *error = 0;
3507   tcp_main_t *tm = vnet_get_tcp_main ();
3508
3509   if ((error = vlib_call_init_function (vm, tcp_init)))
3510     return error;
3511
3512   /* Initialize dispatch table. */
3513   tcp_dispatch_table_init (tm);
3514
3515   return error;
3516 }
3517
3518 VLIB_INIT_FUNCTION (tcp_input_init);
3519
3520 /*
3521  * fd.io coding-style-patch-verification: ON
3522  *
3523  * Local Variables:
3524  * eval: (c-set-style "gnu")
3525  * End:
3526  */