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