d33cbdd4ad4d27903a2928010979401d99ac3d9d
[vpp.git] / src / vnet / tcp / tcp_output.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 <vnet/tcp/tcp.h>
17 #include <math.h>
18
19 typedef enum _tcp_output_next
20 {
21   TCP_OUTPUT_NEXT_DROP,
22   TCP_OUTPUT_NEXT_IP_LOOKUP,
23   TCP_OUTPUT_NEXT_IP_REWRITE,
24   TCP_OUTPUT_NEXT_IP_ARP,
25   TCP_OUTPUT_N_NEXT
26 } tcp_output_next_t;
27
28 #define foreach_tcp4_output_next                \
29   _ (DROP, "error-drop")                        \
30   _ (IP_LOOKUP, "ip4-lookup")                   \
31   _ (IP_REWRITE, "ip4-rewrite")                 \
32   _ (IP_ARP, "ip4-arp")
33
34 #define foreach_tcp6_output_next                \
35   _ (DROP, "error-drop")                        \
36   _ (IP_LOOKUP, "ip6-lookup")                   \
37   _ (IP_REWRITE, "ip6-rewrite")                 \
38   _ (IP_ARP, "ip6-discover-neighbor")
39
40 static char *tcp_error_strings[] = {
41 #define tcp_error(n,s) s,
42 #include <vnet/tcp/tcp_error.def>
43 #undef tcp_error
44 };
45
46 typedef struct
47 {
48   tcp_header_t tcp_header;
49   tcp_connection_t tcp_connection;
50 } tcp_tx_trace_t;
51
52 static u8 *
53 format_tcp_tx_trace (u8 * s, va_list * args)
54 {
55   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
56   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
57   tcp_tx_trace_t *t = va_arg (*args, tcp_tx_trace_t *);
58   tcp_connection_t *tc = &t->tcp_connection;
59   u32 indent = format_get_indent (s);
60
61   s = format (s, "%U state %U\n%U%U", format_tcp_connection_id, tc,
62               format_tcp_state, tc->state, format_white_space, indent,
63               format_tcp_header, &t->tcp_header, 128);
64
65   return s;
66 }
67
68 #ifndef CLIB_MARCH_VARIANT
69 static u8
70 tcp_window_compute_scale (u32 window)
71 {
72   u8 wnd_scale = 0;
73   while (wnd_scale < TCP_MAX_WND_SCALE && (window >> wnd_scale) > TCP_WND_MAX)
74     wnd_scale++;
75   return wnd_scale;
76 }
77
78 /**
79  * TCP's initial window
80  */
81 always_inline u32
82 tcp_initial_wnd_unscaled (tcp_connection_t * tc)
83 {
84   /* RFC 6928 recommends the value lower. However at the time our connections
85    * are initialized, fifos may not be allocated. Therefore, advertise the
86    * smallest possible unscaled window size and update once fifos are
87    * assigned to the session.
88    */
89   /*
90      tcp_update_rcv_mss (tc);
91      TCP_IW_N_SEGMENTS * tc->mss;
92    */
93   return tcp_cfg.min_rx_fifo;
94 }
95
96 /**
97  * Compute initial window and scale factor. As per RFC1323, window field in
98  * SYN and SYN-ACK segments is never scaled.
99  */
100 u32
101 tcp_initial_window_to_advertise (tcp_connection_t * tc)
102 {
103   /* Compute rcv wscale only if peer advertised support for it */
104   if (tc->state != TCP_STATE_SYN_RCVD || tcp_opts_wscale (&tc->rcv_opts))
105     tc->rcv_wscale = tcp_window_compute_scale (tcp_cfg.max_rx_fifo);
106
107   tc->rcv_wnd = tcp_initial_wnd_unscaled (tc);
108
109   return clib_min (tc->rcv_wnd, TCP_WND_MAX);
110 }
111
112 static inline void
113 tcp_update_rcv_wnd (tcp_connection_t * tc)
114 {
115   u32 available_space, wnd;
116   i32 observed_wnd;
117
118   ASSERT (tc->rcv_opts.mss < transport_rx_fifo_size (&tc->connection));
119
120   /*
121    * Figure out how much space we have available
122    */
123   available_space = transport_max_rx_enqueue (&tc->connection);
124   if (PREDICT_FALSE (available_space < tc->rcv_opts.mss))
125     {
126       tc->rcv_wnd = 0;
127       return;
128     }
129
130   /*
131    * Use the above and what we know about what we've previously advertised
132    * to compute the new window
133    */
134   observed_wnd = (i32) tc->rcv_wnd - (tc->rcv_nxt - tc->rcv_las);
135
136   /* Bad. Thou shalt not shrink */
137   if (PREDICT_FALSE ((i32) available_space < observed_wnd))
138     {
139       wnd = clib_max (observed_wnd, 0);
140       TCP_EVT (TCP_EVT_RCV_WND_SHRUNK, tc, observed_wnd, available_space);
141     }
142   else
143     {
144       wnd = available_space;
145     }
146
147   /* Make sure we have a multiple of rcv_wscale */
148   if (wnd && tc->rcv_wscale)
149     {
150       wnd &= ~((1 << tc->rcv_wscale) - 1);
151       if (wnd == 0)
152         wnd = 1 << tc->rcv_wscale;
153     }
154
155   tc->rcv_wnd = clib_min (wnd, TCP_WND_MAX << tc->rcv_wscale);
156 }
157
158 /**
159  * Compute and return window to advertise, scaled as per RFC1323
160  */
161 static inline u32
162 tcp_window_to_advertise (tcp_connection_t * tc, tcp_state_t state)
163 {
164   if (state < TCP_STATE_ESTABLISHED)
165     return tcp_initial_window_to_advertise (tc);
166
167   tcp_update_rcv_wnd (tc);
168   return tc->rcv_wnd >> tc->rcv_wscale;
169 }
170
171 /**
172  * Write TCP options to segment.
173  */
174 static u32
175 tcp_options_write (u8 * data, tcp_options_t * opts)
176 {
177   u32 opts_len = 0;
178   u32 buf, seq_len = 4;
179
180   if (tcp_opts_mss (opts))
181     {
182       *data++ = TCP_OPTION_MSS;
183       *data++ = TCP_OPTION_LEN_MSS;
184       buf = clib_host_to_net_u16 (opts->mss);
185       clib_memcpy_fast (data, &buf, sizeof (opts->mss));
186       data += sizeof (opts->mss);
187       opts_len += TCP_OPTION_LEN_MSS;
188     }
189
190   if (tcp_opts_wscale (opts))
191     {
192       *data++ = TCP_OPTION_WINDOW_SCALE;
193       *data++ = TCP_OPTION_LEN_WINDOW_SCALE;
194       *data++ = opts->wscale;
195       opts_len += TCP_OPTION_LEN_WINDOW_SCALE;
196     }
197
198   if (tcp_opts_sack_permitted (opts))
199     {
200       *data++ = TCP_OPTION_SACK_PERMITTED;
201       *data++ = TCP_OPTION_LEN_SACK_PERMITTED;
202       opts_len += TCP_OPTION_LEN_SACK_PERMITTED;
203     }
204
205   if (tcp_opts_tstamp (opts))
206     {
207       *data++ = TCP_OPTION_TIMESTAMP;
208       *data++ = TCP_OPTION_LEN_TIMESTAMP;
209       buf = clib_host_to_net_u32 (opts->tsval);
210       clib_memcpy_fast (data, &buf, sizeof (opts->tsval));
211       data += sizeof (opts->tsval);
212       buf = clib_host_to_net_u32 (opts->tsecr);
213       clib_memcpy_fast (data, &buf, sizeof (opts->tsecr));
214       data += sizeof (opts->tsecr);
215       opts_len += TCP_OPTION_LEN_TIMESTAMP;
216     }
217
218   if (tcp_opts_sack (opts))
219     {
220       int i;
221
222       if (opts->n_sack_blocks != 0)
223         {
224           *data++ = TCP_OPTION_SACK_BLOCK;
225           *data++ = 2 + opts->n_sack_blocks * TCP_OPTION_LEN_SACK_BLOCK;
226           for (i = 0; i < opts->n_sack_blocks; i++)
227             {
228               buf = clib_host_to_net_u32 (opts->sacks[i].start);
229               clib_memcpy_fast (data, &buf, seq_len);
230               data += seq_len;
231               buf = clib_host_to_net_u32 (opts->sacks[i].end);
232               clib_memcpy_fast (data, &buf, seq_len);
233               data += seq_len;
234             }
235           opts_len += 2 + opts->n_sack_blocks * TCP_OPTION_LEN_SACK_BLOCK;
236         }
237     }
238
239   /* Terminate TCP options */
240   if (opts_len % 4)
241     {
242       *data++ = TCP_OPTION_EOL;
243       opts_len += TCP_OPTION_LEN_EOL;
244     }
245
246   /* Pad with zeroes to a u32 boundary */
247   while (opts_len % 4)
248     {
249       *data++ = TCP_OPTION_NOOP;
250       opts_len += TCP_OPTION_LEN_NOOP;
251     }
252   return opts_len;
253 }
254
255 static int
256 tcp_make_syn_options (tcp_connection_t * tc, tcp_options_t * opts)
257 {
258   u8 len = 0;
259
260   opts->flags |= TCP_OPTS_FLAG_MSS;
261   opts->mss = tc->mss;
262   len += TCP_OPTION_LEN_MSS;
263
264   opts->flags |= TCP_OPTS_FLAG_WSCALE;
265   opts->wscale = tc->rcv_wscale;
266   len += TCP_OPTION_LEN_WINDOW_SCALE;
267
268   opts->flags |= TCP_OPTS_FLAG_TSTAMP;
269   opts->tsval = tcp_time_now ();
270   opts->tsecr = 0;
271   len += TCP_OPTION_LEN_TIMESTAMP;
272
273   if (TCP_USE_SACKS)
274     {
275       opts->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
276       len += TCP_OPTION_LEN_SACK_PERMITTED;
277     }
278
279   /* Align to needed boundary */
280   len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
281   return len;
282 }
283
284 static int
285 tcp_make_synack_options (tcp_connection_t * tc, tcp_options_t * opts)
286 {
287   u8 len = 0;
288
289   opts->flags |= TCP_OPTS_FLAG_MSS;
290   opts->mss = tc->mss;
291   len += TCP_OPTION_LEN_MSS;
292
293   if (tcp_opts_wscale (&tc->rcv_opts))
294     {
295       opts->flags |= TCP_OPTS_FLAG_WSCALE;
296       opts->wscale = tc->rcv_wscale;
297       len += TCP_OPTION_LEN_WINDOW_SCALE;
298     }
299
300   if (tcp_opts_tstamp (&tc->rcv_opts))
301     {
302       opts->flags |= TCP_OPTS_FLAG_TSTAMP;
303       opts->tsval = tcp_time_now ();
304       opts->tsecr = tc->tsval_recent;
305       len += TCP_OPTION_LEN_TIMESTAMP;
306     }
307
308   if (tcp_opts_sack_permitted (&tc->rcv_opts))
309     {
310       opts->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
311       len += TCP_OPTION_LEN_SACK_PERMITTED;
312     }
313
314   /* Align to needed boundary */
315   len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
316   return len;
317 }
318
319 static int
320 tcp_make_established_options (tcp_connection_t * tc, tcp_options_t * opts)
321 {
322   u8 len = 0;
323
324   opts->flags = 0;
325
326   if (tcp_opts_tstamp (&tc->rcv_opts))
327     {
328       opts->flags |= TCP_OPTS_FLAG_TSTAMP;
329       opts->tsval = tcp_tstamp (tc);
330       opts->tsecr = tc->tsval_recent;
331       len += TCP_OPTION_LEN_TIMESTAMP;
332     }
333   if (tcp_opts_sack_permitted (&tc->rcv_opts))
334     {
335       if (vec_len (tc->snd_sacks))
336         {
337           opts->flags |= TCP_OPTS_FLAG_SACK;
338           if (tc->snd_sack_pos >= vec_len (tc->snd_sacks))
339             tc->snd_sack_pos = 0;
340           opts->sacks = &tc->snd_sacks[tc->snd_sack_pos];
341           opts->n_sack_blocks = vec_len (tc->snd_sacks) - tc->snd_sack_pos;
342           opts->n_sack_blocks = clib_min (opts->n_sack_blocks,
343                                           TCP_OPTS_MAX_SACK_BLOCKS);
344           tc->snd_sack_pos += opts->n_sack_blocks;
345           len += 2 + TCP_OPTION_LEN_SACK_BLOCK * opts->n_sack_blocks;
346         }
347     }
348
349   /* Align to needed boundary */
350   len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
351   return len;
352 }
353
354 always_inline int
355 tcp_make_options (tcp_connection_t * tc, tcp_options_t * opts,
356                   tcp_state_t state)
357 {
358   switch (state)
359     {
360     case TCP_STATE_ESTABLISHED:
361     case TCP_STATE_CLOSE_WAIT:
362     case TCP_STATE_FIN_WAIT_1:
363     case TCP_STATE_LAST_ACK:
364     case TCP_STATE_CLOSING:
365     case TCP_STATE_FIN_WAIT_2:
366     case TCP_STATE_TIME_WAIT:
367     case TCP_STATE_CLOSED:
368       return tcp_make_established_options (tc, opts);
369     case TCP_STATE_SYN_RCVD:
370       return tcp_make_synack_options (tc, opts);
371     case TCP_STATE_SYN_SENT:
372       return tcp_make_syn_options (tc, opts);
373     default:
374       clib_warning ("State not handled! %d", state);
375       return 0;
376     }
377 }
378
379 /**
380  * Update burst send vars
381  *
382  * - Updates snd_mss to reflect the effective segment size that we can send
383  * by taking into account all TCP options, including SACKs.
384  * - Cache 'on the wire' options for reuse
385  * - Updates receive window which can be reused for a burst.
386  *
387  * This should *only* be called when doing bursts
388  */
389 void
390 tcp_update_burst_snd_vars (tcp_connection_t * tc)
391 {
392   tcp_main_t *tm = &tcp_main;
393
394   /* Compute options to be used for connection. These may be reused when
395    * sending data or to compute the effective mss (snd_mss) */
396   tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts,
397                                        TCP_STATE_ESTABLISHED);
398
399   /* XXX check if MTU has been updated */
400   tc->snd_mss = clib_min (tc->mss, tc->rcv_opts.mss) - tc->snd_opts_len;
401   ASSERT (tc->snd_mss > 0);
402
403   tcp_options_write (tm->wrk_ctx[tc->c_thread_index].cached_opts,
404                      &tc->snd_opts);
405
406   tcp_update_rcv_wnd (tc);
407
408   if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
409     tcp_bt_check_app_limited (tc);
410
411   if (tc->snd_una == tc->snd_nxt)
412     {
413       tcp_cc_event (tc, TCP_CC_EVT_START_TX);
414       tcp_connection_tx_pacer_reset (tc, tc->cwnd, TRANSPORT_PACER_MIN_BURST);
415     }
416 }
417
418 #endif /* CLIB_MARCH_VARIANT */
419
420 static void *
421 tcp_reuse_buffer (vlib_main_t * vm, vlib_buffer_t * b)
422 {
423   if (b->flags & VLIB_BUFFER_NEXT_PRESENT)
424     vlib_buffer_free_one (vm, b->next_buffer);
425   /* Zero all flags but free list index and trace flag */
426   b->flags &= VLIB_BUFFER_NEXT_PRESENT - 1;
427   b->current_data = 0;
428   b->current_length = 0;
429   b->total_length_not_including_first_buffer = 0;
430   vnet_buffer (b)->tcp.flags = 0;
431
432   /* Leave enough space for headers */
433   return vlib_buffer_make_headroom (b, TRANSPORT_MAX_HDRS_LEN);
434 }
435
436 #ifndef CLIB_MARCH_VARIANT
437 static void *
438 tcp_init_buffer (vlib_main_t * vm, vlib_buffer_t * b)
439 {
440   ASSERT ((b->flags & VLIB_BUFFER_NEXT_PRESENT) == 0);
441   b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
442   b->total_length_not_including_first_buffer = 0;
443   b->current_data = 0;
444   vnet_buffer (b)->tcp.flags = 0;
445   VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b);
446   /* Leave enough space for headers */
447   return vlib_buffer_make_headroom (b, TRANSPORT_MAX_HDRS_LEN);
448 }
449
450
451 /* Compute TCP checksum in software when offloading is disabled for a connection */
452 u16
453 ip6_tcp_compute_checksum_custom (vlib_main_t * vm, vlib_buffer_t * p0,
454                                  ip46_address_t * src, ip46_address_t * dst)
455 {
456   ip_csum_t sum0;
457   u16 payload_length_host_byte_order;
458   u32 i;
459
460   /* Initialize checksum with ip header. */
461   sum0 = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, p0)) +
462     clib_host_to_net_u16 (IP_PROTOCOL_TCP);
463   payload_length_host_byte_order = vlib_buffer_length_in_chain (vm, p0);
464
465   for (i = 0; i < ARRAY_LEN (src->ip6.as_uword); i++)
466     {
467       sum0 = ip_csum_with_carry
468         (sum0, clib_mem_unaligned (&src->ip6.as_uword[i], uword));
469       sum0 = ip_csum_with_carry
470         (sum0, clib_mem_unaligned (&dst->ip6.as_uword[i], uword));
471     }
472
473   return ip_calculate_l4_checksum (vm, p0, sum0,
474                                    payload_length_host_byte_order, NULL, 0,
475                                    NULL);
476 }
477
478 u16
479 ip4_tcp_compute_checksum_custom (vlib_main_t * vm, vlib_buffer_t * p0,
480                                  ip46_address_t * src, ip46_address_t * dst)
481 {
482   ip_csum_t sum0;
483   u32 payload_length_host_byte_order;
484
485   payload_length_host_byte_order = vlib_buffer_length_in_chain (vm, p0);
486   sum0 =
487     clib_host_to_net_u32 (payload_length_host_byte_order +
488                           (IP_PROTOCOL_TCP << 16));
489
490   sum0 = ip_csum_with_carry (sum0, clib_mem_unaligned (&src->ip4, u32));
491   sum0 = ip_csum_with_carry (sum0, clib_mem_unaligned (&dst->ip4, u32));
492
493   return ip_calculate_l4_checksum (vm, p0, sum0,
494                                    payload_length_host_byte_order, NULL, 0,
495                                    NULL);
496 }
497
498 static inline u16
499 tcp_compute_checksum (tcp_connection_t * tc, vlib_buffer_t * b)
500 {
501   u16 checksum = 0;
502   if (PREDICT_FALSE (tc->cfg_flags & TCP_CFG_F_NO_CSUM_OFFLOAD))
503     {
504       tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
505       vlib_main_t *vm = wrk->vm;
506
507       if (tc->c_is_ip4)
508         checksum = ip4_tcp_compute_checksum_custom
509           (vm, b, &tc->c_lcl_ip, &tc->c_rmt_ip);
510       else
511         checksum = ip6_tcp_compute_checksum_custom
512           (vm, b, &tc->c_lcl_ip, &tc->c_rmt_ip);
513     }
514   else
515     {
516       b->flags |= VNET_BUFFER_F_OFFLOAD_TCP_CKSUM;
517     }
518   return checksum;
519 }
520
521 /**
522  * Prepare ACK
523  */
524 static inline void
525 tcp_make_ack_i (tcp_connection_t * tc, vlib_buffer_t * b, tcp_state_t state,
526                 u8 flags)
527 {
528   tcp_options_t _snd_opts, *snd_opts = &_snd_opts;
529   u8 tcp_opts_len, tcp_hdr_opts_len;
530   tcp_header_t *th;
531   u16 wnd;
532
533   wnd = tcp_window_to_advertise (tc, state);
534
535   /* Make and write options */
536   tcp_opts_len = tcp_make_established_options (tc, snd_opts);
537   tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
538
539   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->snd_nxt,
540                              tc->rcv_nxt, tcp_hdr_opts_len, flags, wnd);
541
542   tcp_options_write ((u8 *) (th + 1), snd_opts);
543
544   th->checksum = tcp_compute_checksum (tc, b);
545
546   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
547
548   if (wnd == 0)
549     tcp_zero_rwnd_sent_on (tc);
550   else
551     tcp_zero_rwnd_sent_off (tc);
552 }
553
554 /**
555  * Convert buffer to ACK
556  */
557 static inline void
558 tcp_make_ack (tcp_connection_t * tc, vlib_buffer_t * b)
559 {
560   tcp_make_ack_i (tc, b, TCP_STATE_ESTABLISHED, TCP_FLAG_ACK);
561   TCP_EVT (TCP_EVT_ACK_SENT, tc);
562   tc->rcv_las = tc->rcv_nxt;
563 }
564
565 /**
566  * Convert buffer to FIN-ACK
567  */
568 void
569 tcp_make_fin (tcp_connection_t * tc, vlib_buffer_t * b)
570 {
571   tcp_make_ack_i (tc, b, TCP_STATE_ESTABLISHED, TCP_FLAG_FIN | TCP_FLAG_ACK);
572 }
573
574 /**
575  * Convert buffer to SYN
576  */
577 void
578 tcp_make_syn (tcp_connection_t * tc, vlib_buffer_t * b)
579 {
580   u8 tcp_hdr_opts_len, tcp_opts_len;
581   tcp_header_t *th;
582   u16 initial_wnd;
583   tcp_options_t snd_opts;
584
585   initial_wnd = tcp_initial_window_to_advertise (tc);
586
587   /* Make and write options */
588   clib_memset (&snd_opts, 0, sizeof (snd_opts));
589   tcp_opts_len = tcp_make_syn_options (tc, &snd_opts);
590   tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
591
592   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->iss,
593                              tc->rcv_nxt, tcp_hdr_opts_len, TCP_FLAG_SYN,
594                              initial_wnd);
595   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
596   tcp_options_write ((u8 *) (th + 1), &snd_opts);
597   th->checksum = tcp_compute_checksum (tc, b);
598 }
599
600 /**
601  * Convert buffer to SYN-ACK
602  */
603 void
604 tcp_make_synack (tcp_connection_t * tc, vlib_buffer_t * b)
605 {
606   tcp_options_t _snd_opts, *snd_opts = &_snd_opts;
607   u8 tcp_opts_len, tcp_hdr_opts_len;
608   tcp_header_t *th;
609   u16 initial_wnd;
610
611   clib_memset (snd_opts, 0, sizeof (*snd_opts));
612   initial_wnd = tcp_initial_window_to_advertise (tc);
613   tcp_opts_len = tcp_make_synack_options (tc, snd_opts);
614   tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
615
616   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->iss,
617                              tc->rcv_nxt, tcp_hdr_opts_len,
618                              TCP_FLAG_SYN | TCP_FLAG_ACK, initial_wnd);
619   tcp_options_write ((u8 *) (th + 1), snd_opts);
620
621   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
622   th->checksum = tcp_compute_checksum (tc, b);
623 }
624
625 always_inline void
626 tcp_enqueue_to_ip_lookup_i (tcp_worker_ctx_t * wrk, vlib_buffer_t * b, u32 bi,
627                             u8 is_ip4, u32 fib_index, u8 flush)
628 {
629   vlib_main_t *vm = wrk->vm;
630   u32 *to_next, next_index;
631   vlib_frame_t *f;
632
633   b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
634   b->error = 0;
635
636   vnet_buffer (b)->sw_if_index[VLIB_TX] = fib_index;
637   vnet_buffer (b)->sw_if_index[VLIB_RX] = 0;
638
639   /* Send to IP lookup */
640   next_index = is_ip4 ? ip4_lookup_node.index : ip6_lookup_node.index;
641   tcp_trajectory_add_start (b, 1);
642
643   f = wrk->ip_lookup_tx_frames[!is_ip4];
644   if (!f)
645     {
646       f = vlib_get_frame_to_node (vm, next_index);
647       ASSERT (f);
648       wrk->ip_lookup_tx_frames[!is_ip4] = f;
649     }
650
651   to_next = vlib_frame_vector_args (f);
652   to_next[f->n_vectors] = bi;
653   f->n_vectors += 1;
654   if (flush || f->n_vectors == VLIB_FRAME_SIZE)
655     {
656       vlib_put_frame_to_node (vm, next_index, f);
657       wrk->ip_lookup_tx_frames[!is_ip4] = 0;
658     }
659 }
660
661 static void
662 tcp_enqueue_to_ip_lookup_now (tcp_worker_ctx_t * wrk, vlib_buffer_t * b,
663                               u32 bi, u8 is_ip4, u32 fib_index)
664 {
665   tcp_enqueue_to_ip_lookup_i (wrk, b, bi, is_ip4, fib_index, 1);
666 }
667
668 static void
669 tcp_enqueue_to_ip_lookup (tcp_worker_ctx_t * wrk, vlib_buffer_t * b, u32 bi,
670                           u8 is_ip4, u32 fib_index)
671 {
672   tcp_enqueue_to_ip_lookup_i (wrk, b, bi, is_ip4, fib_index, 0);
673   if (wrk->vm->thread_index == 0 && vlib_num_workers ())
674     session_flush_frames_main_thread (wrk->vm);
675 }
676
677 static void
678 tcp_enqueue_to_output (tcp_worker_ctx_t * wrk, vlib_buffer_t * b, u32 bi,
679                        u8 is_ip4)
680 {
681   session_type_t st;
682
683   b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
684   b->error = 0;
685
686   st = session_type_from_proto_and_ip (TRANSPORT_PROTO_TCP, is_ip4);
687   session_add_pending_tx_buffer (st, wrk->vm->thread_index, bi);
688 }
689
690 #endif /* CLIB_MARCH_VARIANT */
691
692 static int
693 tcp_make_reset_in_place (vlib_main_t * vm, vlib_buffer_t * b, u8 is_ip4)
694 {
695   ip4_header_t *ih4;
696   ip6_header_t *ih6;
697   tcp_header_t *th;
698   ip4_address_t src_ip4, dst_ip4;
699   ip6_address_t src_ip6, dst_ip6;
700   u16 src_port, dst_port;
701   u32 tmp, len, seq, ack;
702   u8 flags;
703
704   /* Find IP and TCP headers */
705   th = tcp_buffer_hdr (b);
706
707   /* Save src and dst ip */
708   if (is_ip4)
709     {
710       ih4 = vlib_buffer_get_current (b);
711       ASSERT ((ih4->ip_version_and_header_length & 0xF0) == 0x40);
712       src_ip4.as_u32 = ih4->src_address.as_u32;
713       dst_ip4.as_u32 = ih4->dst_address.as_u32;
714     }
715   else
716     {
717       ih6 = vlib_buffer_get_current (b);
718       ASSERT ((ih6->ip_version_traffic_class_and_flow_label & 0xF0) == 0x60);
719       clib_memcpy_fast (&src_ip6, &ih6->src_address, sizeof (ip6_address_t));
720       clib_memcpy_fast (&dst_ip6, &ih6->dst_address, sizeof (ip6_address_t));
721     }
722
723   src_port = th->src_port;
724   dst_port = th->dst_port;
725   flags = TCP_FLAG_RST;
726
727   /*
728    * RFC 793. If the ACK bit is off, sequence number zero is used,
729    *   <SEQ=0><ACK=SEG.SEQ+SEG.LEN><CTL=RST,ACK>
730    * If the ACK bit is on,
731    *   <SEQ=SEG.ACK><CTL=RST>
732    */
733   if (tcp_ack (th))
734     {
735       seq = th->ack_number;
736       ack = 0;
737     }
738   else
739     {
740       flags |= TCP_FLAG_ACK;
741       tmp = clib_net_to_host_u32 (th->seq_number);
742       len = vnet_buffer (b)->tcp.data_len + tcp_is_syn (th) + tcp_is_fin (th);
743       ack = clib_host_to_net_u32 (tmp + len);
744       seq = 0;
745     }
746
747   tcp_reuse_buffer (vm, b);
748   tcp_trajectory_add_start (b, 4);
749   th = vlib_buffer_push_tcp_net_order (b, dst_port, src_port, seq, ack,
750                                        sizeof (tcp_header_t), flags, 0);
751
752   if (is_ip4)
753     {
754       ih4 = vlib_buffer_push_ip4 (vm, b, &dst_ip4, &src_ip4,
755                                   IP_PROTOCOL_TCP, 1);
756       th->checksum = ip4_tcp_udp_compute_checksum (vm, b, ih4);
757     }
758   else
759     {
760       int bogus = ~0;
761       ih6 = vlib_buffer_push_ip6 (vm, b, &dst_ip6, &src_ip6, IP_PROTOCOL_TCP);
762       th->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b, ih6, &bogus);
763       ASSERT (!bogus);
764     }
765
766   return 0;
767 }
768
769 #ifndef CLIB_MARCH_VARIANT
770 /**
771  *  Send reset without reusing existing buffer
772  *
773  *  It extracts connection info out of original packet
774  */
775 void
776 tcp_send_reset_w_pkt (tcp_connection_t * tc, vlib_buffer_t * pkt,
777                       u32 thread_index, u8 is_ip4)
778 {
779   tcp_worker_ctx_t *wrk = tcp_get_worker (thread_index);
780   vlib_main_t *vm = wrk->vm;
781   vlib_buffer_t *b;
782   u32 bi, sw_if_index, fib_index;
783   u8 tcp_hdr_len, flags = 0;
784   tcp_header_t *th, *pkt_th;
785   u32 seq, ack;
786   ip4_header_t *ih4, *pkt_ih4;
787   ip6_header_t *ih6, *pkt_ih6;
788   fib_protocol_t fib_proto;
789
790   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
791     return;
792
793   b = vlib_get_buffer (vm, bi);
794   sw_if_index = vnet_buffer (pkt)->sw_if_index[VLIB_RX];
795   fib_proto = is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
796   fib_index = fib_table_get_index_for_sw_if_index (fib_proto, sw_if_index);
797   tcp_init_buffer (vm, b);
798
799   /* Make and write options */
800   tcp_hdr_len = sizeof (tcp_header_t);
801
802   if (is_ip4)
803     {
804       pkt_ih4 = vlib_buffer_get_current (pkt);
805       pkt_th = ip4_next_header (pkt_ih4);
806     }
807   else
808     {
809       pkt_ih6 = vlib_buffer_get_current (pkt);
810       pkt_th = ip6_next_header (pkt_ih6);
811     }
812
813   if (tcp_ack (pkt_th))
814     {
815       flags = TCP_FLAG_RST;
816       seq = pkt_th->ack_number;
817       ack = (tc->state >= TCP_STATE_SYN_RCVD) ? tc->rcv_nxt : 0;
818     }
819   else
820     {
821       flags = TCP_FLAG_RST | TCP_FLAG_ACK;
822       seq = 0;
823       ack = clib_host_to_net_u32 (vnet_buffer (pkt)->tcp.seq_end);
824     }
825
826   th = vlib_buffer_push_tcp_net_order (b, pkt_th->dst_port, pkt_th->src_port,
827                                        seq, ack, tcp_hdr_len, flags, 0);
828
829   /* Swap src and dst ip */
830   if (is_ip4)
831     {
832       ASSERT ((pkt_ih4->ip_version_and_header_length & 0xF0) == 0x40);
833       ih4 = vlib_buffer_push_ip4 (vm, b, &pkt_ih4->dst_address,
834                                   &pkt_ih4->src_address, IP_PROTOCOL_TCP,
835                                   tcp_csum_offload (tc));
836       th->checksum = ip4_tcp_udp_compute_checksum (vm, b, ih4);
837     }
838   else
839     {
840       int bogus = ~0;
841       ASSERT ((pkt_ih6->ip_version_traffic_class_and_flow_label & 0xF0) ==
842               0x60);
843       ih6 = vlib_buffer_push_ip6_custom (vm, b, &pkt_ih6->dst_address,
844                                          &pkt_ih6->src_address,
845                                          IP_PROTOCOL_TCP,
846                                          tc->ipv6_flow_label);
847       th->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b, ih6, &bogus);
848       ASSERT (!bogus);
849     }
850
851   tcp_enqueue_to_ip_lookup_now (wrk, b, bi, is_ip4, fib_index);
852   TCP_EVT (TCP_EVT_RST_SENT, tc);
853   vlib_node_increment_counter (vm, tcp_node_index (output, tc->c_is_ip4),
854                                TCP_ERROR_RST_SENT, 1);
855 }
856
857 /**
858  * Build and set reset packet for connection
859  */
860 void
861 tcp_send_reset (tcp_connection_t * tc)
862 {
863   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
864   vlib_main_t *vm = wrk->vm;
865   vlib_buffer_t *b;
866   u32 bi;
867   tcp_header_t *th;
868   u16 tcp_hdr_opts_len, advertise_wnd, opts_write_len;
869   u8 flags;
870
871   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
872     return;
873   b = vlib_get_buffer (vm, bi);
874   tcp_init_buffer (vm, b);
875
876   tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts, tc->state);
877   tcp_hdr_opts_len = tc->snd_opts_len + sizeof (tcp_header_t);
878   advertise_wnd = tcp_window_to_advertise (tc, TCP_STATE_ESTABLISHED);
879   flags = TCP_FLAG_RST;
880   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->snd_nxt,
881                              tc->rcv_nxt, tcp_hdr_opts_len, flags,
882                              advertise_wnd);
883   opts_write_len = tcp_options_write ((u8 *) (th + 1), &tc->snd_opts);
884   th->checksum = tcp_compute_checksum (tc, b);
885   ASSERT (opts_write_len == tc->snd_opts_len);
886   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
887   tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
888   TCP_EVT (TCP_EVT_RST_SENT, tc);
889   vlib_node_increment_counter (vm, tcp_node_index (output, tc->c_is_ip4),
890                                TCP_ERROR_RST_SENT, 1);
891 }
892
893 static void
894 tcp_push_ip_hdr (tcp_worker_ctx_t * wrk, tcp_connection_t * tc,
895                  vlib_buffer_t * b)
896 {
897   if (tc->c_is_ip4)
898     {
899       vlib_buffer_push_ip4 (wrk->vm, b, &tc->c_lcl_ip4, &tc->c_rmt_ip4,
900                             IP_PROTOCOL_TCP, tcp_csum_offload (tc));
901     }
902   else
903     {
904       vlib_buffer_push_ip6_custom (wrk->vm, b, &tc->c_lcl_ip6, &tc->c_rmt_ip6,
905                                    IP_PROTOCOL_TCP, tc->ipv6_flow_label);
906     }
907 }
908
909 /**
910  *  Send SYN
911  *
912  *  Builds a SYN packet for a half-open connection and sends it to ipx_lookup.
913  *  The packet is not forwarded through tcpx_output to avoid doing lookups
914  *  in the half_open pool.
915  */
916 void
917 tcp_send_syn (tcp_connection_t * tc)
918 {
919   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
920   vlib_main_t *vm = wrk->vm;
921   vlib_buffer_t *b;
922   u32 bi;
923
924   /*
925    * Setup retransmit and establish timers before requesting buffer
926    * such that we can return if we've ran out.
927    */
928   tcp_timer_update (tc, TCP_TIMER_RETRANSMIT_SYN,
929                     tc->rto * TCP_TO_TIMER_TICK);
930
931   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
932     {
933       tcp_timer_update (tc, TCP_TIMER_RETRANSMIT_SYN, 1);
934       return;
935     }
936
937   b = vlib_get_buffer (vm, bi);
938   tcp_init_buffer (vm, b);
939   tcp_make_syn (tc, b);
940
941   /* Measure RTT with this */
942   tc->rtt_ts = tcp_time_now_us (vlib_num_workers ()? 1 : 0);
943   tc->rtt_seq = tc->snd_nxt;
944   tc->rto_boff = 0;
945
946   tcp_push_ip_hdr (wrk, tc, b);
947   tcp_enqueue_to_ip_lookup (wrk, b, bi, tc->c_is_ip4, tc->c_fib_index);
948   TCP_EVT (TCP_EVT_SYN_SENT, tc);
949 }
950
951 void
952 tcp_send_synack (tcp_connection_t * tc)
953 {
954   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
955   vlib_main_t *vm = wrk->vm;
956   vlib_buffer_t *b;
957   u32 bi;
958
959   tcp_retransmit_timer_force_update (tc);
960
961   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
962     {
963       tcp_timer_update (tc, TCP_TIMER_RETRANSMIT, 1);
964       return;
965     }
966
967   tc->rtt_ts = tcp_time_now_us (tc->c_thread_index);
968   b = vlib_get_buffer (vm, bi);
969   tcp_init_buffer (vm, b);
970   tcp_make_synack (tc, b);
971   tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
972   TCP_EVT (TCP_EVT_SYNACK_SENT, tc);
973 }
974
975 /**
976  *  Send FIN
977  */
978 void
979 tcp_send_fin (tcp_connection_t * tc)
980 {
981   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
982   vlib_main_t *vm = wrk->vm;
983   vlib_buffer_t *b;
984   u32 bi;
985   u8 fin_snt = 0;
986
987   fin_snt = tc->flags & TCP_CONN_FINSNT;
988   if (fin_snt)
989     tc->snd_nxt -= 1;
990
991   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
992     {
993       /* Out of buffers so program fin retransmit ASAP */
994       tcp_timer_update (tc, TCP_TIMER_RETRANSMIT, 1);
995       if (fin_snt)
996         tc->snd_nxt += 1;
997       else
998         /* Make sure retransmit retries a fin not data */
999         tc->flags |= TCP_CONN_FINSNT;
1000       return;
1001     }
1002
1003   /* If we have non-dupacks programmed, no need to send them */
1004   if ((tc->flags & TCP_CONN_SNDACK) && !tc->pending_dupacks)
1005     tc->flags &= ~TCP_CONN_SNDACK;
1006
1007   tcp_retransmit_timer_force_update (tc);
1008   b = vlib_get_buffer (vm, bi);
1009   tcp_init_buffer (vm, b);
1010   tcp_make_fin (tc, b);
1011   tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1012   TCP_EVT (TCP_EVT_FIN_SENT, tc);
1013   /* Account for the FIN */
1014   tc->snd_nxt += 1;
1015   if (!fin_snt)
1016     {
1017       tc->flags |= TCP_CONN_FINSNT;
1018       tc->flags &= ~TCP_CONN_FINPNDG;
1019       tc->snd_una_max = seq_max (tc->snd_una_max, tc->snd_nxt);
1020     }
1021 }
1022
1023 /**
1024  * Push TCP header and update connection variables. Should only be called
1025  * for segments with data, not for 'control' packets.
1026  */
1027 always_inline void
1028 tcp_push_hdr_i (tcp_connection_t * tc, vlib_buffer_t * b, u32 snd_nxt,
1029                 u8 compute_opts, u8 maybe_burst, u8 update_snd_nxt)
1030 {
1031   u8 tcp_hdr_opts_len, flags = TCP_FLAG_ACK;
1032   u32 advertise_wnd, data_len;
1033   tcp_main_t *tm = &tcp_main;
1034   tcp_header_t *th;
1035
1036   data_len = b->current_length;
1037   if (PREDICT_FALSE (b->flags & VLIB_BUFFER_NEXT_PRESENT))
1038     data_len += b->total_length_not_including_first_buffer;
1039
1040   vnet_buffer (b)->tcp.flags = 0;
1041   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
1042
1043   if (compute_opts)
1044     tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts, tc->state);
1045
1046   tcp_hdr_opts_len = tc->snd_opts_len + sizeof (tcp_header_t);
1047
1048   if (maybe_burst)
1049     advertise_wnd = tc->rcv_wnd >> tc->rcv_wscale;
1050   else
1051     advertise_wnd = tcp_window_to_advertise (tc, TCP_STATE_ESTABLISHED);
1052
1053   if (PREDICT_FALSE (tc->flags & TCP_CONN_PSH_PENDING))
1054     {
1055       if (seq_geq (tc->psh_seq, snd_nxt)
1056           && seq_lt (tc->psh_seq, snd_nxt + data_len))
1057         flags |= TCP_FLAG_PSH;
1058     }
1059   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, snd_nxt,
1060                              tc->rcv_nxt, tcp_hdr_opts_len, flags,
1061                              advertise_wnd);
1062
1063   if (maybe_burst)
1064     {
1065       clib_memcpy_fast ((u8 *) (th + 1),
1066                         tm->wrk_ctx[tc->c_thread_index].cached_opts,
1067                         tc->snd_opts_len);
1068     }
1069   else
1070     {
1071       u8 len = tcp_options_write ((u8 *) (th + 1), &tc->snd_opts);
1072       ASSERT (len == tc->snd_opts_len);
1073     }
1074
1075   /*
1076    * Update connection variables
1077    */
1078
1079   if (update_snd_nxt)
1080     tc->snd_nxt += data_len;
1081   tc->rcv_las = tc->rcv_nxt;
1082
1083   tc->bytes_out += data_len;
1084   tc->data_segs_out += 1;
1085
1086   th->checksum = tcp_compute_checksum (tc, b);
1087
1088   TCP_EVT (TCP_EVT_PKTIZE, tc);
1089 }
1090
1091 always_inline u32
1092 tcp_buffer_len (vlib_buffer_t * b)
1093 {
1094   u32 data_len = b->current_length;
1095   if (PREDICT_FALSE (b->flags & VLIB_BUFFER_NEXT_PRESENT))
1096     data_len += b->total_length_not_including_first_buffer;
1097   return data_len;
1098 }
1099
1100 u32
1101 tcp_session_push_header (transport_connection_t * tconn, vlib_buffer_t * b)
1102 {
1103   tcp_connection_t *tc = (tcp_connection_t *) tconn;
1104
1105   if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
1106     tcp_bt_track_tx (tc, tcp_buffer_len (b));
1107
1108   tcp_push_hdr_i (tc, b, tc->snd_nxt, /* compute opts */ 0, /* burst */ 1,
1109                   /* update_snd_nxt */ 1);
1110
1111   tc->snd_una_max = seq_max (tc->snd_nxt, tc->snd_una_max);
1112   tcp_validate_txf_size (tc, tc->snd_una_max - tc->snd_una);
1113   /* If not tracking an ACK, start tracking */
1114   if (tc->rtt_ts == 0 && !tcp_in_cong_recovery (tc))
1115     {
1116       tc->rtt_ts = tcp_time_now_us (tc->c_thread_index);
1117       tc->rtt_seq = tc->snd_nxt;
1118     }
1119   if (PREDICT_FALSE (!tcp_timer_is_active (tc, TCP_TIMER_RETRANSMIT)))
1120     {
1121       tcp_retransmit_timer_set (tc);
1122       tc->rto_boff = 0;
1123     }
1124   tcp_trajectory_add_start (b, 3);
1125   return 0;
1126 }
1127
1128 void
1129 tcp_send_ack (tcp_connection_t * tc)
1130 {
1131   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
1132   vlib_main_t *vm = wrk->vm;
1133   vlib_buffer_t *b;
1134   u32 bi;
1135
1136   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
1137     {
1138       tcp_update_rcv_wnd (tc);
1139       return;
1140     }
1141   b = vlib_get_buffer (vm, bi);
1142   tcp_init_buffer (vm, b);
1143   tcp_make_ack (tc, b);
1144   tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1145 }
1146
1147 void
1148 tcp_program_ack (tcp_connection_t * tc)
1149 {
1150   if (!(tc->flags & TCP_CONN_SNDACK))
1151     {
1152       session_add_self_custom_tx_evt (&tc->connection, 1);
1153       tc->flags |= TCP_CONN_SNDACK;
1154     }
1155 }
1156
1157 void
1158 tcp_program_dupack (tcp_connection_t * tc)
1159 {
1160   if (!(tc->flags & TCP_CONN_SNDACK))
1161     {
1162       session_add_self_custom_tx_evt (&tc->connection, 1);
1163       tc->flags |= TCP_CONN_SNDACK;
1164     }
1165   if (tc->pending_dupacks < 255)
1166     tc->pending_dupacks += 1;
1167 }
1168
1169 void
1170 tcp_program_retransmit (tcp_connection_t * tc)
1171 {
1172   if (!(tc->flags & TCP_CONN_RXT_PENDING))
1173     {
1174       session_add_self_custom_tx_evt (&tc->connection, 0);
1175       tc->flags |= TCP_CONN_RXT_PENDING;
1176     }
1177 }
1178
1179 /**
1180  * Delayed ack timer handler
1181  *
1182  * Sends delayed ACK when timer expires
1183  */
1184 void
1185 tcp_timer_delack_handler (tcp_connection_t * tc)
1186 {
1187   tcp_send_ack (tc);
1188 }
1189
1190 /**
1191  * Send window update ack
1192  *
1193  * Ensures that it will be sent only once, after a zero rwnd has been
1194  * advertised in a previous ack, and only if rwnd has grown beyond a
1195  * configurable value.
1196  */
1197 void
1198 tcp_send_window_update_ack (tcp_connection_t * tc)
1199 {
1200   if (tcp_zero_rwnd_sent (tc))
1201     {
1202       tcp_update_rcv_wnd (tc);
1203       if (tc->rcv_wnd >= tcp_cfg.rwnd_min_update_ack * tc->snd_mss)
1204         {
1205           tcp_zero_rwnd_sent_off (tc);
1206           tcp_program_ack (tc);
1207         }
1208     }
1209 }
1210
1211 /**
1212  * Allocate a new buffer and build a new tcp segment
1213  *
1214  * @param wrk           tcp worker
1215  * @param tc            connection for which the segment will be allocated
1216  * @param offset        offset of the first byte in the tx fifo
1217  * @param max_deq_byte  segment size
1218  * @param[out] b        pointer to buffer allocated
1219  *
1220  * @return      the number of bytes in the segment or 0 if buffer cannot be
1221  *              allocated or no data available
1222  */
1223 static int
1224 tcp_prepare_segment (tcp_worker_ctx_t * wrk, tcp_connection_t * tc,
1225                      u32 offset, u32 max_deq_bytes, vlib_buffer_t ** b)
1226 {
1227   u32 bytes_per_buffer = vnet_get_tcp_main ()->bytes_per_buffer;
1228   vlib_main_t *vm = wrk->vm;
1229   u32 bi, seg_size;
1230   int n_bytes = 0;
1231   u8 *data;
1232
1233   seg_size = max_deq_bytes + TRANSPORT_MAX_HDRS_LEN;
1234
1235   /*
1236    * Prepare options
1237    */
1238   tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts, tc->state);
1239
1240   /*
1241    * Allocate and fill in buffer(s)
1242    */
1243
1244   /* Easy case, buffer size greater than mss */
1245   if (PREDICT_TRUE (seg_size <= bytes_per_buffer))
1246     {
1247       if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
1248         return 0;
1249       *b = vlib_get_buffer (vm, bi);
1250       data = tcp_init_buffer (vm, *b);
1251       n_bytes = session_tx_fifo_peek_bytes (&tc->connection, data, offset,
1252                                             max_deq_bytes);
1253       ASSERT (n_bytes == max_deq_bytes);
1254       b[0]->current_length = n_bytes;
1255       tcp_push_hdr_i (tc, *b, tc->snd_una + offset, /* compute opts */ 0,
1256                       /* burst */ 0, /* update_snd_nxt */ 0);
1257     }
1258   /* Split mss into multiple buffers */
1259   else
1260     {
1261       u32 chain_bi = ~0, n_bufs_per_seg, n_bufs;
1262       u16 n_peeked, len_to_deq;
1263       vlib_buffer_t *chain_b, *prev_b;
1264       int i;
1265
1266       /* Make sure we have enough buffers */
1267       n_bufs_per_seg = ceil ((double) seg_size / bytes_per_buffer);
1268       vec_validate_aligned (wrk->tx_buffers, n_bufs_per_seg - 1,
1269                             CLIB_CACHE_LINE_BYTES);
1270       n_bufs = vlib_buffer_alloc (vm, wrk->tx_buffers, n_bufs_per_seg);
1271       if (PREDICT_FALSE (n_bufs != n_bufs_per_seg))
1272         {
1273           if (n_bufs)
1274             vlib_buffer_free (vm, wrk->tx_buffers, n_bufs);
1275           return 0;
1276         }
1277
1278       *b = vlib_get_buffer (vm, wrk->tx_buffers[--n_bufs]);
1279       data = tcp_init_buffer (vm, *b);
1280       n_bytes = session_tx_fifo_peek_bytes (&tc->connection, data, offset,
1281                                             bytes_per_buffer -
1282                                             TRANSPORT_MAX_HDRS_LEN);
1283       b[0]->current_length = n_bytes;
1284       b[0]->flags |= VLIB_BUFFER_TOTAL_LENGTH_VALID;
1285       b[0]->total_length_not_including_first_buffer = 0;
1286       max_deq_bytes -= n_bytes;
1287
1288       chain_b = *b;
1289       for (i = 1; i < n_bufs_per_seg; i++)
1290         {
1291           prev_b = chain_b;
1292           len_to_deq = clib_min (max_deq_bytes, bytes_per_buffer);
1293           chain_bi = wrk->tx_buffers[--n_bufs];
1294           chain_b = vlib_get_buffer (vm, chain_bi);
1295           chain_b->current_data = 0;
1296           data = vlib_buffer_get_current (chain_b);
1297           n_peeked = session_tx_fifo_peek_bytes (&tc->connection, data,
1298                                                  offset + n_bytes,
1299                                                  len_to_deq);
1300           ASSERT (n_peeked == len_to_deq);
1301           n_bytes += n_peeked;
1302           chain_b->current_length = n_peeked;
1303           chain_b->next_buffer = 0;
1304
1305           /* update previous buffer */
1306           prev_b->next_buffer = chain_bi;
1307           prev_b->flags |= VLIB_BUFFER_NEXT_PRESENT;
1308
1309           max_deq_bytes -= n_peeked;
1310           b[0]->total_length_not_including_first_buffer += n_peeked;
1311         }
1312
1313       tcp_push_hdr_i (tc, *b, tc->snd_una + offset, /* compute opts */ 0,
1314                       /* burst */ 0, /* update_snd_nxt */ 0);
1315
1316       if (PREDICT_FALSE (n_bufs))
1317         {
1318           clib_warning ("not all buffers consumed");
1319           vlib_buffer_free (vm, wrk->tx_buffers, n_bufs);
1320         }
1321     }
1322
1323   ASSERT (n_bytes > 0);
1324   ASSERT (((*b)->current_data + (*b)->current_length) <= bytes_per_buffer);
1325
1326   return n_bytes;
1327 }
1328
1329 /**
1330  * Build a retransmit segment
1331  *
1332  * @return the number of bytes in the segment or 0 if there's nothing to
1333  *         retransmit
1334  */
1335 static u32
1336 tcp_prepare_retransmit_segment (tcp_worker_ctx_t * wrk,
1337                                 tcp_connection_t * tc, u32 offset,
1338                                 u32 max_deq_bytes, vlib_buffer_t ** b)
1339 {
1340   u32 start, available_bytes;
1341   int n_bytes = 0;
1342
1343   ASSERT (tc->state >= TCP_STATE_ESTABLISHED);
1344   ASSERT (max_deq_bytes != 0);
1345
1346   /*
1347    * Make sure we can retransmit something
1348    */
1349   available_bytes = transport_max_tx_dequeue (&tc->connection);
1350   ASSERT (available_bytes >= offset);
1351   available_bytes -= offset;
1352   if (!available_bytes)
1353     return 0;
1354
1355   max_deq_bytes = clib_min (tc->snd_mss, max_deq_bytes);
1356   max_deq_bytes = clib_min (available_bytes, max_deq_bytes);
1357
1358   start = tc->snd_una + offset;
1359   ASSERT (seq_leq (start + max_deq_bytes, tc->snd_nxt));
1360
1361   n_bytes = tcp_prepare_segment (wrk, tc, offset, max_deq_bytes, b);
1362   if (!n_bytes)
1363     return 0;
1364
1365   tc->snd_rxt_bytes += n_bytes;
1366
1367   if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
1368     tcp_bt_track_rxt (tc, start, start + n_bytes);
1369
1370   tc->bytes_retrans += n_bytes;
1371   tc->segs_retrans += 1;
1372   tcp_workerp_stats_inc (wrk, rxt_segs, 1);
1373   TCP_EVT (TCP_EVT_CC_RTX, tc, offset, n_bytes);
1374
1375   return n_bytes;
1376 }
1377
1378 static void
1379 tcp_check_sack_reneging (tcp_connection_t * tc)
1380 {
1381   sack_scoreboard_t *sb = &tc->sack_sb;
1382   sack_scoreboard_hole_t *hole;
1383
1384   hole = scoreboard_first_hole (sb);
1385   if (!sb->is_reneging && (!hole || hole->start == tc->snd_una))
1386     return;
1387
1388   scoreboard_clear_reneging (sb, tc->snd_una, tc->snd_nxt);
1389 }
1390
1391 /**
1392  * Reset congestion control, switch cwnd to loss window and try again.
1393  */
1394 static void
1395 tcp_cc_init_rxt_timeout (tcp_connection_t * tc)
1396 {
1397   TCP_EVT (TCP_EVT_CC_EVT, tc, 6);
1398
1399   tc->prev_ssthresh = tc->ssthresh;
1400   tc->prev_cwnd = tc->cwnd;
1401
1402   /* If we entrered loss without fast recovery, notify cc algo of the
1403    * congestion event such that it can update ssthresh and its state */
1404   if (!tcp_in_fastrecovery (tc))
1405     tcp_cc_congestion (tc);
1406
1407   /* Let cc algo decide loss cwnd and ssthresh post unrecovered loss */
1408   tcp_cc_loss (tc);
1409
1410   tc->rtt_ts = 0;
1411   tc->cwnd_acc_bytes = 0;
1412   tc->tr_occurences += 1;
1413   tcp_recovery_on (tc);
1414 }
1415
1416 void
1417 tcp_timer_retransmit_handler (tcp_connection_t * tc)
1418 {
1419   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
1420   vlib_main_t *vm = wrk->vm;
1421   vlib_buffer_t *b = 0;
1422   u32 bi, n_bytes;
1423
1424   tcp_workerp_stats_inc (wrk, tr_events, 1);
1425
1426   /* Should be handled by a different handler */
1427   if (PREDICT_FALSE (tc->state == TCP_STATE_SYN_SENT))
1428     return;
1429
1430   /* Wait-close and retransmit could pop at the same time */
1431   if (tc->state == TCP_STATE_CLOSED)
1432     return;
1433
1434   if (tc->state >= TCP_STATE_ESTABLISHED)
1435     {
1436       TCP_EVT (TCP_EVT_CC_EVT, tc, 2);
1437
1438       /* Lost FIN, retransmit and return */
1439       if (tc->flags & TCP_CONN_FINSNT)
1440         {
1441           tcp_send_fin (tc);
1442           tc->rto_boff += 1;
1443           tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1444           return;
1445         }
1446
1447       /* Shouldn't be here. This condition is tricky because it has to take
1448        * into account boff > 0 due to persist timeout. */
1449       if ((tc->rto_boff == 0 && tc->snd_una == tc->snd_nxt)
1450           || (tc->rto_boff > 0 && seq_geq (tc->snd_una, tc->snd_congestion)
1451               && !tcp_flight_size (tc)))
1452         {
1453           ASSERT (!tcp_in_recovery (tc));
1454           tc->rto_boff = 0;
1455           return;
1456         }
1457
1458       /* We're not in recovery so make sure rto_boff is 0. Can be non 0 due
1459        * to persist timer timeout */
1460       if (!tcp_in_recovery (tc) && tc->rto_boff > 0)
1461         {
1462           tc->rto_boff = 0;
1463           tcp_update_rto (tc);
1464         }
1465
1466       /* Peer is dead or network connectivity is lost. Close connection.
1467        * RFC 1122 section 4.2.3.5 recommends a value of at least 100s. For
1468        * a min rto of 0.2s we need to retry about 8 times. */
1469       if (tc->rto_boff >= TCP_RTO_BOFF_MAX)
1470         {
1471           tcp_send_reset (tc);
1472           tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1473           session_transport_closing_notify (&tc->connection);
1474           session_transport_closed_notify (&tc->connection);
1475           tcp_connection_timers_reset (tc);
1476           tcp_program_cleanup (wrk, tc);
1477           tcp_workerp_stats_inc (wrk, tr_abort, 1);
1478           return;
1479         }
1480
1481       if (tcp_opts_sack_permitted (&tc->rcv_opts))
1482         tcp_check_sack_reneging (tc);
1483
1484       /* Update send congestion to make sure that rxt has data to send */
1485       tc->snd_congestion = tc->snd_nxt;
1486
1487       /* Send the first unacked segment. If we're short on buffers, return
1488        * as soon as possible */
1489       n_bytes = clib_min (tc->snd_mss, tc->snd_nxt - tc->snd_una);
1490       n_bytes = tcp_prepare_retransmit_segment (wrk, tc, 0, n_bytes, &b);
1491       if (!n_bytes)
1492         {
1493           tcp_timer_update (tc, TCP_TIMER_RETRANSMIT, 1);
1494           return;
1495         }
1496
1497       bi = vlib_get_buffer_index (vm, b);
1498       tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1499
1500       tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1501       tcp_retransmit_timer_force_update (tc);
1502
1503       tc->rto_boff += 1;
1504       if (tc->rto_boff == 1)
1505         {
1506           tcp_cc_init_rxt_timeout (tc);
1507           /* Record timestamp. Eifel detection algorithm RFC3522 */
1508           tc->snd_rxt_ts = tcp_tstamp (tc);
1509         }
1510
1511       if (tcp_opts_sack_permitted (&tc->rcv_opts))
1512         scoreboard_init_rxt (&tc->sack_sb, tc->snd_una + n_bytes);
1513
1514       tcp_program_retransmit (tc);
1515     }
1516   /* Retransmit SYN-ACK */
1517   else if (tc->state == TCP_STATE_SYN_RCVD)
1518     {
1519       TCP_EVT (TCP_EVT_CC_EVT, tc, 2);
1520
1521       tc->rtt_ts = 0;
1522
1523       /* Passive open establish timeout */
1524       if (tc->rto > TCP_ESTABLISH_TIME >> 1)
1525         {
1526           tcp_connection_set_state (tc, TCP_STATE_CLOSED);
1527           tcp_connection_timers_reset (tc);
1528           tcp_program_cleanup (wrk, tc);
1529           tcp_workerp_stats_inc (wrk, tr_abort, 1);
1530           return;
1531         }
1532
1533       if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
1534         {
1535           tcp_timer_update (tc, TCP_TIMER_RETRANSMIT, 1);
1536           return;
1537         }
1538
1539       tc->rto_boff += 1;
1540       if (tc->rto_boff > TCP_RTO_SYN_RETRIES)
1541         tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1542
1543       tcp_retransmit_timer_force_update (tc);
1544
1545       b = vlib_get_buffer (vm, bi);
1546       tcp_init_buffer (vm, b);
1547       tcp_make_synack (tc, b);
1548       TCP_EVT (TCP_EVT_SYN_RXT, tc, 1);
1549
1550       /* Retransmit timer already updated, just enqueue to output */
1551       tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1552     }
1553   else
1554     {
1555       ASSERT (tc->state == TCP_STATE_CLOSED);
1556       return;
1557     }
1558 }
1559
1560 /**
1561  * SYN retransmit timer handler. Active open only.
1562  */
1563 void
1564 tcp_timer_retransmit_syn_handler (tcp_connection_t * tc)
1565 {
1566   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
1567   vlib_main_t *vm = wrk->vm;
1568   vlib_buffer_t *b = 0;
1569   u32 bi;
1570
1571   /* Note: the connection may have transitioned to ESTABLISHED... */
1572   if (PREDICT_FALSE (tc->state != TCP_STATE_SYN_SENT))
1573     return;
1574
1575   /* Half-open connection actually moved to established but we were
1576    * waiting for syn retransmit to pop to call cleanup from the right
1577    * thread. */
1578   if (tc->flags & TCP_CONN_HALF_OPEN_DONE)
1579     {
1580       if (tcp_half_open_connection_cleanup (tc))
1581         TCP_DBG ("could not remove half-open connection");
1582       return;
1583     }
1584
1585   TCP_EVT (TCP_EVT_CC_EVT, tc, 2);
1586   tc->rtt_ts = 0;
1587
1588   /* Active open establish timeout */
1589   if (tc->rto >= TCP_ESTABLISH_TIME >> 1)
1590     {
1591       session_stream_connect_notify (&tc->connection, 1 /* fail */ );
1592       tcp_connection_cleanup (tc);
1593       return;
1594     }
1595
1596   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
1597     {
1598       tcp_timer_update (tc, TCP_TIMER_RETRANSMIT_SYN, 1);
1599       return;
1600     }
1601
1602   /* Try without increasing RTO a number of times. If this fails,
1603    * start growing RTO exponentially */
1604   tc->rto_boff += 1;
1605   if (tc->rto_boff > TCP_RTO_SYN_RETRIES)
1606     tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1607
1608   b = vlib_get_buffer (vm, bi);
1609   tcp_init_buffer (vm, b);
1610   tcp_make_syn (tc, b);
1611
1612   TCP_EVT (TCP_EVT_SYN_RXT, tc, 0);
1613
1614   /* This goes straight to ipx_lookup */
1615   tcp_push_ip_hdr (wrk, tc, b);
1616   tcp_enqueue_to_ip_lookup (wrk, b, bi, tc->c_is_ip4, tc->c_fib_index);
1617
1618   tcp_timer_update (tc, TCP_TIMER_RETRANSMIT_SYN,
1619                     tc->rto * TCP_TO_TIMER_TICK);
1620 }
1621
1622 /**
1623  * Got 0 snd_wnd from peer, try to do something about it.
1624  *
1625  */
1626 void
1627 tcp_timer_persist_handler (tcp_connection_t * tc)
1628 {
1629   tcp_worker_ctx_t *wrk = tcp_get_worker (tc->c_thread_index);
1630   u32 bi, max_snd_bytes, available_bytes, offset;
1631   tcp_main_t *tm = vnet_get_tcp_main ();
1632   vlib_main_t *vm = wrk->vm;
1633   vlib_buffer_t *b;
1634   int n_bytes = 0;
1635   u8 *data;
1636
1637   /* Problem already solved or worse */
1638   if (tc->state == TCP_STATE_CLOSED || tc->snd_wnd > tc->snd_mss
1639       || (tc->flags & TCP_CONN_FINSNT))
1640     goto update_scheduler;
1641
1642   available_bytes = transport_max_tx_dequeue (&tc->connection);
1643   offset = tc->snd_nxt - tc->snd_una;
1644
1645   /* Reprogram persist if no new bytes available to send. We may have data
1646    * next time */
1647   if (!available_bytes)
1648     {
1649       tcp_persist_timer_set (tc);
1650       return;
1651     }
1652
1653   if (available_bytes <= offset)
1654     goto update_scheduler;
1655
1656   /* Increment RTO backoff */
1657   tc->rto_boff += 1;
1658   tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1659
1660   /*
1661    * Try to force the first unsent segment (or buffer)
1662    */
1663   if (PREDICT_FALSE (!vlib_buffer_alloc (vm, &bi, 1)))
1664     {
1665       tcp_persist_timer_set (tc);
1666       return;
1667     }
1668
1669   b = vlib_get_buffer (vm, bi);
1670   data = tcp_init_buffer (vm, b);
1671
1672   tcp_validate_txf_size (tc, offset);
1673   tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts, tc->state);
1674   max_snd_bytes = clib_min (tc->snd_mss,
1675                             tm->bytes_per_buffer - TRANSPORT_MAX_HDRS_LEN);
1676   n_bytes = session_tx_fifo_peek_bytes (&tc->connection, data, offset,
1677                                         max_snd_bytes);
1678   b->current_length = n_bytes;
1679   ASSERT (n_bytes != 0 && (tcp_timer_is_active (tc, TCP_TIMER_RETRANSMIT)
1680                            || tc->snd_nxt == tc->snd_una_max
1681                            || tc->rto_boff > 1));
1682
1683   if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
1684     {
1685       tcp_bt_check_app_limited (tc);
1686       tcp_bt_track_tx (tc, n_bytes);
1687     }
1688
1689   tcp_push_hdr_i (tc, b, tc->snd_nxt, /* compute opts */ 0,
1690                   /* burst */ 0, /* update_snd_nxt */ 1);
1691   tc->snd_una_max = seq_max (tc->snd_nxt, tc->snd_una_max);
1692   tcp_validate_txf_size (tc, tc->snd_una_max - tc->snd_una);
1693   tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1694
1695   /* Just sent new data, enable retransmit */
1696   tcp_retransmit_timer_update (tc);
1697
1698   return;
1699
1700 update_scheduler:
1701
1702   if (tcp_is_descheduled (tc))
1703     transport_connection_reschedule (&tc->connection);
1704 }
1705
1706 /**
1707  * Retransmit first unacked segment
1708  */
1709 int
1710 tcp_retransmit_first_unacked (tcp_worker_ctx_t * wrk, tcp_connection_t * tc)
1711 {
1712   vlib_main_t *vm = wrk->vm;
1713   vlib_buffer_t *b;
1714   u32 bi, n_bytes;
1715
1716   TCP_EVT (TCP_EVT_CC_EVT, tc, 1);
1717
1718   n_bytes = tcp_prepare_retransmit_segment (wrk, tc, 0, tc->snd_mss, &b);
1719   if (!n_bytes)
1720     return -1;
1721
1722   bi = vlib_get_buffer_index (vm, b);
1723   tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1724
1725   return 0;
1726 }
1727
1728 static int
1729 tcp_transmit_unsent (tcp_worker_ctx_t * wrk, tcp_connection_t * tc,
1730                      u32 burst_size)
1731 {
1732   u32 offset, n_segs = 0, n_written, bi, available_wnd;
1733   vlib_main_t *vm = wrk->vm;
1734   vlib_buffer_t *b = 0;
1735
1736   offset = tc->snd_nxt - tc->snd_una;
1737   available_wnd = tc->snd_wnd - offset;
1738   burst_size = clib_min (burst_size, available_wnd / tc->snd_mss);
1739
1740   if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
1741     tcp_bt_check_app_limited (tc);
1742
1743   while (n_segs < burst_size)
1744     {
1745       n_written = tcp_prepare_segment (wrk, tc, offset, tc->snd_mss, &b);
1746       if (!n_written)
1747         goto done;
1748
1749       bi = vlib_get_buffer_index (vm, b);
1750       tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1751       offset += n_written;
1752       n_segs += 1;
1753
1754       if (tc->cfg_flags & TCP_CFG_F_RATE_SAMPLE)
1755         tcp_bt_track_tx (tc, n_written);
1756
1757       tc->snd_nxt += n_written;
1758       tc->snd_una_max = seq_max (tc->snd_nxt, tc->snd_una_max);
1759     }
1760
1761 done:
1762   return n_segs;
1763 }
1764
1765 /**
1766  * Estimate send space using proportional rate reduction (RFC6937)
1767  */
1768 int
1769 tcp_fastrecovery_prr_snd_space (tcp_connection_t * tc)
1770 {
1771   u32 pipe, prr_out;
1772   int space;
1773
1774   pipe = tcp_flight_size (tc);
1775   prr_out = tc->snd_rxt_bytes + (tc->snd_nxt - tc->snd_congestion);
1776
1777   if (pipe > tc->ssthresh)
1778     {
1779       space = ((int) tc->prr_delivered * ((f64) tc->ssthresh / tc->prev_cwnd))
1780         - prr_out;
1781     }
1782   else
1783     {
1784       int limit;
1785       limit = clib_max ((int) (tc->prr_delivered - prr_out), 0) + tc->snd_mss;
1786       space = clib_min (tc->ssthresh - pipe, limit);
1787     }
1788   space = clib_max (space, prr_out ? 0 : tc->snd_mss);
1789   return space;
1790 }
1791
1792 static inline u8
1793 tcp_retransmit_should_retry_head (tcp_connection_t * tc,
1794                                   sack_scoreboard_t * sb)
1795 {
1796   u32 tx_adv_sack = sb->high_sacked - tc->snd_congestion;
1797   f64 rr = (f64) tc->ssthresh / tc->prev_cwnd;
1798
1799   if (tcp_fastrecovery_first (tc))
1800     return 1;
1801
1802   return (tx_adv_sack > (tc->snd_una - tc->prr_start) * rr);
1803 }
1804
1805 static inline u8
1806 tcp_max_tx_deq (tcp_connection_t * tc)
1807 {
1808   return (transport_max_tx_dequeue (&tc->connection)
1809           - (tc->snd_nxt - tc->snd_una));
1810 }
1811
1812 #define scoreboard_rescue_rxt_valid(_sb, _tc)                   \
1813     (seq_geq (_sb->rescue_rxt, _tc->snd_una)                    \
1814         && seq_leq (_sb->rescue_rxt, _tc->snd_congestion))
1815
1816 /**
1817  * Do retransmit with SACKs
1818  */
1819 static int
1820 tcp_retransmit_sack (tcp_worker_ctx_t * wrk, tcp_connection_t * tc,
1821                      u32 burst_size)
1822 {
1823   u32 n_written = 0, offset, max_bytes, n_segs = 0;
1824   u8 snd_limited = 0, can_rescue = 0;
1825   u32 bi, max_deq, burst_bytes;
1826   sack_scoreboard_hole_t *hole;
1827   vlib_main_t *vm = wrk->vm;
1828   vlib_buffer_t *b = 0;
1829   sack_scoreboard_t *sb;
1830   int snd_space;
1831
1832   ASSERT (tcp_in_cong_recovery (tc));
1833
1834   burst_bytes = transport_connection_tx_pacer_burst (&tc->connection);
1835   burst_size = clib_min (burst_size, burst_bytes / tc->snd_mss);
1836   if (!burst_size)
1837     {
1838       tcp_program_retransmit (tc);
1839       return 0;
1840     }
1841
1842   if (tcp_in_recovery (tc))
1843     snd_space = tcp_available_cc_snd_space (tc);
1844   else
1845     snd_space = tcp_fastrecovery_prr_snd_space (tc);
1846
1847   if (snd_space < tc->snd_mss)
1848     goto done;
1849
1850   sb = &tc->sack_sb;
1851
1852   /* Check if snd_una is a lost retransmit */
1853   if (pool_elts (sb->holes)
1854       && seq_gt (sb->high_sacked, tc->snd_congestion)
1855       && tc->rxt_head != tc->snd_una
1856       && tcp_retransmit_should_retry_head (tc, sb))
1857     {
1858       max_bytes = clib_min (tc->snd_mss, tc->snd_congestion - tc->snd_una);
1859       n_written = tcp_prepare_retransmit_segment (wrk, tc, 0, max_bytes, &b);
1860       if (!n_written)
1861         {
1862           tcp_program_retransmit (tc);
1863           goto done;
1864         }
1865       bi = vlib_get_buffer_index (vm, b);
1866       tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1867       n_segs = 1;
1868
1869       tc->rxt_head = tc->snd_una;
1870       tc->rxt_delivered += n_written;
1871       tc->prr_delivered += n_written;
1872       ASSERT (tc->rxt_delivered <= tc->snd_rxt_bytes);
1873     }
1874
1875   tcp_fastrecovery_first_off (tc);
1876
1877   TCP_EVT (TCP_EVT_CC_EVT, tc, 0);
1878   hole = scoreboard_get_hole (sb, sb->cur_rxt_hole);
1879
1880   max_deq = transport_max_tx_dequeue (&tc->connection);
1881   max_deq -= tc->snd_nxt - tc->snd_una;
1882
1883   while (snd_space > 0 && n_segs < burst_size)
1884     {
1885       hole = scoreboard_next_rxt_hole (sb, hole, max_deq != 0, &can_rescue,
1886                                        &snd_limited);
1887       if (!hole)
1888         {
1889           /* We are out of lost holes to retransmit so send some new data. */
1890           if (max_deq > tc->snd_mss)
1891             {
1892               u32 n_segs_new;
1893               int av_wnd;
1894
1895               /* Make sure we don't exceed available window and leave space
1896                * for one more packet, to avoid zero window acks */
1897               av_wnd = (int) tc->snd_wnd - (tc->snd_nxt - tc->snd_una);
1898               av_wnd = clib_max (av_wnd - tc->snd_mss, 0);
1899               snd_space = clib_min (snd_space, av_wnd);
1900               snd_space = clib_min (max_deq, snd_space);
1901               burst_size = clib_min (burst_size - n_segs,
1902                                      snd_space / tc->snd_mss);
1903               burst_size = clib_min (burst_size, TCP_RXT_MAX_BURST);
1904               n_segs_new = tcp_transmit_unsent (wrk, tc, burst_size);
1905               if (max_deq > n_segs_new * tc->snd_mss)
1906                 tcp_program_retransmit (tc);
1907
1908               n_segs += n_segs_new;
1909               goto done;
1910             }
1911
1912           if (tcp_in_recovery (tc) || !can_rescue
1913               || scoreboard_rescue_rxt_valid (sb, tc))
1914             break;
1915
1916           /* If rescue rxt undefined or less than snd_una then one segment of
1917            * up to SMSS octets that MUST include the highest outstanding
1918            * unSACKed sequence number SHOULD be returned, and RescueRxt set to
1919            * RecoveryPoint. HighRxt MUST NOT be updated.
1920            */
1921           hole = scoreboard_last_hole (sb);
1922           max_bytes = clib_min (tc->snd_mss, hole->end - hole->start);
1923           max_bytes = clib_min (max_bytes, snd_space);
1924           offset = hole->end - tc->snd_una - max_bytes;
1925           n_written = tcp_prepare_retransmit_segment (wrk, tc, offset,
1926                                                       max_bytes, &b);
1927           if (!n_written)
1928             goto done;
1929
1930           sb->rescue_rxt = tc->snd_congestion;
1931           bi = vlib_get_buffer_index (vm, b);
1932           tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1933           n_segs += 1;
1934           break;
1935         }
1936
1937       max_bytes = clib_min (hole->end - sb->high_rxt, snd_space);
1938       max_bytes = snd_limited ? clib_min (max_bytes, tc->snd_mss) : max_bytes;
1939       if (max_bytes == 0)
1940         break;
1941
1942       offset = sb->high_rxt - tc->snd_una;
1943       n_written = tcp_prepare_retransmit_segment (wrk, tc, offset, max_bytes,
1944                                                   &b);
1945       ASSERT (n_written <= snd_space);
1946
1947       /* Nothing left to retransmit */
1948       if (n_written == 0)
1949         break;
1950
1951       bi = vlib_get_buffer_index (vm, b);
1952       tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
1953
1954       sb->high_rxt += n_written;
1955       ASSERT (seq_leq (sb->high_rxt, tc->snd_nxt));
1956
1957       snd_space -= n_written;
1958       n_segs += 1;
1959     }
1960
1961   if (hole)
1962     tcp_program_retransmit (tc);
1963
1964 done:
1965
1966   transport_connection_tx_pacer_reset_bucket (&tc->connection, 0);
1967   return n_segs;
1968 }
1969
1970 /**
1971  * Fast retransmit without SACK info
1972  */
1973 static int
1974 tcp_retransmit_no_sack (tcp_worker_ctx_t * wrk, tcp_connection_t * tc,
1975                         u32 burst_size)
1976 {
1977   u32 n_written = 0, offset = 0, bi, max_deq, n_segs_now, max_bytes;
1978   u32 burst_bytes, sent_bytes;
1979   vlib_main_t *vm = wrk->vm;
1980   int snd_space, n_segs = 0;
1981   u8 cc_limited = 0;
1982   vlib_buffer_t *b;
1983
1984   ASSERT (tcp_in_cong_recovery (tc));
1985   TCP_EVT (TCP_EVT_CC_EVT, tc, 0);
1986
1987   burst_bytes = transport_connection_tx_pacer_burst (&tc->connection);
1988   burst_size = clib_min (burst_size, burst_bytes / tc->snd_mss);
1989   if (!burst_size)
1990     {
1991       tcp_program_retransmit (tc);
1992       return 0;
1993     }
1994
1995   snd_space = tcp_available_cc_snd_space (tc);
1996   cc_limited = snd_space < burst_bytes;
1997
1998   if (!tcp_fastrecovery_first (tc))
1999     goto send_unsent;
2000
2001   /* RFC 6582: [If a partial ack], retransmit the first unacknowledged
2002    * segment. */
2003   while (snd_space > 0 && n_segs < burst_size)
2004     {
2005       max_bytes = clib_min (tc->snd_mss,
2006                             tc->snd_congestion - tc->snd_una - offset);
2007       if (!max_bytes)
2008         break;
2009       n_written = tcp_prepare_retransmit_segment (wrk, tc, offset, max_bytes,
2010                                                   &b);
2011
2012       /* Nothing left to retransmit */
2013       if (n_written == 0)
2014         break;
2015
2016       bi = vlib_get_buffer_index (vm, b);
2017       tcp_enqueue_to_output (wrk, b, bi, tc->c_is_ip4);
2018       snd_space -= n_written;
2019       offset += n_written;
2020       n_segs += 1;
2021     }
2022
2023   if (n_segs == burst_size)
2024     goto done;
2025
2026 send_unsent:
2027
2028   /* RFC 6582: Send a new segment if permitted by the new value of cwnd. */
2029   if (snd_space < tc->snd_mss || tc->snd_mss == 0)
2030     goto done;
2031
2032   max_deq = transport_max_tx_dequeue (&tc->connection);
2033   max_deq -= tc->snd_nxt - tc->snd_una;
2034   if (max_deq)
2035     {
2036       snd_space = clib_min (max_deq, snd_space);
2037       burst_size = clib_min (burst_size - n_segs, snd_space / tc->snd_mss);
2038       n_segs_now = tcp_transmit_unsent (wrk, tc, burst_size);
2039       if (n_segs_now && max_deq > n_segs_now * tc->snd_mss)
2040         tcp_program_retransmit (tc);
2041       n_segs += n_segs_now;
2042     }
2043
2044 done:
2045   tcp_fastrecovery_first_off (tc);
2046
2047   sent_bytes = clib_min (n_segs * tc->snd_mss, burst_bytes);
2048   sent_bytes = cc_limited ? burst_bytes : sent_bytes;
2049   transport_connection_tx_pacer_update_bytes (&tc->connection, sent_bytes);
2050
2051   return n_segs;
2052 }
2053
2054 static int
2055 tcp_send_acks (tcp_connection_t * tc, u32 max_burst_size)
2056 {
2057   int j, n_acks;
2058
2059   if (!tc->pending_dupacks)
2060     {
2061       if (tcp_in_cong_recovery (tc) || !tcp_max_tx_deq (tc)
2062           || tc->state != TCP_STATE_ESTABLISHED)
2063         {
2064           tcp_send_ack (tc);
2065           return 1;
2066         }
2067       return 0;
2068     }
2069
2070   /* If we're supposed to send dupacks but have no ooo data
2071    * send only one ack */
2072   if (!vec_len (tc->snd_sacks))
2073     {
2074       tcp_send_ack (tc);
2075       tc->dupacks_out += 1;
2076       tc->pending_dupacks = 0;
2077       return 1;
2078     }
2079
2080   /* Start with first sack block */
2081   tc->snd_sack_pos = 0;
2082
2083   /* Generate enough dupacks to cover all sack blocks. Do not generate
2084    * more sacks than the number of packets received. But do generate at
2085    * least 3, i.e., the number needed to signal congestion, if needed. */
2086   n_acks = vec_len (tc->snd_sacks) / TCP_OPTS_MAX_SACK_BLOCKS;
2087   n_acks = clib_min (n_acks, tc->pending_dupacks);
2088   n_acks = clib_max (n_acks, clib_min (tc->pending_dupacks, 3));
2089   for (j = 0; j < clib_min (n_acks, max_burst_size); j++)
2090     tcp_send_ack (tc);
2091
2092   if (n_acks < max_burst_size)
2093     {
2094       tc->pending_dupacks = 0;
2095       tc->snd_sack_pos = 0;
2096       tc->dupacks_out += n_acks;
2097       return n_acks;
2098     }
2099   else
2100     {
2101       TCP_DBG ("constrained by burst size");
2102       tc->pending_dupacks = n_acks - max_burst_size;
2103       tc->dupacks_out += max_burst_size;
2104       tcp_program_dupack (tc);
2105       return max_burst_size;
2106     }
2107 }
2108
2109 static int
2110 tcp_do_retransmit (tcp_connection_t * tc, u32 max_burst_size)
2111 {
2112   tcp_worker_ctx_t *wrk;
2113   u32 n_segs;
2114
2115   if (PREDICT_FALSE (tc->state == TCP_STATE_CLOSED))
2116     return 0;
2117
2118   wrk = tcp_get_worker (tc->c_thread_index);
2119
2120   if (tcp_opts_sack_permitted (&tc->rcv_opts))
2121     n_segs = tcp_retransmit_sack (wrk, tc, max_burst_size);
2122   else
2123     n_segs = tcp_retransmit_no_sack (wrk, tc, max_burst_size);
2124
2125   return n_segs;
2126 }
2127
2128 int
2129 tcp_session_custom_tx (void *conn, u32 max_burst_size)
2130 {
2131   tcp_connection_t *tc = (tcp_connection_t *) conn;
2132   u32 n_segs = 0;
2133
2134   if (tcp_in_cong_recovery (tc) && (tc->flags & TCP_CONN_RXT_PENDING))
2135     {
2136       tc->flags &= ~TCP_CONN_RXT_PENDING;
2137       n_segs = tcp_do_retransmit (tc, max_burst_size);
2138       max_burst_size -= n_segs;
2139     }
2140
2141   if (!(tc->flags & TCP_CONN_SNDACK))
2142     return n_segs;
2143
2144   tc->flags &= ~TCP_CONN_SNDACK;
2145
2146   /* We have retransmitted packets and no dupack */
2147   if (n_segs && !tc->pending_dupacks)
2148     return n_segs;
2149
2150   if (!max_burst_size)
2151     {
2152       tcp_program_ack (tc);
2153       return max_burst_size;
2154     }
2155
2156   n_segs += tcp_send_acks (tc, max_burst_size);
2157
2158   return n_segs;
2159 }
2160 #endif /* CLIB_MARCH_VARIANT */
2161
2162 static void
2163 tcp_output_handle_link_local (tcp_connection_t * tc0, vlib_buffer_t * b0,
2164                               u16 * next0, u32 * error0)
2165 {
2166   ip_adjacency_t *adj;
2167   adj_index_t ai;
2168
2169   /* Not thread safe but as long as the connection exists the adj should
2170    * not be removed */
2171   ai = adj_nbr_find (FIB_PROTOCOL_IP6, VNET_LINK_IP6, &tc0->c_rmt_ip,
2172                      tc0->sw_if_index);
2173   if (ai == ADJ_INDEX_INVALID)
2174     {
2175       vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
2176       *next0 = TCP_OUTPUT_NEXT_DROP;
2177       *error0 = TCP_ERROR_LINK_LOCAL_RW;
2178       return;
2179     }
2180
2181   adj = adj_get (ai);
2182   if (PREDICT_TRUE (adj->lookup_next_index == IP_LOOKUP_NEXT_REWRITE))
2183     *next0 = TCP_OUTPUT_NEXT_IP_REWRITE;
2184   else if (adj->lookup_next_index == IP_LOOKUP_NEXT_ARP)
2185     *next0 = TCP_OUTPUT_NEXT_IP_ARP;
2186   else
2187     {
2188       *next0 = TCP_OUTPUT_NEXT_DROP;
2189       *error0 = TCP_ERROR_LINK_LOCAL_RW;
2190     }
2191   vnet_buffer (b0)->ip.adj_index[VLIB_TX] = ai;
2192 }
2193
2194 static void
2195 tcp46_output_trace_frame (vlib_main_t * vm, vlib_node_runtime_t * node,
2196                           u32 * to_next, u32 n_bufs)
2197 {
2198   tcp_connection_t *tc;
2199   tcp_tx_trace_t *t;
2200   vlib_buffer_t *b;
2201   tcp_header_t *th;
2202   int i;
2203
2204   for (i = 0; i < n_bufs; i++)
2205     {
2206       b = vlib_get_buffer (vm, to_next[i]);
2207       if (!(b->flags & VLIB_BUFFER_IS_TRACED))
2208         continue;
2209       th = vlib_buffer_get_current (b);
2210       tc = tcp_connection_get (vnet_buffer (b)->tcp.connection_index,
2211                                vm->thread_index);
2212       t = vlib_add_trace (vm, node, b, sizeof (*t));
2213       clib_memcpy_fast (&t->tcp_header, th, sizeof (t->tcp_header));
2214       clib_memcpy_fast (&t->tcp_connection, tc, sizeof (t->tcp_connection));
2215     }
2216 }
2217
2218 always_inline void
2219 tcp_output_push_ip (vlib_main_t * vm, vlib_buffer_t * b0,
2220                     tcp_connection_t * tc0, u8 is_ip4)
2221 {
2222   TCP_EVT (TCP_EVT_OUTPUT, tc0,
2223            ((tcp_header_t *) vlib_buffer_get_current (b0))->flags,
2224            b0->current_length);
2225
2226   if (is_ip4)
2227     vlib_buffer_push_ip4 (vm, b0, &tc0->c_lcl_ip4, &tc0->c_rmt_ip4,
2228                           IP_PROTOCOL_TCP, tcp_csum_offload (tc0));
2229   else
2230     vlib_buffer_push_ip6_custom (vm, b0, &tc0->c_lcl_ip6, &tc0->c_rmt_ip6,
2231                                  IP_PROTOCOL_TCP, tc0->ipv6_flow_label);
2232 }
2233
2234 always_inline void
2235 tcp_check_if_gso (tcp_connection_t * tc, vlib_buffer_t * b)
2236 {
2237   if (PREDICT_TRUE (!(tc->cfg_flags & TCP_CFG_F_TSO)))
2238     return;
2239
2240   u16 data_len = b->current_length - sizeof (tcp_header_t) - tc->snd_opts_len;
2241
2242   if (PREDICT_FALSE (b->flags & VLIB_BUFFER_TOTAL_LENGTH_VALID))
2243     data_len += b->total_length_not_including_first_buffer;
2244
2245   if (PREDICT_TRUE (data_len <= tc->snd_mss))
2246     return;
2247   else
2248     {
2249       ASSERT ((b->flags & VNET_BUFFER_F_L3_HDR_OFFSET_VALID) != 0);
2250       ASSERT ((b->flags & VNET_BUFFER_F_L4_HDR_OFFSET_VALID) != 0);
2251       b->flags |= VNET_BUFFER_F_GSO;
2252       vnet_buffer2 (b)->gso_l4_hdr_sz =
2253         sizeof (tcp_header_t) + tc->snd_opts_len;
2254       vnet_buffer2 (b)->gso_size = tc->snd_mss;
2255     }
2256 }
2257
2258 always_inline void
2259 tcp_output_handle_packet (tcp_connection_t * tc0, vlib_buffer_t * b0,
2260                           vlib_node_runtime_t * error_node, u16 * next0,
2261                           u8 is_ip4)
2262 {
2263   /* If next_index is not drop use it */
2264   if (tc0->next_node_index)
2265     {
2266       *next0 = tc0->next_node_index;
2267       vnet_buffer (b0)->tcp.next_node_opaque = tc0->next_node_opaque;
2268     }
2269   else
2270     {
2271       *next0 = TCP_OUTPUT_NEXT_IP_LOOKUP;
2272     }
2273
2274   vnet_buffer (b0)->sw_if_index[VLIB_TX] = tc0->c_fib_index;
2275   vnet_buffer (b0)->sw_if_index[VLIB_RX] = 0;
2276
2277   if (!is_ip4)
2278     {
2279       u32 error0 = 0;
2280
2281       if (PREDICT_FALSE (ip6_address_is_link_local_unicast (&tc0->c_rmt_ip6)))
2282         tcp_output_handle_link_local (tc0, b0, next0, &error0);
2283
2284       if (PREDICT_FALSE (error0))
2285         {
2286           b0->error = error_node->errors[error0];
2287           return;
2288         }
2289     }
2290
2291   if (!TCP_ALWAYS_ACK)
2292     tcp_timer_reset (tc0, TCP_TIMER_DELACK);
2293
2294   tc0->segs_out += 1;
2295 }
2296
2297 always_inline uword
2298 tcp46_output_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
2299                      vlib_frame_t * frame, int is_ip4)
2300 {
2301   u32 n_left_from, *from, thread_index = vm->thread_index;
2302   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b;
2303   u16 nexts[VLIB_FRAME_SIZE], *next;
2304   vlib_node_runtime_t *error_node;
2305
2306   error_node = vlib_node_get_runtime (vm, tcp_node_index (output, is_ip4));
2307
2308   from = vlib_frame_vector_args (frame);
2309   n_left_from = frame->n_vectors;
2310   tcp_set_time_now (tcp_get_worker (thread_index));
2311
2312   if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE))
2313     tcp46_output_trace_frame (vm, node, from, n_left_from);
2314
2315   vlib_get_buffers (vm, from, bufs, n_left_from);
2316   b = bufs;
2317   next = nexts;
2318
2319   while (n_left_from >= 4)
2320     {
2321       tcp_connection_t *tc0, *tc1;
2322
2323       {
2324         vlib_prefetch_buffer_header (b[2], STORE);
2325         CLIB_PREFETCH (b[2]->data, 2 * CLIB_CACHE_LINE_BYTES, STORE);
2326
2327         vlib_prefetch_buffer_header (b[3], STORE);
2328         CLIB_PREFETCH (b[3]->data, 2 * CLIB_CACHE_LINE_BYTES, STORE);
2329       }
2330
2331       tc0 = tcp_connection_get (vnet_buffer (b[0])->tcp.connection_index,
2332                                 thread_index);
2333       tc1 = tcp_connection_get (vnet_buffer (b[1])->tcp.connection_index,
2334                                 thread_index);
2335
2336       if (PREDICT_TRUE (!tc0 + !tc1 == 0))
2337         {
2338           tcp_output_push_ip (vm, b[0], tc0, is_ip4);
2339           tcp_output_push_ip (vm, b[1], tc1, is_ip4);
2340
2341           tcp_check_if_gso (tc0, b[0]);
2342           tcp_check_if_gso (tc1, b[1]);
2343
2344           tcp_output_handle_packet (tc0, b[0], error_node, &next[0], is_ip4);
2345           tcp_output_handle_packet (tc1, b[1], error_node, &next[1], is_ip4);
2346         }
2347       else
2348         {
2349           if (tc0 != 0)
2350             {
2351               tcp_output_push_ip (vm, b[0], tc0, is_ip4);
2352               tcp_check_if_gso (tc0, b[0]);
2353               tcp_output_handle_packet (tc0, b[0], error_node, &next[0],
2354                                         is_ip4);
2355             }
2356           else
2357             {
2358               b[0]->error = error_node->errors[TCP_ERROR_INVALID_CONNECTION];
2359               next[0] = TCP_OUTPUT_NEXT_DROP;
2360             }
2361           if (tc1 != 0)
2362             {
2363               tcp_output_push_ip (vm, b[1], tc1, is_ip4);
2364               tcp_check_if_gso (tc1, b[1]);
2365               tcp_output_handle_packet (tc1, b[1], error_node, &next[1],
2366                                         is_ip4);
2367             }
2368           else
2369             {
2370               b[1]->error = error_node->errors[TCP_ERROR_INVALID_CONNECTION];
2371               next[1] = TCP_OUTPUT_NEXT_DROP;
2372             }
2373         }
2374
2375       b += 2;
2376       next += 2;
2377       n_left_from -= 2;
2378     }
2379   while (n_left_from > 0)
2380     {
2381       tcp_connection_t *tc0;
2382
2383       if (n_left_from > 1)
2384         {
2385           vlib_prefetch_buffer_header (b[1], STORE);
2386           CLIB_PREFETCH (b[1]->data, 2 * CLIB_CACHE_LINE_BYTES, STORE);
2387         }
2388
2389       tc0 = tcp_connection_get (vnet_buffer (b[0])->tcp.connection_index,
2390                                 thread_index);
2391
2392       if (PREDICT_TRUE (tc0 != 0))
2393         {
2394           tcp_output_push_ip (vm, b[0], tc0, is_ip4);
2395           tcp_check_if_gso (tc0, b[0]);
2396           tcp_output_handle_packet (tc0, b[0], error_node, &next[0], is_ip4);
2397         }
2398       else
2399         {
2400           b[0]->error = error_node->errors[TCP_ERROR_INVALID_CONNECTION];
2401           next[0] = TCP_OUTPUT_NEXT_DROP;
2402         }
2403
2404       b += 1;
2405       next += 1;
2406       n_left_from -= 1;
2407     }
2408
2409   vlib_buffer_enqueue_to_next (vm, node, from, nexts, frame->n_vectors);
2410   vlib_node_increment_counter (vm, tcp_node_index (output, is_ip4),
2411                                TCP_ERROR_PKTS_SENT, frame->n_vectors);
2412   return frame->n_vectors;
2413 }
2414
2415 VLIB_NODE_FN (tcp4_output_node) (vlib_main_t * vm, vlib_node_runtime_t * node,
2416                                  vlib_frame_t * from_frame)
2417 {
2418   return tcp46_output_inline (vm, node, from_frame, 1 /* is_ip4 */ );
2419 }
2420
2421 VLIB_NODE_FN (tcp6_output_node) (vlib_main_t * vm, vlib_node_runtime_t * node,
2422                                  vlib_frame_t * from_frame)
2423 {
2424   return tcp46_output_inline (vm, node, from_frame, 0 /* is_ip4 */ );
2425 }
2426
2427 /* *INDENT-OFF* */
2428 VLIB_REGISTER_NODE (tcp4_output_node) =
2429 {
2430   .name = "tcp4-output",
2431   /* Takes a vector of packets. */
2432   .vector_size = sizeof (u32),
2433   .n_errors = TCP_N_ERROR,
2434   .protocol_hint = VLIB_NODE_PROTO_HINT_TCP,
2435   .error_strings = tcp_error_strings,
2436   .n_next_nodes = TCP_OUTPUT_N_NEXT,
2437   .next_nodes = {
2438 #define _(s,n) [TCP_OUTPUT_NEXT_##s] = n,
2439     foreach_tcp4_output_next
2440 #undef _
2441   },
2442   .format_buffer = format_tcp_header,
2443   .format_trace = format_tcp_tx_trace,
2444 };
2445 /* *INDENT-ON* */
2446
2447 /* *INDENT-OFF* */
2448 VLIB_REGISTER_NODE (tcp6_output_node) =
2449 {
2450   .name = "tcp6-output",
2451     /* Takes a vector of packets. */
2452   .vector_size = sizeof (u32),
2453   .n_errors = TCP_N_ERROR,
2454   .protocol_hint = VLIB_NODE_PROTO_HINT_TCP,
2455   .error_strings = tcp_error_strings,
2456   .n_next_nodes = TCP_OUTPUT_N_NEXT,
2457   .next_nodes = {
2458 #define _(s,n) [TCP_OUTPUT_NEXT_##s] = n,
2459     foreach_tcp6_output_next
2460 #undef _
2461   },
2462   .format_buffer = format_tcp_header,
2463   .format_trace = format_tcp_tx_trace,
2464 };
2465 /* *INDENT-ON* */
2466
2467 typedef enum _tcp_reset_next
2468 {
2469   TCP_RESET_NEXT_DROP,
2470   TCP_RESET_NEXT_IP_LOOKUP,
2471   TCP_RESET_N_NEXT
2472 } tcp_reset_next_t;
2473
2474 #define foreach_tcp4_reset_next         \
2475   _(DROP, "error-drop")                 \
2476   _(IP_LOOKUP, "ip4-lookup")
2477
2478 #define foreach_tcp6_reset_next         \
2479   _(DROP, "error-drop")                 \
2480   _(IP_LOOKUP, "ip6-lookup")
2481
2482 static uword
2483 tcp46_send_reset_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
2484                          vlib_frame_t * from_frame, u8 is_ip4)
2485 {
2486   u32 error0 = TCP_ERROR_RST_SENT, next0 = TCP_RESET_NEXT_IP_LOOKUP;
2487   u32 n_left_from, next_index, *from, *to_next;
2488
2489   from = vlib_frame_vector_args (from_frame);
2490   n_left_from = from_frame->n_vectors;
2491
2492   next_index = node->cached_next_index;
2493
2494   while (n_left_from > 0)
2495     {
2496       u32 n_left_to_next;
2497
2498       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
2499
2500       while (n_left_from > 0 && n_left_to_next > 0)
2501         {
2502           vlib_buffer_t *b0;
2503           tcp_tx_trace_t *t0;
2504           tcp_header_t *th0;
2505           u32 bi0;
2506
2507           bi0 = from[0];
2508           to_next[0] = bi0;
2509           from += 1;
2510           to_next += 1;
2511           n_left_from -= 1;
2512           n_left_to_next -= 1;
2513
2514           b0 = vlib_get_buffer (vm, bi0);
2515           tcp_make_reset_in_place (vm, b0, is_ip4);
2516
2517           /* Prepare to send to IP lookup */
2518           vnet_buffer (b0)->sw_if_index[VLIB_TX] = ~0;
2519
2520           b0->error = node->errors[error0];
2521           b0->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
2522           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
2523             {
2524               th0 = vlib_buffer_get_current (b0);
2525               if (is_ip4)
2526                 th0 = ip4_next_header ((ip4_header_t *) th0);
2527               else
2528                 th0 = ip6_next_header ((ip6_header_t *) th0);
2529               t0 = vlib_add_trace (vm, node, b0, sizeof (*t0));
2530               clib_memcpy_fast (&t0->tcp_header, th0,
2531                                 sizeof (t0->tcp_header));
2532             }
2533
2534           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
2535                                            n_left_to_next, bi0, next0);
2536         }
2537       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
2538     }
2539   return from_frame->n_vectors;
2540 }
2541
2542 VLIB_NODE_FN (tcp4_reset_node) (vlib_main_t * vm, vlib_node_runtime_t * node,
2543                                 vlib_frame_t * from_frame)
2544 {
2545   return tcp46_send_reset_inline (vm, node, from_frame, 1);
2546 }
2547
2548 VLIB_NODE_FN (tcp6_reset_node) (vlib_main_t * vm, vlib_node_runtime_t * node,
2549                                 vlib_frame_t * from_frame)
2550 {
2551   return tcp46_send_reset_inline (vm, node, from_frame, 0);
2552 }
2553
2554 /* *INDENT-OFF* */
2555 VLIB_REGISTER_NODE (tcp4_reset_node) = {
2556   .name = "tcp4-reset",
2557   .vector_size = sizeof (u32),
2558   .n_errors = TCP_N_ERROR,
2559   .error_strings = tcp_error_strings,
2560   .n_next_nodes = TCP_RESET_N_NEXT,
2561   .next_nodes = {
2562 #define _(s,n) [TCP_RESET_NEXT_##s] = n,
2563     foreach_tcp4_reset_next
2564 #undef _
2565   },
2566   .format_trace = format_tcp_tx_trace,
2567 };
2568 /* *INDENT-ON* */
2569
2570 /* *INDENT-OFF* */
2571 VLIB_REGISTER_NODE (tcp6_reset_node) = {
2572   .name = "tcp6-reset",
2573   .vector_size = sizeof (u32),
2574   .n_errors = TCP_N_ERROR,
2575   .error_strings = tcp_error_strings,
2576   .n_next_nodes = TCP_RESET_N_NEXT,
2577   .next_nodes = {
2578 #define _(s,n) [TCP_RESET_NEXT_##s] = n,
2579     foreach_tcp6_reset_next
2580 #undef _
2581   },
2582   .format_trace = format_tcp_tx_trace,
2583 };
2584 /* *INDENT-ON* */
2585
2586 /*
2587  * fd.io coding-style-patch-verification: ON
2588  *
2589  * Local Variables:
2590  * eval: (c-set-style "gnu")
2591  * End:
2592  */