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