Add support for tcp/session buffer chains
[vpp.git] / src / vnet / tcp / tcp_output.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <vnet/tcp/tcp.h>
17 #include <vnet/lisp-cp/packets.h>
18
19 vlib_node_registration_t tcp4_output_node;
20 vlib_node_registration_t tcp6_output_node;
21
22 typedef enum _tcp_output_nect
23 {
24   TCP_OUTPUT_NEXT_DROP,
25   TCP_OUTPUT_NEXT_IP_LOOKUP,
26   TCP_OUTPUT_N_NEXT
27 } tcp_output_next_t;
28
29 #define foreach_tcp4_output_next                \
30   _ (DROP, "error-drop")                        \
31   _ (IP_LOOKUP, "ip4-lookup")
32
33 #define foreach_tcp6_output_next                \
34   _ (DROP, "error-drop")                        \
35   _ (IP_LOOKUP, "ip6-lookup")
36
37 static char *tcp_error_strings[] = {
38 #define tcp_error(n,s) s,
39 #include <vnet/tcp/tcp_error.def>
40 #undef tcp_error
41 };
42
43 typedef struct
44 {
45   tcp_header_t tcp_header;
46   tcp_connection_t tcp_connection;
47 } tcp_tx_trace_t;
48
49 u16 dummy_mtu = 1460;
50
51 u8 *
52 format_tcp_tx_trace (u8 * s, va_list * args)
53 {
54   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
55   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
56   tcp_tx_trace_t *t = va_arg (*args, tcp_tx_trace_t *);
57   uword indent = format_get_indent (s);
58
59   s = format (s, "%U\n%U%U",
60               format_tcp_header, &t->tcp_header, 128,
61               format_white_space, indent,
62               format_tcp_connection_verbose, &t->tcp_connection);
63
64   return s;
65 }
66
67 static u8
68 tcp_window_compute_scale (u32 available_space)
69 {
70   u8 wnd_scale = 0;
71   while (wnd_scale < TCP_MAX_WND_SCALE
72          && (available_space >> wnd_scale) > TCP_WND_MAX)
73     wnd_scale++;
74   return wnd_scale;
75 }
76
77 /**
78  * TCP's IW as recommended by RFC6928
79  */
80 always_inline u32
81 tcp_initial_wnd_unscaled (tcp_connection_t * tc)
82 {
83   return TCP_IW_N_SEGMENTS * tc->mss;
84 }
85
86 /**
87  * Compute initial window and scale factor. As per RFC1323, window field in
88  * SYN and SYN-ACK segments is never scaled.
89  */
90 u32
91 tcp_initial_window_to_advertise (tcp_connection_t * tc)
92 {
93   u32 max_fifo;
94
95   /* Initial wnd for SYN. Fifos are not allocated yet.
96    * Use some predefined value. For SYN-ACK we still want the
97    * scale to be computed in the same way */
98   max_fifo = TCP_MAX_RX_FIFO_SIZE;
99
100   tc->rcv_wscale = tcp_window_compute_scale (max_fifo);
101   tc->rcv_wnd = tcp_initial_wnd_unscaled (tc);
102
103   return clib_min (tc->rcv_wnd, TCP_WND_MAX);
104 }
105
106 /**
107  * Compute and return window to advertise, scaled as per RFC1323
108  */
109 u32
110 tcp_window_to_advertise (tcp_connection_t * tc, tcp_state_t state)
111 {
112   if (state < TCP_STATE_ESTABLISHED)
113     return tcp_initial_window_to_advertise (tc);
114
115   tcp_update_rcv_wnd (tc);
116
117   if (tc->rcv_wnd == 0)
118     {
119       tc->flags |= TCP_CONN_SENT_RCV_WND0;
120     }
121   else
122     {
123       tc->flags &= ~TCP_CONN_SENT_RCV_WND0;
124     }
125
126   return tc->rcv_wnd >> tc->rcv_wscale;
127 }
128
129 void
130 tcp_update_rcv_wnd (tcp_connection_t * tc)
131 {
132   i32 observed_wnd;
133   u32 available_space, max_fifo, wnd;
134
135   /*
136    * Figure out how much space we have available
137    */
138   available_space = stream_session_max_rx_enqueue (&tc->connection);
139   max_fifo = stream_session_fifo_size (&tc->connection);
140
141   ASSERT (tc->opt.mss < max_fifo);
142   if (available_space < tc->opt.mss && available_space < max_fifo >> 3)
143     available_space = 0;
144
145   /*
146    * Use the above and what we know about what we've previously advertised
147    * to compute the new window
148    */
149   observed_wnd = (i32) tc->rcv_wnd - (tc->rcv_nxt - tc->rcv_las);
150   if (observed_wnd < 0)
151     observed_wnd = 0;
152
153   /* Bad. Thou shalt not shrink */
154   if (available_space < observed_wnd)
155     {
156       wnd = observed_wnd;
157       TCP_EVT_DBG (TCP_EVT_RCV_WND_SHRUNK, tc, observed_wnd, available_space);
158     }
159   else
160     {
161       wnd = available_space;
162     }
163
164   /* Make sure we have a multiple of rcv_wscale */
165   if (wnd && tc->rcv_wscale)
166     {
167       wnd &= ~(1 << tc->rcv_wscale);
168       if (wnd == 0)
169         wnd = 1 << tc->rcv_wscale;
170     }
171
172   tc->rcv_wnd = clib_min (wnd, TCP_WND_MAX << tc->rcv_wscale);
173 }
174
175 /**
176  * Write TCP options to segment.
177  */
178 u32
179 tcp_options_write (u8 * data, tcp_options_t * opts)
180 {
181   u32 opts_len = 0;
182   u32 buf, seq_len = 4;
183
184   if (tcp_opts_mss (opts))
185     {
186       *data++ = TCP_OPTION_MSS;
187       *data++ = TCP_OPTION_LEN_MSS;
188       buf = clib_host_to_net_u16 (opts->mss);
189       clib_memcpy (data, &buf, sizeof (opts->mss));
190       data += sizeof (opts->mss);
191       opts_len += TCP_OPTION_LEN_MSS;
192     }
193
194   if (tcp_opts_wscale (opts))
195     {
196       *data++ = TCP_OPTION_WINDOW_SCALE;
197       *data++ = TCP_OPTION_LEN_WINDOW_SCALE;
198       *data++ = opts->wscale;
199       opts_len += TCP_OPTION_LEN_WINDOW_SCALE;
200     }
201
202   if (tcp_opts_sack_permitted (opts))
203     {
204       *data++ = TCP_OPTION_SACK_PERMITTED;
205       *data++ = TCP_OPTION_LEN_SACK_PERMITTED;
206       opts_len += TCP_OPTION_LEN_SACK_PERMITTED;
207     }
208
209   if (tcp_opts_tstamp (opts))
210     {
211       *data++ = TCP_OPTION_TIMESTAMP;
212       *data++ = TCP_OPTION_LEN_TIMESTAMP;
213       buf = clib_host_to_net_u32 (opts->tsval);
214       clib_memcpy (data, &buf, sizeof (opts->tsval));
215       data += sizeof (opts->tsval);
216       buf = clib_host_to_net_u32 (opts->tsecr);
217       clib_memcpy (data, &buf, sizeof (opts->tsecr));
218       data += sizeof (opts->tsecr);
219       opts_len += TCP_OPTION_LEN_TIMESTAMP;
220     }
221
222   if (tcp_opts_sack (opts))
223     {
224       int i;
225       u32 n_sack_blocks = clib_min (vec_len (opts->sacks),
226                                     TCP_OPTS_MAX_SACK_BLOCKS);
227
228       if (n_sack_blocks != 0)
229         {
230           *data++ = TCP_OPTION_SACK_BLOCK;
231           *data++ = 2 + n_sack_blocks * TCP_OPTION_LEN_SACK_BLOCK;
232           for (i = 0; i < n_sack_blocks; i++)
233             {
234               buf = clib_host_to_net_u32 (opts->sacks[i].start);
235               clib_memcpy (data, &buf, seq_len);
236               data += seq_len;
237               buf = clib_host_to_net_u32 (opts->sacks[i].end);
238               clib_memcpy (data, &buf, seq_len);
239               data += seq_len;
240             }
241           opts_len += 2 + n_sack_blocks * TCP_OPTION_LEN_SACK_BLOCK;
242         }
243     }
244
245   /* Terminate TCP options */
246   if (opts_len % 4)
247     {
248       *data++ = TCP_OPTION_EOL;
249       opts_len += TCP_OPTION_LEN_EOL;
250     }
251
252   /* Pad with zeroes to a u32 boundary */
253   while (opts_len % 4)
254     {
255       *data++ = TCP_OPTION_NOOP;
256       opts_len += TCP_OPTION_LEN_NOOP;
257     }
258   return opts_len;
259 }
260
261 always_inline int
262 tcp_make_syn_options (tcp_options_t * opts, u8 wnd_scale)
263 {
264   u8 len = 0;
265
266   opts->flags |= TCP_OPTS_FLAG_MSS;
267   opts->mss = dummy_mtu;        /*XXX discover that */
268   len += TCP_OPTION_LEN_MSS;
269
270   opts->flags |= TCP_OPTS_FLAG_WSCALE;
271   opts->wscale = wnd_scale;
272   len += TCP_OPTION_LEN_WINDOW_SCALE;
273
274   opts->flags |= TCP_OPTS_FLAG_TSTAMP;
275   opts->tsval = tcp_time_now ();
276   opts->tsecr = 0;
277   len += TCP_OPTION_LEN_TIMESTAMP;
278
279   opts->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
280   len += TCP_OPTION_LEN_SACK_PERMITTED;
281
282   /* Align to needed boundary */
283   len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
284   return len;
285 }
286
287 always_inline int
288 tcp_make_synack_options (tcp_connection_t * tc, tcp_options_t * opts)
289 {
290   u8 len = 0;
291
292   opts->flags |= TCP_OPTS_FLAG_MSS;
293   opts->mss = tc->mss;
294   len += TCP_OPTION_LEN_MSS;
295
296   if (tcp_opts_wscale (&tc->opt))
297     {
298       opts->flags |= TCP_OPTS_FLAG_WSCALE;
299       opts->wscale = tc->rcv_wscale;
300       len += TCP_OPTION_LEN_WINDOW_SCALE;
301     }
302
303   if (tcp_opts_tstamp (&tc->opt))
304     {
305       opts->flags |= TCP_OPTS_FLAG_TSTAMP;
306       opts->tsval = tcp_time_now ();
307       opts->tsecr = tc->tsval_recent;
308       len += TCP_OPTION_LEN_TIMESTAMP;
309     }
310
311   if (tcp_opts_sack_permitted (&tc->opt))
312     {
313       opts->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
314       len += TCP_OPTION_LEN_SACK_PERMITTED;
315     }
316
317   /* Align to needed boundary */
318   len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
319   return len;
320 }
321
322 always_inline int
323 tcp_make_established_options (tcp_connection_t * tc, tcp_options_t * opts)
324 {
325   u8 len = 0;
326
327   opts->flags = 0;
328
329   if (tcp_opts_tstamp (&tc->opt))
330     {
331       opts->flags |= TCP_OPTS_FLAG_TSTAMP;
332       opts->tsval = tcp_time_now ();
333       opts->tsecr = tc->tsval_recent;
334       len += TCP_OPTION_LEN_TIMESTAMP;
335     }
336   if (tcp_opts_sack_permitted (&tc->opt))
337     {
338       if (vec_len (tc->snd_sacks))
339         {
340           opts->flags |= TCP_OPTS_FLAG_SACK;
341           opts->sacks = tc->snd_sacks;
342           opts->n_sack_blocks = clib_min (vec_len (tc->snd_sacks),
343                                           TCP_OPTS_MAX_SACK_BLOCKS);
344           len += 2 + TCP_OPTION_LEN_SACK_BLOCK * opts->n_sack_blocks;
345         }
346     }
347
348   /* Align to needed boundary */
349   len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
350   return len;
351 }
352
353 always_inline int
354 tcp_make_options (tcp_connection_t * tc, tcp_options_t * opts,
355                   tcp_state_t state)
356 {
357   switch (state)
358     {
359     case TCP_STATE_ESTABLISHED:
360     case TCP_STATE_FIN_WAIT_1:
361       return tcp_make_established_options (tc, opts);
362     case TCP_STATE_SYN_RCVD:
363       return tcp_make_synack_options (tc, opts);
364     case TCP_STATE_SYN_SENT:
365       return tcp_make_syn_options (opts, tc->rcv_wscale);
366     default:
367       clib_warning ("Not handled!");
368       return 0;
369     }
370 }
371
372 /**
373  * Update max segment size we're able to process.
374  *
375  * The value is constrained by our interface's MTU and IP options. It is
376  * also what we advertise to our peer.
377  */
378 void
379 tcp_update_rcv_mss (tcp_connection_t * tc)
380 {
381   /* TODO find our iface MTU */
382   tc->mss = dummy_mtu;
383 }
384
385 /**
386  * Update snd_mss to reflect the effective segment size that we can send
387  * by taking into account all TCP options, including SACKs
388  */
389 void
390 tcp_update_snd_mss (tcp_connection_t * tc)
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 =
395     tcp_make_options (tc, &tc->snd_opts, TCP_STATE_ESTABLISHED);
396
397   /* XXX check if MTU has been updated */
398   tc->snd_mss = clib_min (tc->mss, tc->opt.mss) - tc->snd_opts_len;
399 }
400
401 void
402 tcp_init_mss (tcp_connection_t * tc)
403 {
404   tcp_update_rcv_mss (tc);
405
406   /* TODO cache mss and consider PMTU discovery */
407   tc->snd_mss = clib_min (tc->opt.mss, tc->mss);
408
409   if (tc->snd_mss == 0)
410     {
411       clib_warning ("snd mss is 0");
412       tc->snd_mss = tc->mss;
413     }
414
415   /* We should have enough space for 40 bytes of options */
416   ASSERT (tc->snd_mss > 45);
417
418   /* If we use timestamp option, account for it */
419   if (tcp_opts_tstamp (&tc->opt))
420     tc->snd_mss -= TCP_OPTION_LEN_TIMESTAMP;
421 }
422
423 #define tcp_get_free_buffer_index(tm, bidx)                             \
424 do {                                                                    \
425   u32 *my_tx_buffers, n_free_buffers;                                   \
426   u32 thread_index = vlib_get_thread_index();                                   \
427   my_tx_buffers = tm->tx_buffers[thread_index];                            \
428   if (PREDICT_FALSE(vec_len (my_tx_buffers) == 0))                      \
429     {                                                                   \
430       n_free_buffers = 32;      /* TODO config or macro */              \
431       vec_validate (my_tx_buffers, n_free_buffers - 1);                 \
432       _vec_len(my_tx_buffers) = vlib_buffer_alloc_from_free_list (      \
433           tm->vlib_main, my_tx_buffers, n_free_buffers,                 \
434           VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);                         \
435       tm->tx_buffers[thread_index] = my_tx_buffers;                        \
436     }                                                                   \
437   /* buffer shortage */                                                 \
438   if (PREDICT_FALSE (vec_len (my_tx_buffers) == 0))                     \
439     return;                                                             \
440   *bidx = my_tx_buffers[_vec_len (my_tx_buffers)-1];                    \
441   _vec_len (my_tx_buffers) -= 1;                                        \
442 } while (0)
443
444 #define tcp_return_buffer(tm)                                           \
445 do {                                                                    \
446   u32 *my_tx_buffers;                                                   \
447   u32 thread_index = vlib_get_thread_index();                                   \
448   my_tx_buffers = tm->tx_buffers[thread_index];                                 \
449   _vec_len (my_tx_buffers) +=1;                                         \
450 } while (0)
451
452 always_inline void
453 tcp_reuse_buffer (vlib_main_t * vm, vlib_buffer_t * b)
454 {
455   vlib_buffer_t *it = b;
456   do
457     {
458       it->current_data = 0;
459       it->current_length = 0;
460       it->total_length_not_including_first_buffer = 0;
461     }
462   while ((it->flags & VLIB_BUFFER_NEXT_PRESENT)
463          && (it = vlib_get_buffer (vm, it->next_buffer)));
464
465   /* Leave enough space for headers */
466   vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
467   vnet_buffer (b)->tcp.flags = 0;
468 }
469
470 /**
471  * Prepare ACK
472  */
473 void
474 tcp_make_ack_i (tcp_connection_t * tc, vlib_buffer_t * b, tcp_state_t state,
475                 u8 flags)
476 {
477   tcp_options_t _snd_opts, *snd_opts = &_snd_opts;
478   u8 tcp_opts_len, tcp_hdr_opts_len;
479   tcp_header_t *th;
480   u16 wnd;
481
482   wnd = tcp_window_to_advertise (tc, state);
483
484   /* Make and write options */
485   tcp_opts_len = tcp_make_established_options (tc, snd_opts);
486   tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
487
488   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->snd_nxt,
489                              tc->rcv_nxt, tcp_hdr_opts_len, flags, wnd);
490
491   tcp_options_write ((u8 *) (th + 1), snd_opts);
492   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
493 }
494
495 /**
496  * Convert buffer to ACK
497  */
498 void
499 tcp_make_ack (tcp_connection_t * tc, vlib_buffer_t * b)
500 {
501   vlib_main_t *vm = vlib_get_main ();
502
503   tcp_reuse_buffer (vm, b);
504   tcp_make_ack_i (tc, b, TCP_STATE_ESTABLISHED, TCP_FLAG_ACK);
505   TCP_EVT_DBG (TCP_EVT_ACK_SENT, tc);
506   vnet_buffer (b)->tcp.flags = TCP_BUF_FLAG_ACK;
507   tc->rcv_las = tc->rcv_nxt;
508 }
509
510 /**
511  * Convert buffer to FIN-ACK
512  */
513 void
514 tcp_make_fin (tcp_connection_t * tc, vlib_buffer_t * b)
515 {
516   vlib_main_t *vm = vlib_get_main ();
517   u8 flags = 0;
518
519   tcp_reuse_buffer (vm, b);
520
521   flags = TCP_FLAG_FIN | TCP_FLAG_ACK;
522   tcp_make_ack_i (tc, b, TCP_STATE_ESTABLISHED, flags);
523
524   /* Reset flags, make sure ack is sent */
525   vnet_buffer (b)->tcp.flags &= ~TCP_BUF_FLAG_DUPACK;
526
527   tc->snd_nxt += 1;
528 }
529
530 /**
531  * Convert buffer to SYN-ACK
532  */
533 void
534 tcp_make_synack (tcp_connection_t * tc, vlib_buffer_t * b)
535 {
536   vlib_main_t *vm = vlib_get_main ();
537   tcp_options_t _snd_opts, *snd_opts = &_snd_opts;
538   u8 tcp_opts_len, tcp_hdr_opts_len;
539   tcp_header_t *th;
540   u16 initial_wnd;
541   u32 time_now;
542
543   memset (snd_opts, 0, sizeof (*snd_opts));
544
545   tcp_reuse_buffer (vm, b);
546
547   /* Set random initial sequence */
548   time_now = tcp_time_now ();
549
550   tc->iss = random_u32 (&time_now);
551   tc->snd_una = tc->iss;
552   tc->snd_nxt = tc->iss + 1;
553   tc->snd_una_max = tc->snd_nxt;
554
555   initial_wnd = tcp_initial_window_to_advertise (tc);
556
557   /* Make and write options */
558   tcp_opts_len = tcp_make_synack_options (tc, snd_opts);
559   tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
560
561   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->iss,
562                              tc->rcv_nxt, tcp_hdr_opts_len,
563                              TCP_FLAG_SYN | TCP_FLAG_ACK, initial_wnd);
564
565   tcp_options_write ((u8 *) (th + 1), snd_opts);
566
567   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
568   vnet_buffer (b)->tcp.flags = TCP_BUF_FLAG_ACK;
569
570   /* Init retransmit timer */
571   tcp_retransmit_timer_set (tc);
572 }
573
574 always_inline void
575 tcp_enqueue_to_ip_lookup (vlib_main_t * vm, vlib_buffer_t * b, u32 bi,
576                           u8 is_ip4)
577 {
578   u32 *to_next, next_index;
579   vlib_frame_t *f;
580
581   b->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
582   b->error = 0;
583
584   /* Default FIB for now */
585   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
586
587   /* Send to IP lookup */
588   next_index = is_ip4 ? ip4_lookup_node.index : ip6_lookup_node.index;
589   f = vlib_get_frame_to_node (vm, next_index);
590
591   /* Enqueue the packet */
592   to_next = vlib_frame_vector_args (f);
593   to_next[0] = bi;
594   f->n_vectors = 1;
595   vlib_put_frame_to_node (vm, next_index, f);
596 }
597
598 int
599 tcp_make_reset_in_place (vlib_main_t * vm, vlib_buffer_t * b0,
600                          tcp_state_t state, u32 my_thread_index, u8 is_ip4)
601 {
602   u8 tcp_hdr_len = sizeof (tcp_header_t);
603   ip4_header_t *ih4;
604   ip6_header_t *ih6;
605   tcp_header_t *th0;
606   ip4_address_t src_ip40;
607   ip6_address_t src_ip60;
608   u16 src_port0;
609   u32 tmp;
610
611   /* Find IP and TCP headers */
612   if (is_ip4)
613     {
614       ih4 = vlib_buffer_get_current (b0);
615       th0 = ip4_next_header (ih4);
616     }
617   else
618     {
619       ih6 = vlib_buffer_get_current (b0);
620       th0 = ip6_next_header (ih6);
621     }
622
623   /* Swap src and dst ip */
624   if (is_ip4)
625     {
626       ASSERT ((ih4->ip_version_and_header_length & 0xF0) == 0x40);
627       src_ip40.as_u32 = ih4->src_address.as_u32;
628       ih4->src_address.as_u32 = ih4->dst_address.as_u32;
629       ih4->dst_address.as_u32 = src_ip40.as_u32;
630
631       /* Chop the end of the pkt */
632       b0->current_length += ip4_header_bytes (ih4) + tcp_hdr_len;
633     }
634   else
635     {
636       ASSERT ((ih6->ip_version_traffic_class_and_flow_label & 0xF0) == 0x60);
637       clib_memcpy (&src_ip60, &ih6->src_address, sizeof (ip6_address_t));
638       clib_memcpy (&ih6->src_address, &ih6->dst_address,
639                    sizeof (ip6_address_t));
640       clib_memcpy (&ih6->dst_address, &src_ip60, sizeof (ip6_address_t));
641
642       /* Chop the end of the pkt */
643       b0->current_length += sizeof (ip6_header_t) + tcp_hdr_len;
644     }
645
646   /* Try to determine what/why we're actually resetting and swap
647    * src and dst ports */
648   if (state == TCP_STATE_CLOSED)
649     {
650       if (!tcp_syn (th0))
651         return -1;
652
653       tmp = clib_net_to_host_u32 (th0->seq_number);
654
655       /* Got a SYN for no listener. */
656       th0->flags = TCP_FLAG_RST | TCP_FLAG_ACK;
657       th0->ack_number = clib_host_to_net_u32 (tmp + 1);
658       th0->seq_number = 0;
659
660     }
661   else if (state >= TCP_STATE_SYN_SENT)
662     {
663       th0->flags = TCP_FLAG_RST | TCP_FLAG_ACK;
664       th0->seq_number = th0->ack_number;
665       th0->ack_number = 0;
666     }
667
668   src_port0 = th0->src_port;
669   th0->src_port = th0->dst_port;
670   th0->dst_port = src_port0;
671   th0->window = 0;
672   th0->data_offset_and_reserved = (tcp_hdr_len >> 2) << 4;
673   th0->urgent_pointer = 0;
674
675   /* Compute checksum */
676   if (is_ip4)
677     {
678       th0->checksum = ip4_tcp_udp_compute_checksum (vm, b0, ih4);
679     }
680   else
681     {
682       int bogus = ~0;
683       th0->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b0, ih6, &bogus);
684       ASSERT (!bogus);
685     }
686
687   return 0;
688 }
689
690 /**
691  *  Send reset without reusing existing buffer
692  */
693 void
694 tcp_send_reset (vlib_buffer_t * pkt, u8 is_ip4)
695 {
696   vlib_buffer_t *b;
697   u32 bi;
698   tcp_main_t *tm = vnet_get_tcp_main ();
699   vlib_main_t *vm = vlib_get_main ();
700   u8 tcp_hdr_len, flags = 0;
701   tcp_header_t *th, *pkt_th;
702   u32 seq, ack;
703   ip4_header_t *ih4, *pkt_ih4;
704   ip6_header_t *ih6, *pkt_ih6;
705
706   tcp_get_free_buffer_index (tm, &bi);
707   b = vlib_get_buffer (vm, bi);
708
709   /* Leave enough space for headers */
710   vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
711
712   /* Make and write options */
713   tcp_hdr_len = sizeof (tcp_header_t);
714
715   if (is_ip4)
716     {
717       pkt_ih4 = vlib_buffer_get_current (pkt);
718       pkt_th = ip4_next_header (pkt_ih4);
719     }
720   else
721     {
722       pkt_ih6 = vlib_buffer_get_current (pkt);
723       pkt_th = ip6_next_header (pkt_ih6);
724     }
725
726   if (tcp_ack (pkt_th))
727     {
728       flags = TCP_FLAG_RST;
729       seq = pkt_th->ack_number;
730       ack = 0;
731     }
732   else
733     {
734       flags = TCP_FLAG_RST | TCP_FLAG_ACK;
735       seq = 0;
736       ack = clib_host_to_net_u32 (vnet_buffer (pkt)->tcp.seq_end);
737     }
738
739   th = vlib_buffer_push_tcp_net_order (b, pkt_th->dst_port, pkt_th->src_port,
740                                        seq, ack, tcp_hdr_len, flags, 0);
741
742   /* Swap src and dst ip */
743   if (is_ip4)
744     {
745       ASSERT ((pkt_ih4->ip_version_and_header_length & 0xF0) == 0x40);
746       ih4 = vlib_buffer_push_ip4 (vm, b, &pkt_ih4->dst_address,
747                                   &pkt_ih4->src_address, IP_PROTOCOL_TCP);
748       th->checksum = ip4_tcp_udp_compute_checksum (vm, b, ih4);
749     }
750   else
751     {
752       int bogus = ~0;
753       pkt_ih6 = (ip6_header_t *) (pkt_th - 1);
754       ASSERT ((pkt_ih6->ip_version_traffic_class_and_flow_label & 0xF0) ==
755               0x60);
756       ih6 =
757         vlib_buffer_push_ip6 (vm, b, &pkt_ih6->dst_address,
758                               &pkt_ih6->src_address, IP_PROTOCOL_TCP);
759       th->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b, ih6, &bogus);
760       ASSERT (!bogus);
761     }
762
763   tcp_enqueue_to_ip_lookup (vm, b, bi, is_ip4);
764 }
765
766 void
767 tcp_push_ip_hdr (tcp_main_t * tm, tcp_connection_t * tc, vlib_buffer_t * b)
768 {
769   tcp_header_t *th = vlib_buffer_get_current (b);
770
771   if (tc->c_is_ip4)
772     {
773       ip4_header_t *ih;
774       ih = vlib_buffer_push_ip4 (tm->vlib_main, b, &tc->c_lcl_ip4,
775                                  &tc->c_rmt_ip4, IP_PROTOCOL_TCP);
776       th->checksum = ip4_tcp_udp_compute_checksum (tm->vlib_main, b, ih);
777     }
778   else
779     {
780       ip6_header_t *ih;
781       int bogus = ~0;
782
783       ih = vlib_buffer_push_ip6 (tm->vlib_main, b, &tc->c_lcl_ip6,
784                                  &tc->c_rmt_ip6, IP_PROTOCOL_TCP);
785       th->checksum = ip6_tcp_udp_icmp_compute_checksum (tm->vlib_main, b, ih,
786                                                         &bogus);
787       ASSERT (!bogus);
788     }
789 }
790
791 /**
792  *  Send SYN
793  *
794  *  Builds a SYN packet for a half-open connection and sends it to ipx_lookup.
795  *  The packet is not forwarded through tcpx_output to avoid doing lookups
796  *  in the half_open pool.
797  */
798 void
799 tcp_send_syn (tcp_connection_t * tc)
800 {
801   vlib_buffer_t *b;
802   u32 bi;
803   tcp_main_t *tm = vnet_get_tcp_main ();
804   vlib_main_t *vm = vlib_get_main ();
805   u8 tcp_hdr_opts_len, tcp_opts_len;
806   tcp_header_t *th;
807   u32 time_now;
808   u16 initial_wnd;
809   tcp_options_t snd_opts;
810
811   tcp_get_free_buffer_index (tm, &bi);
812   b = vlib_get_buffer (vm, bi);
813
814   /* Leave enough space for headers */
815   vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
816
817   /* Set random initial sequence */
818   time_now = tcp_time_now ();
819
820   tc->iss = random_u32 (&time_now);
821   tc->snd_una = tc->iss;
822   tc->snd_una_max = tc->snd_nxt = tc->iss + 1;
823
824   initial_wnd = tcp_initial_window_to_advertise (tc);
825
826   /* Make and write options */
827   memset (&snd_opts, 0, sizeof (snd_opts));
828   tcp_opts_len = tcp_make_syn_options (&snd_opts, tc->rcv_wscale);
829   tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
830
831   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->iss,
832                              tc->rcv_nxt, tcp_hdr_opts_len, TCP_FLAG_SYN,
833                              initial_wnd);
834
835   tcp_options_write ((u8 *) (th + 1), &snd_opts);
836
837   /* Measure RTT with this */
838   tc->rtt_ts = tcp_time_now ();
839   tc->rtt_seq = tc->snd_nxt;
840
841   /* Start retransmit trimer  */
842   tcp_timer_set (tc, TCP_TIMER_RETRANSMIT_SYN, tc->rto * TCP_TO_TIMER_TICK);
843   tc->rto_boff = 0;
844
845   /* Set the connection establishment timer */
846   tcp_timer_set (tc, TCP_TIMER_ESTABLISH, TCP_ESTABLISH_TIME);
847
848   tcp_push_ip_hdr (tm, tc, b);
849   tcp_enqueue_to_ip_lookup (vm, b, bi, tc->c_is_ip4);
850 }
851
852 always_inline void
853 tcp_enqueue_to_output (vlib_main_t * vm, vlib_buffer_t * b, u32 bi, u8 is_ip4)
854 {
855   u32 *to_next, next_index;
856   vlib_frame_t *f;
857
858   b->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
859   b->error = 0;
860
861   /* Decide where to send the packet */
862   next_index = is_ip4 ? tcp4_output_node.index : tcp6_output_node.index;
863
864   /* Enqueue the packet */
865   f = vlib_get_frame_to_node (vm, next_index);
866   to_next = vlib_frame_vector_args (f);
867   to_next[0] = bi;
868   f->n_vectors = 1;
869   vlib_put_frame_to_node (vm, next_index, f);
870 }
871
872 /**
873  *  Send FIN
874  */
875 void
876 tcp_send_fin (tcp_connection_t * tc)
877 {
878   vlib_buffer_t *b;
879   u32 bi;
880   tcp_main_t *tm = vnet_get_tcp_main ();
881   vlib_main_t *vm = vlib_get_main ();
882
883   tcp_get_free_buffer_index (tm, &bi);
884   b = vlib_get_buffer (vm, bi);
885
886   /* Leave enough space for headers */
887   vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
888
889   tcp_make_fin (tc, b);
890   tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
891   tc->flags |= TCP_CONN_FINSNT;
892   TCP_EVT_DBG (TCP_EVT_FIN_SENT, tc);
893 }
894
895 always_inline u8
896 tcp_make_state_flags (tcp_state_t next_state)
897 {
898   switch (next_state)
899     {
900     case TCP_STATE_ESTABLISHED:
901       return TCP_FLAG_ACK;
902     case TCP_STATE_SYN_RCVD:
903       return TCP_FLAG_SYN | TCP_FLAG_ACK;
904     case TCP_STATE_SYN_SENT:
905       return TCP_FLAG_SYN;
906     case TCP_STATE_LAST_ACK:
907     case TCP_STATE_FIN_WAIT_1:
908       return TCP_FLAG_FIN;
909     default:
910       clib_warning ("Shouldn't be here!");
911     }
912   return 0;
913 }
914
915 /**
916  * Push TCP header and update connection variables
917  */
918 static void
919 tcp_push_hdr_i (tcp_connection_t * tc, vlib_buffer_t * b,
920                 tcp_state_t next_state, u8 compute_opts)
921 {
922   u32 advertise_wnd, data_len;
923   u8 tcp_hdr_opts_len, opts_write_len, flags;
924   tcp_header_t *th;
925
926   data_len = b->current_length + b->total_length_not_including_first_buffer;
927   vnet_buffer (b)->tcp.flags = 0;
928
929   if (compute_opts)
930     tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts, tc->state);
931
932   /* Write pre-computed options */
933   tcp_hdr_opts_len = tc->snd_opts_len + sizeof (tcp_header_t);
934
935   /* Get rcv window to advertise */
936   advertise_wnd = tcp_window_to_advertise (tc, next_state);
937   flags = tcp_make_state_flags (next_state);
938
939   /* Push header and options */
940   th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->snd_nxt,
941                              tc->rcv_nxt, tcp_hdr_opts_len, flags,
942                              advertise_wnd);
943
944   opts_write_len = tcp_options_write ((u8 *) (th + 1), &tc->snd_opts);
945
946   ASSERT (opts_write_len == tc->snd_opts_len);
947
948   /* Tag the buffer with the connection index  */
949   vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
950
951   tc->snd_nxt += data_len;
952   tc->rcv_las = tc->rcv_nxt;
953
954   /* TODO this is updated in output as well ... */
955   if (tc->snd_nxt > tc->snd_una_max)
956     tc->snd_una_max = tc->snd_nxt;
957
958   if (tc->rtt_ts == 0)
959     {
960       tc->rtt_ts = tcp_time_now ();
961       tc->rtt_seq = tc->snd_nxt;
962     }
963   TCP_EVT_DBG (TCP_EVT_PKTIZE, tc);
964 }
965
966 void
967 tcp_send_ack (tcp_connection_t * tc)
968 {
969   tcp_main_t *tm = vnet_get_tcp_main ();
970   vlib_main_t *vm = vlib_get_main ();
971
972   vlib_buffer_t *b;
973   u32 bi;
974
975   /* Get buffer */
976   tcp_get_free_buffer_index (tm, &bi);
977   b = vlib_get_buffer (vm, bi);
978
979   /* Fill in the ACK */
980   tcp_make_ack (tc, b);
981   tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
982 }
983
984 /* Send delayed ACK when timer expires */
985 void
986 tcp_timer_delack_handler (u32 index)
987 {
988   u32 thread_index = vlib_get_thread_index ();
989   tcp_connection_t *tc;
990
991   tc = tcp_connection_get (index, thread_index);
992   tc->timers[TCP_TIMER_DELACK] = TCP_TIMER_HANDLE_INVALID;
993   tcp_send_ack (tc);
994 }
995
996 /** Build a retransmit segment
997  *
998  * @return the number of bytes in the segment or 0 if there's nothing to
999  *         retransmit
1000  * */
1001 u32
1002 tcp_prepare_retransmit_segment (tcp_connection_t * tc, vlib_buffer_t * b,
1003                                 u32 offset, u32 max_bytes)
1004 {
1005   vlib_main_t *vm = vlib_get_main ();
1006   u32 n_bytes = 0;
1007
1008   tcp_reuse_buffer (vm, b);
1009
1010   ASSERT (tc->state >= TCP_STATE_ESTABLISHED);
1011   ASSERT (max_bytes != 0);
1012
1013   max_bytes = clib_min (tc->snd_mss, max_bytes);
1014
1015   /* Start is beyond snd_congestion */
1016   if (seq_geq (tc->snd_una + offset, tc->snd_congestion))
1017     goto done;
1018
1019   /* Don't overshoot snd_congestion */
1020   if (seq_gt (tc->snd_nxt + max_bytes, tc->snd_congestion))
1021     {
1022       max_bytes = tc->snd_congestion - tc->snd_nxt;
1023       if (max_bytes == 0)
1024         goto done;
1025     }
1026
1027   tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts, tc->state);
1028
1029   ASSERT (max_bytes <= tc->snd_mss);
1030
1031   n_bytes = stream_session_peek_bytes (&tc->connection,
1032                                        vlib_buffer_get_current (b), offset,
1033                                        max_bytes);
1034   ASSERT (n_bytes != 0);
1035   b->current_length = n_bytes;
1036   tcp_push_hdr_i (tc, b, tc->state, 0);
1037   tc->rtx_bytes += n_bytes;
1038
1039 done:
1040   TCP_EVT_DBG (TCP_EVT_CC_RTX, tc, offset, n_bytes);
1041   return n_bytes;
1042 }
1043
1044 /**
1045  * Reset congestion control, switch cwnd to loss window and try again.
1046  */
1047 static void
1048 tcp_rtx_timeout_cc (tcp_connection_t * tc)
1049 {
1050   /* Cleanly recover cc (also clears up fast retransmit) */
1051   if (tcp_in_fastrecovery (tc))
1052     {
1053       tcp_cc_recover (tc);
1054     }
1055   else
1056     {
1057       tc->ssthresh = clib_max (tcp_flight_size (tc) / 2, 2 * tc->snd_mss);
1058     }
1059
1060   /* Start again from the beginning */
1061
1062   tc->cwnd = tcp_loss_wnd (tc);
1063   tc->snd_congestion = tc->snd_una_max;
1064   tcp_recovery_on (tc);
1065 }
1066
1067 static void
1068 tcp_timer_retransmit_handler_i (u32 index, u8 is_syn)
1069 {
1070   tcp_main_t *tm = vnet_get_tcp_main ();
1071   vlib_main_t *vm = vlib_get_main ();
1072   u32 thread_index = vlib_get_thread_index ();
1073   tcp_connection_t *tc;
1074   vlib_buffer_t *b;
1075   u32 bi, n_bytes;
1076
1077   if (is_syn)
1078     {
1079       tc = tcp_half_open_connection_get (index);
1080     }
1081   else
1082     {
1083       tc = tcp_connection_get (index, thread_index);
1084     }
1085
1086   /* Make sure timer handle is set to invalid */
1087   tc->timers[TCP_TIMER_RETRANSMIT] = TCP_TIMER_HANDLE_INVALID;
1088
1089   /* Increment RTO backoff (also equal to number of retries) */
1090   tc->rto_boff += 1;
1091
1092   /* Go back to first un-acked byte */
1093   tc->snd_nxt = tc->snd_una;
1094
1095   /* Get buffer */
1096   tcp_get_free_buffer_index (tm, &bi);
1097   b = vlib_get_buffer (vm, bi);
1098
1099   if (tc->state >= TCP_STATE_ESTABLISHED)
1100     {
1101       /* First retransmit timeout */
1102       if (tc->rto_boff == 1)
1103         tcp_rtx_timeout_cc (tc);
1104
1105       /* Exponential backoff */
1106       tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1107
1108       TCP_EVT_DBG (TCP_EVT_CC_EVT, tc, 1);
1109
1110       /* Send one segment. No fancy recovery for now! */
1111       n_bytes = tcp_prepare_retransmit_segment (tc, b, 0, tc->snd_mss);
1112       scoreboard_clear (&tc->sack_sb);
1113
1114       if (n_bytes == 0)
1115         {
1116           clib_warning ("could not retransmit");
1117           return;
1118         }
1119     }
1120   else
1121     {
1122       /* Retransmit for SYN/SYNACK */
1123       ASSERT (tc->state == TCP_STATE_SYN_RCVD
1124               || tc->state == TCP_STATE_SYN_SENT);
1125
1126       /* Try without increasing RTO a number of times. If this fails,
1127        * start growing RTO exponentially */
1128       if (tc->rto_boff > TCP_RTO_SYN_RETRIES)
1129         tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1130
1131       vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
1132
1133       tcp_push_hdr_i (tc, b, tc->state, 1);
1134
1135       /* Account for the SYN */
1136       tc->snd_nxt += 1;
1137     }
1138
1139   if (!is_syn)
1140     {
1141       tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
1142
1143       /* Re-enable retransmit timer */
1144       tcp_retransmit_timer_set (tc);
1145     }
1146   else
1147     {
1148       ASSERT (tc->state == TCP_STATE_SYN_SENT);
1149
1150       TCP_EVT_DBG (TCP_EVT_SYN_RTX, tc);
1151
1152       /* This goes straight to ipx_lookup */
1153       tcp_push_ip_hdr (tm, tc, b);
1154       tcp_enqueue_to_ip_lookup (vm, b, bi, tc->c_is_ip4);
1155
1156       /* Re-enable retransmit timer */
1157       tcp_timer_set (tc, TCP_TIMER_RETRANSMIT_SYN,
1158                      tc->rto * TCP_TO_TIMER_TICK);
1159     }
1160 }
1161
1162 void
1163 tcp_timer_retransmit_handler (u32 index)
1164 {
1165   tcp_timer_retransmit_handler_i (index, 0);
1166 }
1167
1168 void
1169 tcp_timer_retransmit_syn_handler (u32 index)
1170 {
1171   tcp_timer_retransmit_handler_i (index, 1);
1172 }
1173
1174 /**
1175  * Got 0 snd_wnd from peer, try to do something about it.
1176  *
1177  */
1178 void
1179 tcp_timer_persist_handler (u32 index)
1180 {
1181   tcp_main_t *tm = vnet_get_tcp_main ();
1182   vlib_main_t *vm = vlib_get_main ();
1183   u32 thread_index = vlib_get_thread_index ();
1184   tcp_connection_t *tc;
1185   vlib_buffer_t *b;
1186   u32 bi, n_bytes;
1187
1188   tc = tcp_connection_get (index, thread_index);
1189
1190   /* Make sure timer handle is set to invalid */
1191   tc->timers[TCP_TIMER_PERSIST] = TCP_TIMER_HANDLE_INVALID;
1192
1193   /* Problem already solved or worse */
1194   if (tc->snd_wnd > tc->snd_mss || tcp_in_recovery (tc))
1195     return;
1196
1197   /* Increment RTO backoff */
1198   tc->rto_boff += 1;
1199   tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
1200
1201   /* Try to force the first unsent segment  */
1202   tcp_get_free_buffer_index (tm, &bi);
1203   b = vlib_get_buffer (vm, bi);
1204   tc->snd_opts_len = tcp_make_options (tc, &tc->snd_opts, tc->state);
1205   n_bytes = stream_session_peek_bytes (&tc->connection,
1206                                        vlib_buffer_get_current (b),
1207                                        tc->snd_una_max - tc->snd_una,
1208                                        tc->snd_mss);
1209   /* Nothing to send */
1210   if (n_bytes == 0)
1211     {
1212       tcp_return_buffer (tm);
1213       return;
1214     }
1215
1216   b->current_length = n_bytes;
1217   tcp_push_hdr_i (tc, b, tc->state, 0);
1218   tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
1219
1220   /* Re-enable persist timer */
1221   tcp_persist_timer_set (tc);
1222 }
1223
1224 /**
1225  * Retransmit first unacked segment
1226  */
1227 void
1228 tcp_retransmit_first_unacked (tcp_connection_t * tc)
1229 {
1230   tcp_main_t *tm = vnet_get_tcp_main ();
1231   vlib_main_t *vm = vlib_get_main ();
1232   vlib_buffer_t *b;
1233   u32 bi, n_bytes;
1234
1235   tc->snd_nxt = tc->snd_una;
1236
1237   /* Get buffer */
1238   tcp_get_free_buffer_index (tm, &bi);
1239   b = vlib_get_buffer (vm, bi);
1240
1241   TCP_EVT_DBG (TCP_EVT_CC_EVT, tc, 2);
1242
1243   n_bytes = tcp_prepare_retransmit_segment (tc, b, 0, tc->snd_mss);
1244   if (n_bytes == 0)
1245     goto done;
1246
1247   tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
1248
1249 done:
1250   tc->snd_nxt = tc->snd_una_max;
1251 }
1252
1253 sack_scoreboard_hole_t *
1254 scoreboard_first_rtx_hole (sack_scoreboard_t * sb)
1255 {
1256   sack_scoreboard_hole_t *hole = 0;
1257
1258 //  hole = scoreboard_first_hole (&tc->sack_sb);
1259 //  if (hole)
1260 //    {
1261 //
1262 //      offset = hole->start - tc->snd_una;
1263 //      hole_size = hole->end - hole->start;
1264 //
1265 //      ASSERT(hole_size);
1266 //
1267 //      if (hole_size < max_bytes)
1268 //      max_bytes = hole_size;
1269 //    }
1270   return hole;
1271 }
1272
1273 /**
1274  * Do fast retransmit.
1275  */
1276 void
1277 tcp_fast_retransmit (tcp_connection_t * tc)
1278 {
1279   tcp_main_t *tm = vnet_get_tcp_main ();
1280   vlib_main_t *vm = vlib_get_main ();
1281   u32 bi;
1282   int snd_space;
1283   u32 n_written = 0, offset = 0;
1284   vlib_buffer_t *b;
1285   u8 use_sacks = 0;
1286
1287   ASSERT (tcp_in_fastrecovery (tc));
1288
1289   /* Start resending from first un-acked segment */
1290   tc->snd_nxt = tc->snd_una;
1291
1292   snd_space = tcp_available_snd_space (tc);
1293   TCP_EVT_DBG (TCP_EVT_CC_EVT, tc, 0);
1294
1295   /* If we have SACKs use them */
1296   if (tcp_opts_sack_permitted (&tc->opt)
1297       && scoreboard_first_hole (&tc->sack_sb))
1298     use_sacks = 0;
1299
1300   while (snd_space > 0)
1301     {
1302       tcp_get_free_buffer_index (tm, &bi);
1303       b = vlib_get_buffer (vm, bi);
1304
1305       if (use_sacks)
1306         {
1307           scoreboard_first_rtx_hole (&tc->sack_sb);
1308         }
1309       else
1310         {
1311           offset += n_written;
1312         }
1313
1314       n_written = tcp_prepare_retransmit_segment (tc, b, offset, snd_space);
1315
1316       /* Nothing left to retransmit */
1317       if (n_written == 0)
1318         {
1319           tcp_return_buffer (tm);
1320           break;
1321         }
1322
1323       tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
1324       snd_space -= n_written;
1325     }
1326
1327   /* If window allows, send 1 SMSS of new data */
1328   if (seq_lt (tc->snd_nxt, tc->snd_congestion))
1329     tc->snd_nxt = tc->snd_congestion;
1330 }
1331
1332 always_inline u32
1333 tcp_session_has_ooo_data (tcp_connection_t * tc)
1334 {
1335   stream_session_t *s =
1336     stream_session_get (tc->c_s_index, tc->c_thread_index);
1337   return svm_fifo_has_ooo_data (s->server_rx_fifo);
1338 }
1339
1340 always_inline uword
1341 tcp46_output_inline (vlib_main_t * vm,
1342                      vlib_node_runtime_t * node,
1343                      vlib_frame_t * from_frame, int is_ip4)
1344 {
1345   u32 n_left_from, next_index, *from, *to_next;
1346   u32 my_thread_index = vm->thread_index;
1347
1348   from = vlib_frame_vector_args (from_frame);
1349   n_left_from = from_frame->n_vectors;
1350
1351   next_index = node->cached_next_index;
1352
1353   while (n_left_from > 0)
1354     {
1355       u32 n_left_to_next;
1356
1357       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1358
1359       while (n_left_from > 0 && n_left_to_next > 0)
1360         {
1361           u32 bi0;
1362           vlib_buffer_t *b0;
1363           tcp_connection_t *tc0;
1364           tcp_tx_trace_t *t0;
1365           tcp_header_t *th0 = 0;
1366           u32 error0 = TCP_ERROR_PKTS_SENT, next0 = TCP_OUTPUT_NEXT_IP_LOOKUP;
1367
1368           bi0 = from[0];
1369           to_next[0] = bi0;
1370           from += 1;
1371           to_next += 1;
1372           n_left_from -= 1;
1373           n_left_to_next -= 1;
1374
1375           b0 = vlib_get_buffer (vm, bi0);
1376           tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
1377                                     my_thread_index);
1378           if (PREDICT_FALSE (tc0 == 0 || tc0->state == TCP_STATE_CLOSED))
1379             {
1380               error0 = TCP_ERROR_INVALID_CONNECTION;
1381               next0 = TCP_OUTPUT_NEXT_DROP;
1382               goto done;
1383             }
1384
1385           th0 = vlib_buffer_get_current (b0);
1386           TCP_EVT_DBG (TCP_EVT_OUTPUT, tc0, th0->flags, b0->current_length);
1387
1388           if (is_ip4)
1389             {
1390               ip4_header_t *ih0;
1391               ih0 = vlib_buffer_push_ip4 (vm, b0, &tc0->c_lcl_ip4,
1392                                           &tc0->c_rmt_ip4, IP_PROTOCOL_TCP);
1393               th0->checksum = ip4_tcp_udp_compute_checksum (vm, b0, ih0);
1394             }
1395           else
1396             {
1397               ip6_header_t *ih0;
1398               int bogus = ~0;
1399
1400               ih0 = vlib_buffer_push_ip6 (vm, b0, &tc0->c_lcl_ip6,
1401                                           &tc0->c_rmt_ip6, IP_PROTOCOL_TCP);
1402               th0->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b0, ih0,
1403                                                                  &bogus);
1404               ASSERT (!bogus);
1405             }
1406
1407           /* Filter out DUPACKs if there are no OOO segments left */
1408           if (PREDICT_FALSE
1409               (vnet_buffer (b0)->tcp.flags & TCP_BUF_FLAG_DUPACK))
1410             {
1411               if (!tcp_session_has_ooo_data (tc0))
1412                 {
1413                   error0 = TCP_ERROR_FILTERED_DUPACKS;
1414                   next0 = TCP_OUTPUT_NEXT_DROP;
1415                   goto done;
1416                 }
1417             }
1418
1419           /* Stop DELACK timer and fix flags */
1420           tc0->flags &= ~(TCP_CONN_SNDACK);
1421           if (tcp_timer_is_active (tc0, TCP_TIMER_DELACK))
1422             {
1423               tcp_timer_reset (tc0, TCP_TIMER_DELACK);
1424             }
1425
1426           /* If not retransmitting
1427            * 1) update snd_una_max (SYN, SYNACK, FIN)
1428            * 2) If we're not tracking an ACK, start tracking */
1429           if (seq_lt (tc0->snd_una_max, tc0->snd_nxt))
1430             {
1431               tc0->snd_una_max = tc0->snd_nxt;
1432               if (tc0->rtt_ts == 0)
1433                 {
1434                   tc0->rtt_ts = tcp_time_now ();
1435                   tc0->rtt_seq = tc0->snd_nxt;
1436                 }
1437             }
1438
1439           /* Set the retransmit timer if not set already and not
1440            * doing a pure ACK */
1441           if (!tcp_timer_is_active (tc0, TCP_TIMER_RETRANSMIT)
1442               && tc0->snd_nxt != tc0->snd_una)
1443             {
1444               tcp_retransmit_timer_set (tc0);
1445               tc0->rto_boff = 0;
1446             }
1447
1448           /* set fib index to default and lookup node */
1449           /* XXX network virtualization (vrf/vni) */
1450           vnet_buffer (b0)->sw_if_index[VLIB_RX] = 0;
1451           vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
1452
1453           b0->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
1454         done:
1455           b0->error = node->errors[error0];
1456           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1457             {
1458               t0 = vlib_add_trace (vm, node, b0, sizeof (*t0));
1459               if (th0)
1460                 {
1461                   clib_memcpy (&t0->tcp_header, th0, sizeof (t0->tcp_header));
1462                 }
1463               else
1464                 {
1465                   memset (&t0->tcp_header, 0, sizeof (t0->tcp_header));
1466                 }
1467               clib_memcpy (&t0->tcp_connection, tc0,
1468                            sizeof (t0->tcp_connection));
1469             }
1470
1471           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
1472                                            n_left_to_next, bi0, next0);
1473         }
1474
1475       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1476     }
1477
1478   return from_frame->n_vectors;
1479 }
1480
1481 static uword
1482 tcp4_output (vlib_main_t * vm, vlib_node_runtime_t * node,
1483              vlib_frame_t * from_frame)
1484 {
1485   return tcp46_output_inline (vm, node, from_frame, 1 /* is_ip4 */ );
1486 }
1487
1488 static uword
1489 tcp6_output (vlib_main_t * vm, vlib_node_runtime_t * node,
1490              vlib_frame_t * from_frame)
1491 {
1492   return tcp46_output_inline (vm, node, from_frame, 0 /* is_ip4 */ );
1493 }
1494
1495 /* *INDENT-OFF* */
1496 VLIB_REGISTER_NODE (tcp4_output_node) =
1497 {
1498   .function = tcp4_output,.name = "tcp4-output",
1499     /* Takes a vector of packets. */
1500     .vector_size = sizeof (u32),
1501     .n_errors = TCP_N_ERROR,
1502     .error_strings = tcp_error_strings,
1503     .n_next_nodes = TCP_OUTPUT_N_NEXT,
1504     .next_nodes = {
1505 #define _(s,n) [TCP_OUTPUT_NEXT_##s] = n,
1506     foreach_tcp4_output_next
1507 #undef _
1508     },
1509     .format_buffer = format_tcp_header,
1510     .format_trace = format_tcp_tx_trace,
1511 };
1512 /* *INDENT-ON* */
1513
1514 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_output_node, tcp4_output);
1515
1516 /* *INDENT-OFF* */
1517 VLIB_REGISTER_NODE (tcp6_output_node) =
1518 {
1519   .function = tcp6_output,
1520   .name = "tcp6-output",
1521     /* Takes a vector of packets. */
1522   .vector_size = sizeof (u32),
1523   .n_errors = TCP_N_ERROR,
1524   .error_strings = tcp_error_strings,
1525   .n_next_nodes = TCP_OUTPUT_N_NEXT,
1526   .next_nodes = {
1527 #define _(s,n) [TCP_OUTPUT_NEXT_##s] = n,
1528     foreach_tcp6_output_next
1529 #undef _
1530   },
1531   .format_buffer = format_tcp_header,
1532   .format_trace = format_tcp_tx_trace,
1533 };
1534 /* *INDENT-ON* */
1535
1536 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_output_node, tcp6_output);
1537
1538 u32
1539 tcp_push_header (transport_connection_t * tconn, vlib_buffer_t * b)
1540 {
1541   tcp_connection_t *tc;
1542
1543   tc = (tcp_connection_t *) tconn;
1544   tcp_push_hdr_i (tc, b, TCP_STATE_ESTABLISHED, 0);
1545   return 0;
1546 }
1547
1548 typedef enum _tcp_reset_next
1549 {
1550   TCP_RESET_NEXT_DROP,
1551   TCP_RESET_NEXT_IP_LOOKUP,
1552   TCP_RESET_N_NEXT
1553 } tcp_reset_next_t;
1554
1555 #define foreach_tcp4_reset_next         \
1556   _(DROP, "error-drop")                 \
1557   _(IP_LOOKUP, "ip4-lookup")
1558
1559 #define foreach_tcp6_reset_next         \
1560   _(DROP, "error-drop")                 \
1561   _(IP_LOOKUP, "ip6-lookup")
1562
1563 static uword
1564 tcp46_send_reset_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
1565                          vlib_frame_t * from_frame, u8 is_ip4)
1566 {
1567   u32 n_left_from, next_index, *from, *to_next;
1568   u32 my_thread_index = vm->thread_index;
1569
1570   from = vlib_frame_vector_args (from_frame);
1571   n_left_from = from_frame->n_vectors;
1572
1573   next_index = node->cached_next_index;
1574
1575   while (n_left_from > 0)
1576     {
1577       u32 n_left_to_next;
1578
1579       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1580
1581       while (n_left_from > 0 && n_left_to_next > 0)
1582         {
1583           u32 bi0;
1584           vlib_buffer_t *b0;
1585           tcp_tx_trace_t *t0;
1586           tcp_header_t *th0;
1587           u32 error0 = TCP_ERROR_RST_SENT, next0 = TCP_RESET_NEXT_IP_LOOKUP;
1588
1589           bi0 = from[0];
1590           to_next[0] = bi0;
1591           from += 1;
1592           to_next += 1;
1593           n_left_from -= 1;
1594           n_left_to_next -= 1;
1595
1596           b0 = vlib_get_buffer (vm, bi0);
1597
1598           if (tcp_make_reset_in_place (vm, b0, vnet_buffer (b0)->tcp.flags,
1599                                        my_thread_index, is_ip4))
1600             {
1601               error0 = TCP_ERROR_LOOKUP_DROPS;
1602               next0 = TCP_RESET_NEXT_DROP;
1603               goto done;
1604             }
1605
1606           /* Prepare to send to IP lookup */
1607           vnet_buffer (b0)->sw_if_index[VLIB_TX] = 0;
1608           next0 = TCP_RESET_NEXT_IP_LOOKUP;
1609
1610         done:
1611           b0->error = node->errors[error0];
1612           b0->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
1613           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1614             {
1615               th0 = vlib_buffer_get_current (b0);
1616               if (is_ip4)
1617                 th0 = ip4_next_header ((ip4_header_t *) th0);
1618               else
1619                 th0 = ip6_next_header ((ip6_header_t *) th0);
1620               t0 = vlib_add_trace (vm, node, b0, sizeof (*t0));
1621               clib_memcpy (&t0->tcp_header, th0, sizeof (t0->tcp_header));
1622             }
1623
1624           vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
1625                                            n_left_to_next, bi0, next0);
1626         }
1627       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1628     }
1629   return from_frame->n_vectors;
1630 }
1631
1632 static uword
1633 tcp4_send_reset (vlib_main_t * vm, vlib_node_runtime_t * node,
1634                  vlib_frame_t * from_frame)
1635 {
1636   return tcp46_send_reset_inline (vm, node, from_frame, 1);
1637 }
1638
1639 static uword
1640 tcp6_send_reset (vlib_main_t * vm, vlib_node_runtime_t * node,
1641                  vlib_frame_t * from_frame)
1642 {
1643   return tcp46_send_reset_inline (vm, node, from_frame, 0);
1644 }
1645
1646 /* *INDENT-OFF* */
1647 VLIB_REGISTER_NODE (tcp4_reset_node) = {
1648   .function = tcp4_send_reset,
1649   .name = "tcp4-reset",
1650   .vector_size = sizeof (u32),
1651   .n_errors = TCP_N_ERROR,
1652   .error_strings = tcp_error_strings,
1653   .n_next_nodes = TCP_RESET_N_NEXT,
1654   .next_nodes = {
1655 #define _(s,n) [TCP_RESET_NEXT_##s] = n,
1656     foreach_tcp4_reset_next
1657 #undef _
1658   },
1659   .format_trace = format_tcp_tx_trace,
1660 };
1661 /* *INDENT-ON* */
1662
1663 VLIB_NODE_FUNCTION_MULTIARCH (tcp4_reset_node, tcp4_send_reset);
1664
1665 /* *INDENT-OFF* */
1666 VLIB_REGISTER_NODE (tcp6_reset_node) = {
1667   .function = tcp6_send_reset,
1668   .name = "tcp6-reset",
1669   .vector_size = sizeof (u32),
1670   .n_errors = TCP_N_ERROR,
1671   .error_strings = tcp_error_strings,
1672   .n_next_nodes = TCP_RESET_N_NEXT,
1673   .next_nodes = {
1674 #define _(s,n) [TCP_RESET_NEXT_##s] = n,
1675     foreach_tcp6_reset_next
1676 #undef _
1677   },
1678   .format_trace = format_tcp_tx_trace,
1679 };
1680 /* *INDENT-ON* */
1681
1682 VLIB_NODE_FUNCTION_MULTIARCH (tcp6_reset_node, tcp6_send_reset);
1683
1684 /*
1685  * fd.io coding-style-patch-verification: ON
1686  *
1687  * Local Variables:
1688  * eval: (c-set-style "gnu")
1689  * End:
1690  */