VPP-598: tcp stack initial commit 61/5561/7
authorDave Barach <dave@barachs.net>
Tue, 28 Feb 2017 20:15:56 +0000 (15:15 -0500)
committerDamjan Marion <dmarion.lists@gmail.com>
Wed, 1 Mar 2017 20:25:48 +0000 (20:25 +0000)
Change-Id: I49e5ce0aae6e4ff634024387ceaf7dbc432a0351
Signed-off-by: Dave Barach <dave@barachs.net>
Signed-off-by: Florin Coras <fcoras@cisco.com>
94 files changed:
src/Makefile.am
src/plugins/ioam/export-common/ioam_export.h
src/plugins/ioam/ipfixcollector/ipfixcollector.c
src/plugins/ioam/lib-vxlan-gpe/ioam_transit.c
src/plugins/snat/in2out.c
src/plugins/snat/out2in.c
src/scripts/vnet/tcp
src/scripts/vnet/udp [new file with mode: 0644]
src/scripts/vnet/uri/tcp-setup.sh [new file with mode: 0755]
src/scripts/vnet/uri/tcp_server [new file with mode: 0644]
src/scripts/vnet/uri/udp [new file with mode: 0644]
src/svm.am
src/svm/ssvm.c
src/svm/ssvm.h
src/svm/svm_fifo.c [new file with mode: 0644]
src/svm/svm_fifo.h [new file with mode: 0644]
src/svm/svm_fifo_segment.c [new file with mode: 0644]
src/svm/svm_fifo_segment.h [new file with mode: 0644]
src/svm/test_svm_fifo1.c [new file with mode: 0644]
src/uri.am [new file with mode: 0644]
src/uri/uri_tcp_test.c [new file with mode: 0644]
src/uri/uri_udp_test.c [new file with mode: 0644]
src/uri/uri_udp_test2.c [new file with mode: 0644]
src/uri/uritest.c [new file with mode: 0644]
src/vlib/buffer.c
src/vlib/buffer.h
src/vlibmemory/unix_shared_memory_queue.c
src/vlibmemory/unix_shared_memory_queue.h
src/vnet.am
src/vnet/api_errno.h
src/vnet/bfd/bfd_udp.c
src/vnet/buffer.h
src/vnet/classify/vnet_classify.c
src/vnet/dhcp/dhcp_proxy.h
src/vnet/flow/flow_report.h
src/vnet/ip/ip.h
src/vnet/ip/ip4.h
src/vnet/ip/ip4_forward.c
src/vnet/ip/ip4_packet.h
src/vnet/ip/ip6.h
src/vnet/ip/ip6_packet.h
src/vnet/ip/punt.c
src/vnet/ip/tcp_packet.h [deleted file]
src/vnet/ip/udp_init.c [deleted file]
src/vnet/ipsec/ikev2.c
src/vnet/ipsec/ikev2_cli.c
src/vnet/ipsec/ikev2_crypto.c
src/vnet/lisp-cp/packets.c
src/vnet/lisp-cp/packets.h
src/vnet/lisp-gpe/interface.c
src/vnet/lisp-gpe/lisp_gpe.h
src/vnet/lisp-gpe/lisp_gpe_adjacency.c
src/vnet/session/application.c [new file with mode: 0644]
src/vnet/session/application.h [new file with mode: 0644]
src/vnet/session/application_interface.c [new file with mode: 0644]
src/vnet/session/application_interface.h [new file with mode: 0644]
src/vnet/session/hashes.c [new file with mode: 0644]
src/vnet/session/node.c [new file with mode: 0644]
src/vnet/session/session.api [new file with mode: 0644]
src/vnet/session/session.c [new file with mode: 0644]
src/vnet/session/session.h [new file with mode: 0644]
src/vnet/session/session_api.c [new file with mode: 0644]
src/vnet/session/session_cli.c [new file with mode: 0644]
src/vnet/session/transport.c [new file with mode: 0644]
src/vnet/session/transport.h [new file with mode: 0644]
src/vnet/tcp/tcp.c [new file with mode: 0644]
src/vnet/tcp/tcp.h [new file with mode: 0644]
src/vnet/tcp/tcp_error.def [new file with mode: 0644]
src/vnet/tcp/tcp_format.c [new file with mode: 0644]
src/vnet/tcp/tcp_input.c [new file with mode: 0644]
src/vnet/tcp/tcp_newreno.c [new file with mode: 0644]
src/vnet/tcp/tcp_output.c [new file with mode: 0644]
src/vnet/tcp/tcp_packet.h [new file with mode: 0644]
src/vnet/tcp/tcp_pg.c [new file with mode: 0644]
src/vnet/tcp/tcp_syn_filter4.c [new file with mode: 0644]
src/vnet/tcp/tcp_timer.h [new file with mode: 0644]
src/vnet/udp/builtin_server.c [new file with mode: 0644]
src/vnet/udp/udp.c [new file with mode: 0644]
src/vnet/udp/udp.h [moved from src/vnet/ip/udp.h with 85% similarity]
src/vnet/udp/udp_error.def [moved from src/vnet/ip/udp_error.def with 100% similarity]
src/vnet/udp/udp_format.c [moved from src/vnet/ip/udp_format.c with 100% similarity]
src/vnet/udp/udp_input.c [new file with mode: 0644]
src/vnet/udp/udp_local.c [moved from src/vnet/ip/udp_local.c with 96% similarity]
src/vnet/udp/udp_packet.h [moved from src/vnet/ip/udp_packet.h with 100% similarity]
src/vnet/udp/udp_pg.c [moved from src/vnet/ip/udp_pg.c with 100% similarity]
src/vnet/vnet_all_api_h.h
src/vnet/vxlan-gpe/vxlan_gpe.h
src/vnet/vxlan/vxlan.h
src/vpp/api/vpe.api
src/vppinfra.am
src/vppinfra/bihash_16_8.h [new file with mode: 0644]
src/vppinfra/bihash_48_8.h [new file with mode: 0644]
src/vppinfra/tw_timer_16t_1w_2048sl.c [new file with mode: 0644]
src/vppinfra/tw_timer_16t_1w_2048sl.h [new file with mode: 0644]

index 08feb29..641707e 100644 (file)
@@ -88,6 +88,7 @@ include vlib-api.am
 include vnet.am
 include vpp.am
 include vpp-api-test.am
+include uri.am
 
 SUBDIRS += plugins
 
index e84dab0..dd48a93 100644 (file)
@@ -21,7 +21,7 @@
 #include <vnet/ip/ip4_packet.h>
 #include <vnet/ip/ip6_packet.h>
 #include <vnet/ip/ip6_hop_by_hop.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/flow/ipfix_packet.h>
 
 #include <vppinfra/pool.h>
index 4ae47ed..71b934e 100644 (file)
@@ -15,7 +15,7 @@
 
 #include <vnet/ip/ip.h>
 #include <vnet/plugin/plugin.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <ioam/ipfixcollector/ipfixcollector.h>
 
 ipfix_collector_main_t ipfix_collector_main;
index b42c357..f334c98 100644 (file)
@@ -16,7 +16,7 @@
 #include <vppinfra/hash.h>
 #include <vnet/vnet.h>
 #include <vnet/ip/ip.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ethernet/ethernet.h>
 #include <vnet/vxlan-gpe/vxlan_gpe.h>
 #include <ioam/lib-vxlan-gpe/vxlan_gpe_ioam_packet.h>
index e30c913..b4b7793 100644 (file)
@@ -689,12 +689,12 @@ snat_hairpinning (snat_main_t *sm,
                              ip4_header_t, dst_address);
       ip0->checksum = ip_csum_fold (sum0);
 
-      old_dst_port0 = tcp0->ports.dst;
+      old_dst_port0 = tcp0->dst;
       if (PREDICT_TRUE(new_dst_port0 != old_dst_port0))
         {
           if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
             {
-              tcp0->ports.dst = new_dst_port0;
+              tcp0->dst = new_dst_port0;
               sum0 = tcp0->checksum;
               sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                                      ip4_header_t, dst_address);
@@ -872,9 +872,9 @@ snat_in2out_node_fn_inline (vlib_main_t * vm,
 
           if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
             {
-              old_port0 = tcp0->ports.src;
-              tcp0->ports.src = s0->out2in.port;
-              new_port0 = tcp0->ports.src;
+              old_port0 = tcp0->src_port;
+              tcp0->src_port = s0->out2in.port;
+              new_port0 = tcp0->src_port;
 
               sum0 = tcp0->checksum;
               sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
@@ -1012,9 +1012,9 @@ snat_in2out_node_fn_inline (vlib_main_t * vm,
 
           if (PREDICT_TRUE(proto1 == SNAT_PROTOCOL_TCP))
             {
-              old_port1 = tcp1->ports.src;
-              tcp1->ports.src = s1->out2in.port;
-              new_port1 = tcp1->ports.src;
+              old_port1 = tcp1->src_port;
+              tcp1->src_port = s1->out2in.port;
+              new_port1 = tcp1->src_port;
 
               sum1 = tcp1->checksum;
               sum1 = ip_csum_update (sum1, old_addr1, new_addr1,
@@ -1188,9 +1188,9 @@ snat_in2out_node_fn_inline (vlib_main_t * vm,
 
           if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
             {
-              old_port0 = tcp0->ports.src;
-              tcp0->ports.src = s0->out2in.port;
-              new_port0 = tcp0->ports.src;
+              old_port0 = tcp0->src_port;
+              tcp0->src_port = s0->out2in.port;
+              new_port0 = tcp0->src_port;
 
               sum0 = tcp0->checksum;
               sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
@@ -1667,8 +1667,8 @@ snat_in2out_fast_static_map_fn (vlib_main_t * vm,
             {
               if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
                 {
-                  old_port0 = tcp0->ports.src;
-                  tcp0->ports.src = new_port0;
+                  old_port0 = tcp0->src_port;
+                  tcp0->src_port = new_port0;
 
                   sum0 = tcp0->checksum;
                   sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
index 328f5ba..3bfc0aa 100644 (file)
@@ -19,7 +19,7 @@
 #include <vnet/handoff.h>
 
 #include <vnet/ip/ip.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ethernet/ethernet.h>
 #include <vnet/fib/ip4_fib.h>
 #include <snat/snat.h>
@@ -602,9 +602,9 @@ snat_out2in_node_fn (vlib_main_t * vm,
 
           if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
             {
-              old_port0 = tcp0->ports.dst;
-              tcp0->ports.dst = s0->in2out.port;
-              new_port0 = tcp0->ports.dst;
+              old_port0 = tcp0->dst_port;
+              tcp0->dst_port = s0->in2out.port;
+              new_port0 = tcp0->dst_port;
 
               sum0 = tcp0->checksum;
               sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
@@ -737,9 +737,9 @@ snat_out2in_node_fn (vlib_main_t * vm,
 
           if (PREDICT_TRUE(proto1 == SNAT_PROTOCOL_TCP))
             {
-              old_port1 = tcp1->ports.dst;
-              tcp1->ports.dst = s1->in2out.port;
-              new_port1 = tcp1->ports.dst;
+              old_port1 = tcp1->dst_port;
+              tcp1->dst_port = s1->in2out.port;
+              new_port1 = tcp1->dst_port;
 
               sum1 = tcp1->checksum;
               sum1 = ip_csum_update (sum1, old_addr1, new_addr1,
@@ -907,9 +907,9 @@ snat_out2in_node_fn (vlib_main_t * vm,
 
           if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
             {
-              old_port0 = tcp0->ports.dst;
-              tcp0->ports.dst = s0->in2out.port;
-              new_port0 = tcp0->ports.dst;
+              old_port0 = tcp0->dst_port;
+              tcp0->dst_port = s0->in2out.port;
+              new_port0 = tcp0->dst_port;
 
               sum0 = tcp0->checksum;
               sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
@@ -1369,8 +1369,8 @@ snat_out2in_fast_node_fn (vlib_main_t * vm,
             {
                if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
                 {
-                  old_port0 = tcp0->ports.dst;
-                  tcp0->ports.dst = new_port0;
+                  old_port0 = tcp0->dst_port;
+                  tcp0->dst_port = new_port0;
 
                   sum0 = tcp0->checksum;
                   sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
index a2ee8b2..b9c23c3 100644 (file)
@@ -1,16 +1,18 @@
+loop create
+set int ip address loop0 192.168.1.1/8
+set int state loop0 up
+
 packet-generator new {
   name x
-  limit 1
+  limit 2048
   node ip4-input
-  size 64-64
+  size 100-100
+  interface loop0
   no-recycle
   data {
-    TCP: 1.2.3.4 -> 5.6.7.8
-    TCP: 1234 -> 5678
+    TCP: 192.168.1.2 -> 192.168.1.1
+    TCP: 32415 -> 80
+    SYN
     incrementing 100
   }
 }
-
-tr add pg-input 100
-ip route 5.6.7.8/32 via local
-ip route 1.2.3.4/32 via local
diff --git a/src/scripts/vnet/udp b/src/scripts/vnet/udp
new file mode 100644 (file)
index 0000000..7dda1ee
--- /dev/null
@@ -0,0 +1,19 @@
+loop create
+set int ip address loop0 192.168.1.1/8
+set int state loop0 up
+
+packet-generator new {
+  name udp
+  limit 512
+  rate 1e4
+  node ip4-input
+  size 100-100
+  interface loop0
+  no-recycle
+  data {
+   UDP: 192.168.1.2 - 192.168.2.255 -> 192.168.1.1
+   UDP: 4321 -> 1234
+    length 72
+    incrementing 100
+  }
+}
diff --git a/src/scripts/vnet/uri/tcp-setup.sh b/src/scripts/vnet/uri/tcp-setup.sh
new file mode 100755 (executable)
index 0000000..e0b0158
--- /dev/null
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+
+function topo_setup
+{
+  ip netns add vppns1
+  ip link add veth_vpp1 type veth peer name vpp1
+  ip link set dev vpp1 up
+  ip link set dev veth_vpp1 up netns vppns1
+
+  ip netns exec vppns1                          \
+  bash -c "
+    ip link set dev lo up
+    ip addr add 6.0.1.2/24 dev veth_vpp1
+  "
+
+  ethtool --offload  vpp1 rx off tx off
+  ip netns exec vppns1 ethtool --offload veth_vpp1 rx off tx off
+
+}
+
+function topo_clean
+{
+  ip link del dev veth_vpp1 &> /dev/null
+  ip netns del vppns1 &> /dev/null
+}
+
+if [ "$1" == "clean" ] ; then
+  topo_clean
+    exit 0
+else
+  topo_setup
+fi
+
+# to test connectivity do:
+# sudo ip netns exec vppns1 telnet 6.0.1.1 1234
+# to push traffic to the server
+# dd if=/dev/zero bs=1024K count=512 | nc 6.0.1.1
+# to listen for incoming connection from vpp
+# nc -l 1234
diff --git a/src/scripts/vnet/uri/tcp_server b/src/scripts/vnet/uri/tcp_server
new file mode 100644 (file)
index 0000000..7f5a86d
--- /dev/null
@@ -0,0 +1,4 @@
+create host-interface name vpp1
+set int state host-vpp1 up
+set int ip address host-vpp1 6.0.1.1/24
+trace add af-packet-input 10
diff --git a/src/scripts/vnet/uri/udp b/src/scripts/vnet/uri/udp
new file mode 100644 (file)
index 0000000..ca13b83
--- /dev/null
@@ -0,0 +1,19 @@
+loop create
+set int ip address loop0 10.0.0.1/32
+set int state loop0 up
+
+packet-generator new {
+  name udp
+  limit 512
+  rate 1e4
+  node ip4-input
+  size 100-100
+  interface loop0
+  no-recycle
+  data {
+   UDP: 192.168.1.2 - 192.168.2.255 -> 192.168.1.1
+   UDP: 4321 -> 1234
+    length 72
+    incrementing 100
+  }
+}
index 2cd385b..442eba8 100644 (file)
 
 bin_PROGRAMS += svmtool svmdbtool
 
-nobase_include_HEADERS += svm/svm.h svm/ssvm.h svm/svmdb.h
+nobase_include_HEADERS += svm/svm.h svm/ssvm.h svm/svmdb.h \
+       svm/svm_fifo.h svm/svm_fifo_segment.h
 
 lib_LTLIBRARIES += libsvm.la libsvmdb.la
 
+libsvm_la_SOURCES = svm/svm.c svm/ssvm.c svm/svm_fifo.c svm/svm_fifo_segment.c
 libsvm_la_LIBADD = libvppinfra.la -lrt -lpthread
 libsvm_la_DEPENDENCIES = libvppinfra.la
-libsvm_la_SOURCES = svm/svm.c svm/ssvm.c
 
 svmtool_SOURCES = svm/svmtool.c
 svmtool_LDADD = libsvm.la libvppinfra.la -lpthread -lrt
@@ -31,4 +32,9 @@ libsvmdb_la_SOURCES = svm/svmdb.c
 svmdbtool_SOURCES = svm/svmdbtool.c
 svmdbtool_LDADD = libsvmdb.la libsvm.la libvppinfra.la -lpthread -lrt
 
+noinst_PROGRAMS += test_svm_fifo1
+test_svm_fifo1_SOURCES = svm/test_svm_fifo1.c
+test_svm_fifo1_LDADD = libsvm.la libvppinfra.la -lpthread -lrt
+test_svm_fifo1_LDFLAGS = -static
+
 # vi:syntax=automake
index 6f409eb..6cda1f2 100644 (file)
@@ -169,6 +169,22 @@ re_map_it:
   return 0;
 }
 
+void
+ssvm_delete (ssvm_private_t * ssvm)
+{
+  u8 *fn;
+
+  fn = format (0, "/dev/shm/%s%c", ssvm->name, 0);
+
+  /* Throw away the backing file */
+  if (unlink ((char *) fn) < 0)
+    clib_unix_warning ("unlink segment '%s'", ssvm->name);
+
+  munmap ((void *) ssvm->requested_va, ssvm->ssvm_size);
+  vec_free (fn);
+}
+
+
 /*
  * fd.io coding-style-patch-verification: ON
  *
index 9e61b9a..bccfc16 100644 (file)
 #include <vppinfra/pool.h>
 #include <vppinfra/format.h>
 
-#define MMAP_PAGESIZE (4<<10)
+#ifndef MMAP_PAGESIZE
+#define MMAP_PAGESIZE (clib_mem_get_page_size())
+#endif
+
 #define SSVM_N_OPAQUE 7
 
 typedef struct
@@ -125,12 +128,12 @@ ssvm_pop_heap (void *oldheap)
 }
 
 #define foreach_ssvm_api_error                  \
-_(NO_NAME, "No shared segment name", -10      \
-_(NO_SIZE, "Size not set (master)", -11)        \
-_(CREATE_FAILURE, "Create failed", -12)                \
-_(SET_SIZE, "Set size failed", -13)            \
-_(MMAP, "mmap failed", -14)                    \
-_(SLAVE_TIMEOUT, "Slave map timeout", -15)
+_(NO_NAME, "No shared segment name", -100)      \
+_(NO_SIZE, "Size not set (master)", -101)       \
+_(CREATE_FAILURE, "Create failed", -102)        \
+_(SET_SIZE, "Set size failed", -103)           \
+_(MMAP, "mmap failed", -104)                   \
+_(SLAVE_TIMEOUT, "Slave map timeout", -105)
 
 typedef enum
 {
@@ -143,6 +146,7 @@ typedef enum
 
 int ssvm_master_init (ssvm_private_t * ssvm, u32 master_index);
 int ssvm_slave_init (ssvm_private_t * ssvm, int timeout_in_seconds);
+void ssvm_delete (ssvm_private_t * ssvm);
 
 #endif /* __included_ssvm_h__ */
 
diff --git a/src/svm/svm_fifo.c b/src/svm/svm_fifo.c
new file mode 100644 (file)
index 0000000..11f9019
--- /dev/null
@@ -0,0 +1,568 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "svm_fifo.h"
+
+/** create an svm fifo, in the current heap. Fails vs blow up the process */
+svm_fifo_t *
+svm_fifo_create (u32 data_size_in_bytes)
+{
+  svm_fifo_t *f;
+  pthread_mutexattr_t attr;
+  pthread_condattr_t cattr;
+
+  f = clib_mem_alloc_aligned_or_null (sizeof (*f) + data_size_in_bytes,
+                                     CLIB_CACHE_LINE_BYTES);
+  if (f == 0)
+    return 0;
+
+  memset (f, 0, sizeof (*f) + data_size_in_bytes);
+  f->nitems = data_size_in_bytes;
+  f->ooos_list_head = OOO_SEGMENT_INVALID_INDEX;
+
+  memset (&attr, 0, sizeof (attr));
+  memset (&cattr, 0, sizeof (cattr));
+
+  if (pthread_mutexattr_init (&attr))
+    clib_unix_warning ("mutexattr_init");
+  if (pthread_mutexattr_setpshared (&attr, PTHREAD_PROCESS_SHARED))
+    clib_unix_warning ("pthread_mutexattr_setpshared");
+  if (pthread_mutex_init (&f->mutex, &attr))
+    clib_unix_warning ("mutex_init");
+  if (pthread_mutexattr_destroy (&attr))
+    clib_unix_warning ("mutexattr_destroy");
+  if (pthread_condattr_init (&cattr))
+    clib_unix_warning ("condattr_init");
+  if (pthread_condattr_setpshared (&cattr, PTHREAD_PROCESS_SHARED))
+    clib_unix_warning ("condattr_setpshared");
+  if (pthread_cond_init (&f->condvar, &cattr))
+    clib_unix_warning ("cond_init1");
+  if (pthread_condattr_destroy (&cattr))
+    clib_unix_warning ("cond_init2");
+
+  return (f);
+}
+
+always_inline ooo_segment_t *
+ooo_segment_new (svm_fifo_t * f, u32 start, u32 length)
+{
+  ooo_segment_t *s;
+
+  pool_get (f->ooo_segments, s);
+
+  s->fifo_position = start;
+  s->length = length;
+
+  s->prev = s->next = OOO_SEGMENT_INVALID_INDEX;
+
+  return s;
+}
+
+always_inline void
+ooo_segment_del (svm_fifo_t * f, u32 index)
+{
+  ooo_segment_t *cur, *prev = 0, *next = 0;
+  cur = pool_elt_at_index (f->ooo_segments, index);
+
+  if (cur->next != OOO_SEGMENT_INVALID_INDEX)
+    {
+      next = pool_elt_at_index (f->ooo_segments, cur->next);
+      next->prev = cur->prev;
+    }
+
+  if (cur->prev != OOO_SEGMENT_INVALID_INDEX)
+    {
+      prev = pool_elt_at_index (f->ooo_segments, cur->prev);
+      prev->next = cur->next;
+    }
+  else
+    {
+      f->ooos_list_head = cur->next;
+    }
+
+  pool_put (f->ooo_segments, cur);
+}
+
+/**
+ * Add segment to fifo's out-of-order segment list. Takes care of merging
+ * adjacent segments and removing overlapping ones.
+ */
+static void
+ooo_segment_add (svm_fifo_t * f, u32 offset, u32 length)
+{
+  ooo_segment_t *s, *new_s, *prev, *next, *it;
+  u32 new_index, position, end_offset, s_sof, s_eof, s_index;
+
+  position = (f->tail + offset) % f->nitems;
+  end_offset = offset + length;
+
+  if (f->ooos_list_head == OOO_SEGMENT_INVALID_INDEX)
+    {
+      s = ooo_segment_new (f, position, length);
+      f->ooos_list_head = s - f->ooo_segments;
+      f->ooos_newest = f->ooos_list_head;
+      return;
+    }
+
+  /* Find first segment that starts after new segment */
+  s = pool_elt_at_index (f->ooo_segments, f->ooos_list_head);
+  while (s->next != OOO_SEGMENT_INVALID_INDEX
+        && ooo_segment_offset (f, s) <= offset)
+    s = pool_elt_at_index (f->ooo_segments, s->next);
+
+  s_index = s - f->ooo_segments;
+  s_sof = ooo_segment_offset (f, s);
+  s_eof = ooo_segment_end_offset (f, s);
+
+  /* No overlap, add before current segment */
+  if (end_offset < s_sof)
+    {
+      new_s = ooo_segment_new (f, position, length);
+      new_index = new_s - f->ooo_segments;
+
+      /* Pool might've moved, get segment again */
+      s = pool_elt_at_index (f->ooo_segments, s_index);
+
+      if (s->prev != OOO_SEGMENT_INVALID_INDEX)
+       {
+         new_s->prev = s->prev;
+
+         prev = pool_elt_at_index (f->ooo_segments, new_s->prev);
+         prev->next = new_index;
+       }
+      else
+       {
+         /* New head */
+         f->ooos_list_head = new_index;
+       }
+
+      new_s->next = s - f->ooo_segments;
+      s->prev = new_index;
+      f->ooos_newest = new_index;
+      return;
+    }
+  /* No overlap, add after current segment */
+  else if (s_eof < offset)
+    {
+      new_s = ooo_segment_new (f, position, length);
+      new_index = new_s - f->ooo_segments;
+
+      /* Pool might've moved, get segment again */
+      s = pool_elt_at_index (f->ooo_segments, s_index);
+
+      if (s->next != OOO_SEGMENT_INVALID_INDEX)
+       {
+         new_s->next = s->next;
+
+         next = pool_elt_at_index (f->ooo_segments, new_s->next);
+         next->prev = new_index;
+       }
+
+      new_s->prev = s - f->ooo_segments;
+      s->next = new_index;
+      f->ooos_newest = new_index;
+
+      return;
+    }
+
+  /*
+   * Merge needed
+   */
+
+  /* Merge at head */
+  if (offset <= s_sof)
+    {
+      /* If we have a previous, check if we overlap */
+      if (s->prev != OOO_SEGMENT_INVALID_INDEX)
+       {
+         prev = pool_elt_at_index (f->ooo_segments, s->prev);
+
+         /* New segment merges prev and current. Remove previous and
+          * update position of current. */
+         if (ooo_segment_end_offset (f, prev) >= offset)
+           {
+             s->fifo_position = prev->fifo_position;
+             s->length = s_eof - ooo_segment_offset (f, prev);
+             ooo_segment_del (f, s->prev);
+           }
+       }
+      else
+       {
+         s->fifo_position = position;
+         s->length = s_eof - ooo_segment_offset (f, s);
+       }
+
+      /* The new segment's tail may cover multiple smaller ones */
+      if (s_eof < end_offset)
+       {
+         /* Remove segments completely covered */
+         it = (s->next != OOO_SEGMENT_INVALID_INDEX) ?
+           pool_elt_at_index (f->ooo_segments, s->next) : 0;
+         while (it && ooo_segment_end_offset (f, it) < end_offset)
+           {
+             next = (it->next != OOO_SEGMENT_INVALID_INDEX) ?
+               pool_elt_at_index (f->ooo_segments, it->next) : 0;
+             ooo_segment_del (f, it - f->ooo_segments);
+             it = next;
+           }
+
+         /* Update length. Segment's start might have changed. */
+         s->length = end_offset - ooo_segment_offset (f, s);
+
+         /* If partial overlap with last, merge */
+         if (it && ooo_segment_offset (f, it) < end_offset)
+           {
+             s->length +=
+               it->length - (ooo_segment_offset (f, it) - end_offset);
+             ooo_segment_del (f, it - f->ooo_segments);
+           }
+       }
+    }
+  /* Last but overlapping previous */
+  else if (s_eof <= end_offset)
+    {
+      s->length = end_offset - ooo_segment_offset (f, s);
+    }
+  /* New segment completely covered by current one */
+  else
+    {
+      /* Do Nothing */
+    }
+
+  /* Most recently updated segment */
+  f->ooos_newest = s - f->ooo_segments;
+}
+
+/**
+ * Removes segments that can now be enqueued because the fifo's tail has
+ * advanced. Returns the number of bytes added to tail.
+ */
+static int
+ooo_segment_try_collect (svm_fifo_t * f, u32 n_bytes_enqueued)
+{
+  ooo_segment_t *s;
+  u32 index, bytes = 0, diff;
+
+  s = pool_elt_at_index (f->ooo_segments, f->ooos_list_head);
+
+  /* If last tail update overlaps one/multiple ooo segments, remove them */
+  diff = (f->nitems + f->tail - s->fifo_position) % f->nitems;
+  while (0 < diff && diff < n_bytes_enqueued)
+    {
+      /* Segment end is beyond the tail. Advance tail and be done */
+      if (diff < s->length)
+       {
+         f->tail += s->length - diff;
+         f->tail %= f->nitems;
+         break;
+       }
+      /* If we have next go on */
+      else if (s->next != OOO_SEGMENT_INVALID_INDEX)
+       {
+         index = s - f->ooo_segments;
+         s = pool_elt_at_index (f->ooo_segments, s->next);
+         diff = (f->nitems + f->tail - s->fifo_position) % f->nitems;
+         ooo_segment_del (f, index);
+       }
+      /* End of search */
+      else
+       {
+         break;
+       }
+    }
+
+  /* If tail is adjacent to an ooo segment, 'consume' it */
+  if (diff == 0)
+    {
+      bytes = ((f->nitems - f->cursize) >= s->length) ? s->length :
+       f->nitems - f->cursize;
+
+      f->tail += bytes;
+      f->tail %= f->nitems;
+
+      ooo_segment_del (f, s - f->ooo_segments);
+    }
+
+  return bytes;
+}
+
+static int
+svm_fifo_enqueue_internal (svm_fifo_t * f,
+                          int pid, u32 max_bytes, u8 * copy_from_here)
+{
+  u32 total_copy_bytes, first_copy_bytes, second_copy_bytes;
+  u32 cursize, nitems;
+
+  if (PREDICT_FALSE (f->cursize == f->nitems))
+    return -2;                 /* fifo stuffed */
+
+  /* read cursize, which can only decrease while we're working */
+  cursize = f->cursize;
+  nitems = f->nitems;
+
+  /* Number of bytes we're going to copy */
+  total_copy_bytes = (nitems - cursize) < max_bytes ?
+    (nitems - cursize) : max_bytes;
+
+  if (PREDICT_TRUE (copy_from_here != 0))
+    {
+      /* Number of bytes in first copy segment */
+      first_copy_bytes = ((nitems - f->tail) < total_copy_bytes)
+       ? (nitems - f->tail) : total_copy_bytes;
+
+      clib_memcpy (&f->data[f->tail], copy_from_here, first_copy_bytes);
+      f->tail += first_copy_bytes;
+      f->tail = (f->tail == nitems) ? 0 : f->tail;
+
+      /* Number of bytes in second copy segment, if any */
+      second_copy_bytes = total_copy_bytes - first_copy_bytes;
+      if (second_copy_bytes)
+       {
+         clib_memcpy (&f->data[f->tail], copy_from_here + first_copy_bytes,
+                      second_copy_bytes);
+         f->tail += second_copy_bytes;
+         f->tail = (f->tail == nitems) ? 0 : f->tail;
+       }
+    }
+  else
+    {
+      /* Account for a zero-copy enqueue done elsewhere */
+      ASSERT (max_bytes <= (nitems - cursize));
+      f->tail += max_bytes;
+      f->tail = f->tail % nitems;
+      total_copy_bytes = max_bytes;
+    }
+
+  /* Any out-of-order segments to collect? */
+  if (PREDICT_FALSE (f->ooos_list_head != OOO_SEGMENT_INVALID_INDEX))
+    total_copy_bytes += ooo_segment_try_collect (f, total_copy_bytes);
+
+  /* Atomically increase the queue length */
+  __sync_fetch_and_add (&f->cursize, total_copy_bytes);
+
+  return (total_copy_bytes);
+}
+
+int
+svm_fifo_enqueue_nowait (svm_fifo_t * f,
+                        int pid, u32 max_bytes, u8 * copy_from_here)
+{
+  return svm_fifo_enqueue_internal (f, pid, max_bytes, copy_from_here);
+}
+
+/** Enqueue a future segment.
+ * Two choices: either copies the entire segment, or copies nothing
+ * Returns 0 of the entire segment was copied
+ * Returns -1 if none of the segment was copied due to lack of space
+ */
+
+static int
+svm_fifo_enqueue_with_offset_internal2 (svm_fifo_t * f,
+                                       int pid,
+                                       u32 offset,
+                                       u32 required_bytes,
+                                       u8 * copy_from_here)
+{
+  u32 total_copy_bytes, first_copy_bytes, second_copy_bytes;
+  u32 cursize, nitems;
+  u32 tail_plus_offset;
+
+  ASSERT (offset > 0);
+
+  /* read cursize, which can only decrease while we're working */
+  cursize = f->cursize;
+  nitems = f->nitems;
+
+  /* Will this request fit? */
+  if ((required_bytes + offset) > (nitems - cursize))
+    return -1;
+
+  ooo_segment_add (f, offset, required_bytes);
+
+  /* Number of bytes we're going to copy */
+  total_copy_bytes = required_bytes;
+  tail_plus_offset = (f->tail + offset) % nitems;
+
+  /* Number of bytes in first copy segment */
+  first_copy_bytes = ((nitems - tail_plus_offset) < total_copy_bytes)
+    ? (nitems - tail_plus_offset) : total_copy_bytes;
+
+  clib_memcpy (&f->data[tail_plus_offset], copy_from_here, first_copy_bytes);
+
+  /* Number of bytes in second copy segment, if any */
+  second_copy_bytes = total_copy_bytes - first_copy_bytes;
+  if (second_copy_bytes)
+    {
+      tail_plus_offset += first_copy_bytes;
+      tail_plus_offset %= nitems;
+
+      ASSERT (tail_plus_offset == 0);
+
+      clib_memcpy (&f->data[tail_plus_offset],
+                  copy_from_here + first_copy_bytes, second_copy_bytes);
+    }
+
+  return (0);
+}
+
+
+int
+svm_fifo_enqueue_with_offset (svm_fifo_t * f,
+                             int pid,
+                             u32 offset,
+                             u32 required_bytes, u8 * copy_from_here)
+{
+  return svm_fifo_enqueue_with_offset_internal2
+    (f, pid, offset, required_bytes, copy_from_here);
+}
+
+
+static int
+svm_fifo_dequeue_internal2 (svm_fifo_t * f,
+                           int pid, u32 max_bytes, u8 * copy_here)
+{
+  u32 total_copy_bytes, first_copy_bytes, second_copy_bytes;
+  u32 cursize, nitems;
+
+  if (PREDICT_FALSE (f->cursize == 0))
+    return -2;                 /* nothing in the fifo */
+
+  /* read cursize, which can only increase while we're working */
+  cursize = f->cursize;
+  nitems = f->nitems;
+
+  /* Number of bytes we're going to copy */
+  total_copy_bytes = (cursize < max_bytes) ? cursize : max_bytes;
+
+  if (PREDICT_TRUE (copy_here != 0))
+    {
+      /* Number of bytes in first copy segment */
+      first_copy_bytes = ((nitems - f->head) < total_copy_bytes)
+       ? (nitems - f->head) : total_copy_bytes;
+      clib_memcpy (copy_here, &f->data[f->head], first_copy_bytes);
+      f->head += first_copy_bytes;
+      f->head = (f->head == nitems) ? 0 : f->head;
+
+      /* Number of bytes in second copy segment, if any */
+      second_copy_bytes = total_copy_bytes - first_copy_bytes;
+      if (second_copy_bytes)
+       {
+         clib_memcpy (copy_here + first_copy_bytes,
+                      &f->data[f->head], second_copy_bytes);
+         f->head += second_copy_bytes;
+         f->head = (f->head == nitems) ? 0 : f->head;
+       }
+    }
+  else
+    {
+      /* Account for a zero-copy dequeue done elsewhere */
+      ASSERT (max_bytes <= cursize);
+      f->head += max_bytes;
+      f->head = f->head % nitems;
+      cursize -= max_bytes;
+      total_copy_bytes = max_bytes;
+    }
+
+  __sync_fetch_and_sub (&f->cursize, total_copy_bytes);
+
+  return (total_copy_bytes);
+}
+
+int
+svm_fifo_dequeue_nowait (svm_fifo_t * f,
+                        int pid, u32 max_bytes, u8 * copy_here)
+{
+  return svm_fifo_dequeue_internal2 (f, pid, max_bytes, copy_here);
+}
+
+int
+svm_fifo_peek (svm_fifo_t * f, int pid, u32 offset, u32 max_bytes,
+              u8 * copy_here)
+{
+  u32 total_copy_bytes, first_copy_bytes, second_copy_bytes;
+  u32 cursize, nitems;
+
+  if (PREDICT_FALSE (f->cursize == 0))
+    return -2;                 /* nothing in the fifo */
+
+  /* read cursize, which can only increase while we're working */
+  cursize = f->cursize;
+  nitems = f->nitems;
+
+  /* Number of bytes we're going to copy */
+  total_copy_bytes = (cursize < max_bytes) ? cursize : max_bytes;
+
+  if (PREDICT_TRUE (copy_here != 0))
+    {
+      /* Number of bytes in first copy segment */
+      first_copy_bytes =
+       ((nitems - f->head) < total_copy_bytes) ?
+       (nitems - f->head) : total_copy_bytes;
+      clib_memcpy (copy_here, &f->data[f->head], first_copy_bytes);
+
+      /* Number of bytes in second copy segment, if any */
+      second_copy_bytes = total_copy_bytes - first_copy_bytes;
+      if (second_copy_bytes)
+       {
+         clib_memcpy (copy_here + first_copy_bytes, &f->data[0],
+                      second_copy_bytes);
+       }
+    }
+  return total_copy_bytes;
+}
+
+int
+svm_fifo_dequeue_drop (svm_fifo_t * f, int pid, u32 max_bytes)
+{
+  u32 total_drop_bytes, first_drop_bytes, second_drop_bytes;
+  u32 cursize, nitems;
+
+  if (PREDICT_FALSE (f->cursize == 0))
+    return -2;                 /* nothing in the fifo */
+
+  /* read cursize, which can only increase while we're working */
+  cursize = f->cursize;
+  nitems = f->nitems;
+
+  /* Number of bytes we're going to drop */
+  total_drop_bytes = (cursize < max_bytes) ? cursize : max_bytes;
+
+  /* Number of bytes in first copy segment */
+  first_drop_bytes =
+    ((nitems - f->head) < total_drop_bytes) ?
+    (nitems - f->head) : total_drop_bytes;
+  f->head += first_drop_bytes;
+  f->head = (f->head == nitems) ? 0 : f->head;
+
+  /* Number of bytes in second drop segment, if any */
+  second_drop_bytes = total_drop_bytes - first_drop_bytes;
+  if (second_drop_bytes)
+    {
+      f->head += second_drop_bytes;
+      f->head = (f->head == nitems) ? 0 : f->head;
+    }
+
+  __sync_fetch_and_sub (&f->cursize, total_drop_bytes);
+
+  return total_drop_bytes;
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/svm/svm_fifo.h b/src/svm/svm_fifo.h
new file mode 100644 (file)
index 0000000..70624b7
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __included_ssvm_fifo_h__
+#define __included_ssvm_fifo_h__
+
+#include <vppinfra/clib.h>
+#include <vppinfra/vec.h>
+#include <vppinfra/mheap.h>
+#include <vppinfra/heap.h>
+#include <vppinfra/pool.h>
+#include <vppinfra/format.h>
+#include <pthread.h>
+
+typedef enum
+{
+  SVM_FIFO_TAG_NOT_HELD = 0,
+  SVM_FIFO_TAG_DEQUEUE,
+  SVM_FIFO_TAG_ENQUEUE,
+} svm_lock_tag_t;
+
+/** Out-of-order segment */
+typedef struct
+{
+  u32 next;    /**< Next linked-list element pool index */
+  u32 prev;    /**< Previous linked-list element pool index */
+
+  u32 fifo_position;   /**< Start of segment, normalized*/
+  u32 length;          /**< Length of segment */
+} ooo_segment_t;
+
+#define OOO_SEGMENT_INVALID_INDEX ((u32)~0)
+
+typedef struct
+{
+  pthread_mutex_t mutex;       /* 8 bytes */
+  pthread_cond_t condvar;      /* 8 bytes */
+  u32 owner_pid;
+  svm_lock_tag_t tag;
+  volatile u32 cursize;
+  u32 nitems;
+
+  /* Backpointers */
+  u32 server_session_index;
+  u32 client_session_index;
+  u8 server_thread_index;
+  u8 client_thread_index;
+    CLIB_CACHE_LINE_ALIGN_MARK (end_shared);
+  u32 head;
+    CLIB_CACHE_LINE_ALIGN_MARK (end_consumer);
+
+  /* producer */
+  u32 tail;
+
+  ooo_segment_t *ooo_segments; /**< Pool of ooo segments */
+  u32 ooos_list_head;          /**< Head of out-of-order linked-list */
+  u32 ooos_newest;             /**< Last segment to have been updated */
+
+    CLIB_CACHE_LINE_ALIGN_MARK (data);
+} svm_fifo_t;
+
+static inline int
+svm_fifo_lock (svm_fifo_t * f, u32 pid, u32 tag, int nowait)
+{
+  if (PREDICT_TRUE (nowait == 0))
+    pthread_mutex_lock (&f->mutex);
+  else
+    {
+      if (pthread_mutex_trylock (&f->mutex))
+       return -1;
+    }
+  f->owner_pid = pid;
+  f->tag = tag;
+  return 0;
+}
+
+static inline void
+svm_fifo_unlock (svm_fifo_t * f)
+{
+  f->owner_pid = 0;
+  f->tag = 0;
+  CLIB_MEMORY_BARRIER ();
+  pthread_mutex_unlock (&f->mutex);
+}
+
+static inline u32
+svm_fifo_max_dequeue (svm_fifo_t * f)
+{
+  return f->cursize;
+}
+
+static inline u32
+svm_fifo_max_enqueue (svm_fifo_t * f)
+{
+  return f->nitems - f->cursize;
+}
+
+static inline u8
+svm_fifo_has_ooo_data (svm_fifo_t * f)
+{
+  return f->ooos_list_head != OOO_SEGMENT_INVALID_INDEX;
+}
+
+svm_fifo_t *svm_fifo_create (u32 data_size_in_bytes);
+
+int svm_fifo_enqueue_nowait (svm_fifo_t * f, int pid, u32 max_bytes,
+                            u8 * copy_from_here);
+
+int svm_fifo_enqueue_with_offset (svm_fifo_t * f, int pid,
+                                 u32 offset, u32 required_bytes,
+                                 u8 * copy_from_here);
+
+int svm_fifo_dequeue_nowait (svm_fifo_t * f, int pid, u32 max_bytes,
+                            u8 * copy_here);
+
+int svm_fifo_peek (svm_fifo_t * f, int pid, u32 offset, u32 max_bytes,
+                  u8 * copy_here);
+int svm_fifo_dequeue_drop (svm_fifo_t * f, int pid, u32 max_bytes);
+
+always_inline ooo_segment_t *
+svm_fifo_newest_ooo_segment (svm_fifo_t * f)
+{
+  return f->ooo_segments + f->ooos_newest;
+}
+
+always_inline u32
+ooo_segment_offset (svm_fifo_t * f, ooo_segment_t * s)
+{
+  return ((f->nitems + s->fifo_position - f->tail) % f->nitems);
+}
+
+always_inline u32
+ooo_segment_end_offset (svm_fifo_t * f, ooo_segment_t * s)
+{
+  return ((f->nitems + s->fifo_position + s->length - f->tail) % f->nitems);
+}
+
+#endif /* __included_ssvm_fifo_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/svm/svm_fifo_segment.c b/src/svm/svm_fifo_segment.c
new file mode 100644 (file)
index 0000000..acabb3b
--- /dev/null
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <svm/svm_fifo_segment.h>
+
+svm_fifo_segment_main_t svm_fifo_segment_main;
+
+/** (master) create an svm fifo segment */
+int
+svm_fifo_segment_create (svm_fifo_segment_create_args_t * a)
+{
+  int rv;
+  svm_fifo_segment_private_t *s;
+  svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
+  ssvm_shared_header_t *sh;
+  svm_fifo_segment_header_t *fsh;
+  void *oldheap;
+
+  /* Allocate a fresh segment */
+  pool_get (sm->segments, s);
+  memset (s, 0, sizeof (*s));
+
+  s->ssvm.ssvm_size = a->segment_size;
+  s->ssvm.i_am_master = 1;
+  s->ssvm.my_pid = getpid ();
+  s->ssvm.name = (u8 *) a->segment_name;
+  s->ssvm.requested_va = sm->next_baseva;
+
+  rv = ssvm_master_init (&s->ssvm, s - sm->segments);
+
+  if (rv)
+    {
+      _vec_len (s) = vec_len (s) - 1;
+      return (rv);
+    }
+
+  /* Note; requested_va updated due to seg base addr randomization */
+  sm->next_baseva = s->ssvm.requested_va + a->segment_size;
+
+  sh = s->ssvm.sh;
+  oldheap = ssvm_push_heap (sh);
+
+  /* Set up svm_fifo_segment shared header */
+  fsh = clib_mem_alloc (sizeof (*fsh));
+  memset (fsh, 0, sizeof (*fsh));
+  sh->opaque[0] = fsh;
+  s->h = fsh;
+  fsh->segment_name = format (0, "%s%c", a->segment_name, 0);
+
+  /* Avoid vec_add1(...) failure when adding a fifo, etc. */
+  vec_validate (fsh->fifos, 64);
+  _vec_len (fsh->fifos) = 0;
+
+  ssvm_pop_heap (oldheap);
+
+  sh->ready = 1;
+  a->new_segment_index = s - sm->segments;
+  return (0);
+}
+
+/** (slave) attach to an svm fifo segment */
+int
+svm_fifo_segment_attach (svm_fifo_segment_create_args_t * a)
+{
+  int rv;
+  svm_fifo_segment_private_t *s;
+  svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
+  ssvm_shared_header_t *sh;
+  svm_fifo_segment_header_t *fsh;
+
+  /* Allocate a fresh segment */
+  pool_get (sm->segments, s);
+
+  memset (s, 0, sizeof (*s));
+
+  s->ssvm.ssvm_size = a->segment_size;
+  s->ssvm.my_pid = getpid ();
+  s->ssvm.name = (u8 *) a->segment_name;
+  s->ssvm.requested_va = sm->next_baseva;
+
+  rv = ssvm_slave_init (&s->ssvm, sm->timeout_in_seconds);
+
+  if (rv)
+    {
+      _vec_len (s) = vec_len (s) - 1;
+      return (rv);
+    }
+
+  /* Fish the segment header */
+  sh = s->ssvm.sh;
+  fsh = (svm_fifo_segment_header_t *) sh->opaque[0];
+  s->h = fsh;
+
+  a->new_segment_index = s - sm->segments;
+  return (0);
+}
+
+void
+svm_fifo_segment_delete (svm_fifo_segment_private_t * s)
+{
+  svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
+  ssvm_delete (&s->ssvm);
+  pool_put (sm->segments, s);
+}
+
+svm_fifo_t *
+svm_fifo_segment_alloc_fifo (svm_fifo_segment_private_t * s,
+                            u32 data_size_in_bytes)
+{
+  ssvm_shared_header_t *sh;
+  svm_fifo_segment_header_t *fsh;
+  svm_fifo_t *f;
+  void *oldheap;
+
+  sh = s->ssvm.sh;
+  fsh = (svm_fifo_segment_header_t *) sh->opaque[0];
+  oldheap = ssvm_push_heap (sh);
+
+  /* Note: this can fail, in which case: create another segment */
+  f = svm_fifo_create (data_size_in_bytes);
+  if (f == 0)
+    {
+      ssvm_pop_heap (oldheap);
+      return (0);
+    }
+
+  vec_add1 (fsh->fifos, f);
+
+  ssvm_pop_heap (oldheap);
+  return (f);
+}
+
+void
+svm_fifo_segment_free_fifo (svm_fifo_segment_private_t * s, svm_fifo_t * f)
+{
+  ssvm_shared_header_t *sh;
+  svm_fifo_segment_header_t *fsh;
+  void *oldheap;
+  int i;
+
+  sh = s->ssvm.sh;
+  fsh = (svm_fifo_segment_header_t *) sh->opaque[0];
+  oldheap = ssvm_push_heap (sh);
+
+  for (i = 0; i < vec_len (fsh->fifos); i++)
+    {
+      if (fsh->fifos[i] == f)
+       {
+         vec_delete (fsh->fifos, 1, i);
+         goto found;
+       }
+    }
+  clib_warning ("fifo 0x%llx not found in fifo table...", f);
+
+found:
+  clib_mem_free (f);
+  ssvm_pop_heap (oldheap);
+}
+
+void
+svm_fifo_segment_init (u64 baseva, u32 timeout_in_seconds)
+{
+  svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
+
+  sm->next_baseva = baseva;
+  sm->timeout_in_seconds = timeout_in_seconds;
+}
+
+u32
+svm_fifo_segment_index (svm_fifo_segment_private_t * s)
+{
+  return s - svm_fifo_segment_main.segments;
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/svm/svm_fifo_segment.h b/src/svm/svm_fifo_segment.h
new file mode 100644 (file)
index 0000000..793fa7c
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __included_ssvm_fifo_segment_h__
+#define __included_ssvm_fifo_segment_h__
+
+#include "svm_fifo.h"
+#include "ssvm.h"
+
+typedef struct
+{
+  volatile svm_fifo_t **fifos;
+  u8 *segment_name;
+} svm_fifo_segment_header_t;
+
+typedef struct
+{
+  ssvm_private_t ssvm;
+  svm_fifo_segment_header_t *h;
+} svm_fifo_segment_private_t;
+
+typedef struct
+{
+  /** pool of segments */
+  svm_fifo_segment_private_t *segments;
+  /* Where to put the next one */
+  u64 next_baseva;
+  u32 timeout_in_seconds;
+} svm_fifo_segment_main_t;
+
+extern svm_fifo_segment_main_t svm_fifo_segment_main;
+
+typedef struct
+{
+  char *segment_name;
+  u32 segment_size;
+  u32 new_segment_index;
+} svm_fifo_segment_create_args_t;
+
+static inline svm_fifo_segment_private_t *
+svm_fifo_get_segment (u32 segment_index)
+{
+  svm_fifo_segment_main_t *ssm = &svm_fifo_segment_main;
+  return vec_elt_at_index (ssm->segments, segment_index);
+}
+
+#define foreach_ssvm_fifo_segment_api_error             \
+_(OUT_OF_SPACE, "Out of space in segment", -200)
+
+typedef enum
+{
+#define _(n,s,c) SSVM_FIFO_SEGMENT_API_ERROR_##n = c,
+  foreach_ssvm_fifo_segment_api_error
+#undef _
+} ssvm_fifo_segment_api_error_enum_t;
+
+int svm_fifo_segment_create (svm_fifo_segment_create_args_t * a);
+int svm_fifo_segment_attach (svm_fifo_segment_create_args_t * a);
+void svm_fifo_segment_delete (svm_fifo_segment_private_t * s);
+
+svm_fifo_t *svm_fifo_segment_alloc_fifo (svm_fifo_segment_private_t * s,
+                                        u32 data_size_in_bytes);
+void svm_fifo_segment_free_fifo (svm_fifo_segment_private_t * s,
+                                svm_fifo_t * f);
+
+void svm_fifo_segment_init (u64 baseva, u32 timeout_in_seconds);
+
+u32 svm_fifo_segment_index (svm_fifo_segment_private_t * s);
+
+#endif /* __included_ssvm_fifo_segment_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/svm/test_svm_fifo1.c b/src/svm/test_svm_fifo1.c
new file mode 100644 (file)
index 0000000..355653d
--- /dev/null
@@ -0,0 +1,361 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "svm_fifo_segment.h"
+
+clib_error_t *
+hello_world (int verbose)
+{
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  svm_fifo_segment_private_t *sp;
+  svm_fifo_t *f;
+  int rv;
+  u8 *test_data;
+  u8 *retrieved_data = 0;
+  clib_error_t *error = 0;
+  int pid = getpid ();
+
+  memset (a, 0, sizeof (*a));
+
+  a->segment_name = "fifo-test1";
+  a->segment_size = 256 << 10;
+
+  rv = svm_fifo_segment_create (a);
+
+  if (rv)
+    return clib_error_return (0, "svm_fifo_segment_create returned %d", rv);
+
+  sp = svm_fifo_get_segment (a->new_segment_index);
+
+  f = svm_fifo_segment_alloc_fifo (sp, 4096);
+
+  if (f == 0)
+    return clib_error_return (0, "svm_fifo_segment_alloc_fifo failed");
+
+  test_data = format (0, "Hello world%c", 0);
+  vec_validate (retrieved_data, vec_len (test_data) - 1);
+
+  while (svm_fifo_max_enqueue (f) >= vec_len (test_data))
+    svm_fifo_enqueue_nowait (f, pid, vec_len (test_data), test_data);
+
+  while (svm_fifo_max_dequeue (f) >= vec_len (test_data))
+    svm_fifo_dequeue_nowait (f, pid, vec_len (retrieved_data),
+                            retrieved_data);
+
+  while (svm_fifo_max_enqueue (f) >= vec_len (test_data))
+    svm_fifo_enqueue_nowait (f, pid, vec_len (test_data), test_data);
+
+  while (svm_fifo_max_dequeue (f) >= vec_len (test_data))
+    svm_fifo_dequeue_nowait (f, pid, vec_len (retrieved_data),
+                            retrieved_data);
+
+  if (!memcmp (retrieved_data, test_data, vec_len (test_data)))
+    error = clib_error_return (0, "data test OK, got '%s'", retrieved_data);
+  else
+    error = clib_error_return (0, "data test FAIL!");
+
+  svm_fifo_segment_free_fifo (sp, f);
+
+  return error;
+}
+
+clib_error_t *
+master (int verbose)
+{
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  svm_fifo_segment_private_t *sp;
+  svm_fifo_t *f;
+  int rv;
+  u8 *test_data;
+  u8 *retrieved_data = 0;
+  int i;
+  int pid = getpid ();
+
+  memset (a, 0, sizeof (*a));
+
+  a->segment_name = "fifo-test1";
+  a->segment_size = 256 << 10;
+
+  rv = svm_fifo_segment_create (a);
+
+  if (rv)
+    return clib_error_return (0, "svm_fifo_segment_create returned %d", rv);
+
+  sp = svm_fifo_get_segment (a->new_segment_index);
+
+  f = svm_fifo_segment_alloc_fifo (sp, 4096);
+
+  if (f == 0)
+    return clib_error_return (0, "svm_fifo_segment_alloc_fifo failed");
+
+  test_data = format (0, "Hello world%c", 0);
+  vec_validate (retrieved_data, vec_len (test_data) - 1);
+
+  for (i = 0; i < 1000; i++)
+    svm_fifo_enqueue_nowait (f, pid, vec_len (test_data), test_data);
+
+  return clib_error_return (0, "master (enqueue) done");
+}
+
+clib_error_t *
+mempig (int verbose)
+{
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  svm_fifo_segment_private_t *sp;
+  svm_fifo_t *f;
+  svm_fifo_t **flist = 0;
+  int rv;
+  int i;
+
+  memset (a, 0, sizeof (*a));
+
+  a->segment_name = "fifo-test1";
+  a->segment_size = 256 << 10;
+
+  rv = svm_fifo_segment_create (a);
+
+  if (rv)
+    return clib_error_return (0, "svm_fifo_segment_create returned %d", rv);
+
+  sp = svm_fifo_get_segment (a->new_segment_index);
+
+  for (i = 0; i < 1000; i++)
+    {
+      f = svm_fifo_segment_alloc_fifo (sp, 4096);
+      if (f == 0)
+       break;
+      vec_add1 (flist, f);
+    }
+
+  fformat (stdout, "Try #1: created %d fifos...\n", vec_len (flist));
+  for (i = 0; i < vec_len (flist); i++)
+    {
+      f = flist[i];
+      svm_fifo_segment_free_fifo (sp, f);
+    }
+
+  _vec_len (flist) = 0;
+
+  for (i = 0; i < 1000; i++)
+    {
+      f = svm_fifo_segment_alloc_fifo (sp, 4096);
+      if (f == 0)
+       break;
+      vec_add1 (flist, f);
+    }
+
+  fformat (stdout, "Try #2: created %d fifos...\n", vec_len (flist));
+  for (i = 0; i < vec_len (flist); i++)
+    {
+      f = flist[i];
+      svm_fifo_segment_free_fifo (sp, f);
+    }
+
+  return 0;
+}
+
+clib_error_t *
+offset (int verbose)
+{
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  svm_fifo_segment_private_t *sp;
+  svm_fifo_t *f;
+  int rv;
+  u32 *test_data = 0;
+  u32 *recovered_data = 0;
+  int i;
+  int pid = getpid ();
+
+  memset (a, 0, sizeof (*a));
+
+  a->segment_name = "fifo-test1";
+  a->segment_size = 256 << 10;
+
+  rv = svm_fifo_segment_create (a);
+
+  if (rv)
+    return clib_error_return (0, "svm_fifo_segment_create returned %d", rv);
+
+  sp = svm_fifo_get_segment (a->new_segment_index);
+
+  f = svm_fifo_segment_alloc_fifo (sp, 200 << 10);
+
+  if (f == 0)
+    return clib_error_return (0, "svm_fifo_segment_alloc_fifo failed");
+
+  for (i = 0; i < (3 * 1024); i++)
+    vec_add1 (test_data, i);
+
+  /* Enqueue the first 1024 u32's */
+  svm_fifo_enqueue_nowait (f, pid, 4096 /* bytes to enqueue */ ,
+                          (u8 *) test_data);
+
+  /* Enqueue the third 1024 u32's 2048 ahead of the current tail */
+  svm_fifo_enqueue_with_offset (f, pid, 4096, 4096, (u8 *) & test_data[2048]);
+
+  /* Enqueue the second 1024 u32's at the current tail */
+  svm_fifo_enqueue_nowait (f, pid, 4096 /* bytes to enqueue */ ,
+                          (u8 *) & test_data[1024]);
+
+  vec_validate (recovered_data, (3 * 1024) - 1);
+
+  svm_fifo_dequeue_nowait (f, pid, 3 * 4096, (u8 *) recovered_data);
+
+  for (i = 0; i < (3 * 1024); i++)
+    {
+      if (recovered_data[i] != test_data[i])
+       {
+         clib_warning ("[%d] expected %d recovered %d", i,
+                       test_data[i], recovered_data[i]);
+         return clib_error_return (0, "offset test FAILED");
+       }
+    }
+
+  return clib_error_return (0, "offset test OK");
+}
+
+clib_error_t *
+slave (int verbose)
+{
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  svm_fifo_segment_private_t *sp;
+  svm_fifo_segment_header_t *fsh;
+  svm_fifo_t *f;
+  ssvm_shared_header_t *sh;
+  int rv;
+  u8 *test_data;
+  u8 *retrieved_data = 0;
+  int pid = getpid ();
+  int i;
+
+  memset (a, 0, sizeof (*a));
+
+  a->segment_name = "fifo-test1";
+
+  rv = svm_fifo_segment_attach (a);
+
+  if (rv)
+    return clib_error_return (0, "svm_fifo_segment_attach returned %d", rv);
+
+  sp = svm_fifo_get_segment (a->new_segment_index);
+  sh = sp->ssvm.sh;
+  fsh = (svm_fifo_segment_header_t *) sh->opaque[0];
+
+  /* might wanna wait.. */
+  f = (svm_fifo_t *) fsh->fifos[0];
+
+  /* Lazy bastards united */
+  test_data = format (0, "Hello world%c", 0);
+  vec_validate (retrieved_data, vec_len (test_data) - 1);
+
+  for (i = 0; i < 1000; i++)
+    {
+      svm_fifo_dequeue_nowait (f, pid, vec_len (retrieved_data),
+                              retrieved_data);
+      if (memcmp (retrieved_data, test_data, vec_len (retrieved_data)))
+       return clib_error_return (0, "retrieved data incorrect, '%s'",
+                                 retrieved_data);
+    }
+
+  return clib_error_return (0, "slave (dequeue) done");
+}
+
+
+int
+test_ssvm_fifo1 (unformat_input_t * input)
+{
+  clib_error_t *error = 0;
+  int verbose = 0;
+  int test_id = 0;
+
+  svm_fifo_segment_init (0x200000000ULL, 20);
+
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "verbose %d", &verbose))
+       ;
+      else if (unformat (input, "verbose"))
+       verbose = 1;
+      else if (unformat (input, "master"))
+       test_id = 1;
+      else if (unformat (input, "slave"))
+       test_id = 2;
+      else if (unformat (input, "mempig"))
+       test_id = 3;
+      else if (unformat (input, "offset"))
+       test_id = 4;
+      else
+       {
+         error = clib_error_create ("unknown input `%U'\n",
+                                    format_unformat_error, input);
+         goto out;
+       }
+    }
+
+  switch (test_id)
+    {
+    case 0:
+      error = hello_world (verbose);
+      break;
+
+    case 1:
+      error = master (verbose);
+      break;
+
+    case 2:
+      error = slave (verbose);
+      break;
+
+    case 3:
+      error = mempig (verbose);
+      break;
+
+    case 4:
+      error = offset (verbose);
+      break;
+
+    default:
+      error = clib_error_return (0, "test id %d unknown", test_id);
+      break;
+    }
+
+out:
+  if (error)
+    clib_error_report (error);
+
+  return 0;
+}
+
+
+
+int
+main (int argc, char *argv[])
+{
+  unformat_input_t i;
+  int r;
+
+  unformat_init_command_line (&i, argv);
+  r = test_ssvm_fifo1 (&i);
+  unformat_free (&i);
+  return r;
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/uri.am b/src/uri.am
new file mode 100644 (file)
index 0000000..8cdd77c
--- /dev/null
@@ -0,0 +1,22 @@
+# Copyright (c) 2016 Cisco and/or its affiliates.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at:
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+noinst_PROGRAMS += uri_udp_test2 uri_tcp_test
+
+uri_udp_test2_SOURCES = uri/uri_udp_test2.c                    
+uri_udp_test2_LDADD = libvlibmemoryclient.la libvlibapi.la libsvm.la \
+       libvppinfra.la -lpthread -lm -lrt 
+
+uri_tcp_test_SOURCES = uri/uri_tcp_test.c
+uri_tcp_test_LDADD = libvlibmemoryclient.la libvlibapi.la libsvm.la \
+       libvppinfra.la -lpthread -lm -lrt 
diff --git a/src/uri/uri_tcp_test.c b/src/uri/uri_tcp_test.c
new file mode 100644 (file)
index 0000000..ed5a37d
--- /dev/null
@@ -0,0 +1,916 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <signal.h>
+#include <vlib/vlib.h>
+#include <vnet/vnet.h>
+#include <svm/svm_fifo_segment.h>
+#include <vlibmemory/api.h>
+#include <vpp/api/vpe_msg_enum.h>
+
+#include "../vnet/session/application_interface.h"
+
+#define vl_typedefs             /* define message structures */
+#include <vpp/api/vpe_all_api_h.h>
+#undef vl_typedefs
+
+/* declare message handlers for each api */
+
+#define vl_endianfun            /* define message structures */
+#include <vpp/api/vpe_all_api_h.h>
+#undef vl_endianfun
+
+/* instantiate all the print functions we know about */
+#define vl_print(handle, ...)
+#define vl_printfun
+#include <vpp/api/vpe_all_api_h.h>
+#undef vl_printfun
+
+/* Satisfy external references when not linking with -lvlib */
+vlib_main_t vlib_global_main;
+vlib_main_t **vlib_mains;
+
+typedef struct
+{
+  svm_fifo_t * server_rx_fifo;
+  svm_fifo_t * server_tx_fifo;
+
+  u32 vpp_session_index;
+  u32 vpp_session_thread;
+} session_t;
+
+typedef enum
+{
+  STATE_START,
+  STATE_READY,
+  STATE_DISCONNECTING,
+  STATE_FAILED
+} connection_state_t;
+
+typedef struct
+{
+  /* vpe input queue */
+  unix_shared_memory_queue_t *vl_input_queue;
+
+  /* API client handle */
+  u32 my_client_index;
+
+  /* The URI we're playing with */
+  u8 * uri;
+
+  /* Session pool */
+  session_t * sessions;
+
+  /* Hash table for disconnect processing */
+  uword * session_index_by_vpp_handles;
+
+  /* intermediate rx buffer */
+  u8 * rx_buf;
+
+  /* URI for slave's connect */
+  u8 * connect_uri;
+
+  u32 connected_session_index;
+
+  int i_am_master;
+
+  /* drop all packets */
+  int drop_packets;
+
+  /* Our event queue */
+  unix_shared_memory_queue_t * our_event_queue;
+
+  /* $$$ single thread only for the moment */
+  unix_shared_memory_queue_t * vpp_event_queue;
+
+  pid_t my_pid;
+
+  /* For deadman timers */
+  clib_time_t clib_time;
+
+  /* State of the connection, shared between msg RX thread and main thread */
+  volatile connection_state_t state;
+
+  /* Signal variables */
+  volatile int time_to_stop;
+  volatile int time_to_print_stats;
+
+  u32 configured_segment_size;
+
+  /* VNET_API_ERROR_FOO -> "Foo" hash table */
+  uword * error_string_by_error_number;
+
+  /* convenience */
+  svm_fifo_segment_main_t * segment_main;
+
+  u8 *connect_test_data;
+} uri_tcp_test_main_t;
+
+uri_tcp_test_main_t uri_tcp_test_main;
+
+#if CLIB_DEBUG > 0
+#define NITER 10000
+#else
+#define NITER 4000000
+#endif
+
+int
+wait_for_state_change (uri_tcp_test_main_t * utm, connection_state_t state)
+{
+#if CLIB_DEBUG > 0
+#define TIMEOUT 600.0
+#else
+#define TIMEOUT 600.0
+#endif
+
+  f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT;
+
+  while (clib_time_now (&utm->clib_time) < timeout)
+    {
+      if (utm->state == state)
+        return 0;
+      if (utm->state == STATE_FAILED)
+       return -1;
+    }
+  clib_warning ("timeout waiting for STATE_READY");
+  return -1;
+}
+
+static void
+init_error_string_table (uri_tcp_test_main_t * utm)
+{
+  utm->error_string_by_error_number = hash_create (0, sizeof (uword));
+
+#define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
+  foreach_vnet_api_error;
+#undef _
+
+  hash_set (utm->error_string_by_error_number, 99, "Misc");
+}
+
+static void
+stop_signal (int signum)
+{
+  uri_tcp_test_main_t *um = &uri_tcp_test_main;
+
+  um->time_to_stop = 1;
+}
+
+static void
+stats_signal (int signum)
+{
+  uri_tcp_test_main_t *um = &uri_tcp_test_main;
+
+  um->time_to_print_stats = 1;
+}
+
+static clib_error_t *
+setup_signal_handlers (void)
+{
+  signal (SIGINT, stats_signal);
+  signal (SIGQUIT, stop_signal);
+  signal (SIGTERM, stop_signal);
+
+  return 0;
+}
+
+void
+vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
+{
+  clib_warning ("BUG");
+}
+
+int
+connect_to_vpp (char *name)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+  api_main_t *am = &api_main;
+
+  if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
+    return -1;
+
+  utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
+  utm->my_client_index = am->my_client_index;
+
+  return 0;
+}
+
+static void
+vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t *mp)
+{
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  int rv;
+
+  a->segment_name = (char *) mp->segment_name;
+  a->segment_size = mp->segment_size;
+  /* Attach to the segment vpp created */
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning ("svm_fifo_segment_attach ('%s') failed",
+                    mp->segment_name);
+      return;
+    }
+  clib_warning ("Mapped new segment '%s' size %d", mp->segment_name,
+                mp->segment_size);
+}
+
+static void
+vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+  session_t * session;
+  vl_api_disconnect_session_reply_t * rmp;
+  uword * p;
+  int rv = 0;
+  u64 key;
+
+  key = (((u64)mp->session_thread_index) << 32) | (u64)mp->session_index;
+
+  p = hash_get (utm->session_index_by_vpp_handles, key);
+
+  if (p)
+    {
+      session = pool_elt_at_index (utm->sessions, p[0]);
+      hash_unset (utm->session_index_by_vpp_handles, key);
+      pool_put (utm->sessions, session);
+    }
+  else
+    {
+      clib_warning ("couldn't find session key %llx", key);
+      rv = -11;
+    }
+
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+
+  rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
+  rmp->retval = rv;
+  rmp->session_index = mp->session_index;
+  rmp->session_thread_index = mp->session_thread_index;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *)&rmp);
+}
+
+static void
+vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+  session_t * session;
+  vl_api_reset_session_reply_t * rmp;
+  uword * p;
+  int rv = 0;
+  u64 key;
+
+  key = (((u64)mp->session_thread_index) << 32) | (u64)mp->session_index;
+
+  p = hash_get(utm->session_index_by_vpp_handles, key);
+
+  if (p)
+    {
+      session = pool_elt_at_index(utm->sessions, p[0]);
+      hash_unset(utm->session_index_by_vpp_handles, key);
+      pool_put(utm->sessions, session);
+    }
+  else
+    {
+      clib_warning("couldn't find session key %llx", key);
+      rv = -11;
+    }
+
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+  rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
+  rmp->retval = rv;
+  rmp->session_index = mp->session_index;
+  rmp->session_thread_index = mp->session_thread_index;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *)&rmp);
+}
+
+void
+handle_fifo_event_connect_rx (uri_tcp_test_main_t *utm, session_fifo_event_t * e)
+{
+  svm_fifo_t * rx_fifo;
+  int n_read, bytes;
+
+  rx_fifo = e->fifo;
+
+  bytes = e->enqueue_length;
+  do
+    {
+      n_read = svm_fifo_dequeue_nowait (rx_fifo, 0, vec_len(utm->rx_buf),
+                                         utm->rx_buf);
+      if (n_read > 0)
+        bytes -= n_read;
+    }
+  while (n_read < 0 || bytes > 0);
+
+  //      bytes_to_read = svm_fifo_max_dequeue (rx_fifo);
+  //
+  //      bytes_to_read = vec_len(utm->rx_buf) > bytes_to_read ?
+  //        bytes_to_read : vec_len(utm->rx_buf);
+  //
+  //      buffer_offset = 0;
+  //      while (bytes_to_read > 0)
+  //        {
+  //          rv = svm_fifo_dequeue_nowait2 (rx_fifo, mypid,
+  //                                         bytes_to_read,
+  //                                         utm->rx_buf + buffer_offset);
+  //          if (rv > 0)
+  //            {
+  //              bytes_to_read -= rv;
+  //              buffer_offset += rv;
+  //              bytes_received += rv;
+  //            }
+  //        }
+
+
+  //  while (bytes_received < bytes_sent)
+  //    {
+  //      rv = svm_fifo_dequeue_nowait2 (rx_fifo, mypid,
+  //                                     vec_len (utm->rx_buf),
+  //                                     utm->rx_buf);
+  //      if (rv > 0)
+  //        {
+  //#if CLIB_DEBUG > 0
+  //          int j;
+  //          for (j = 0; j < rv; j++)
+  //            {
+  //              if (utm->rx_buf[j] != ((bytes_received + j) & 0xff))
+  //                {
+  //                  clib_warning ("error at byte %lld, 0x%x not 0x%x",
+  //                                bytes_received + j,
+  //                                utm->rx_buf[j],
+  //                                ((bytes_received + j )&0xff));
+  //                }
+  //            }
+  //#endif
+  //          bytes_received += (u64) rv;
+  //        }
+  //    }
+}
+
+void
+handle_connect_event_queue (uri_tcp_test_main_t * utm)
+{
+  session_fifo_event_t _e, *e = &_e;;
+
+  unix_shared_memory_queue_sub (utm->our_event_queue, (u8 *) e, 0 /* nowait */);
+  switch (e->event_type)
+    {
+    case FIFO_EVENT_SERVER_RX:
+      handle_fifo_event_connect_rx (utm, e);
+      break;
+
+    case FIFO_EVENT_SERVER_EXIT:
+      return;
+
+    default:
+      clib_warning("unknown event type %d", e->event_type);
+      break;
+    }
+}
+
+void
+uri_tcp_connect_send (uri_tcp_test_main_t *utm)
+{
+  u8 *test_data = utm->connect_test_data;
+  u64 bytes_sent = 0;
+  int rv;
+  int mypid = getpid();
+  session_t * session;
+  svm_fifo_t *tx_fifo;
+  int buffer_offset, bytes_to_send = 0;
+  session_fifo_event_t evt;
+  static int serial_number = 0;
+  int i;
+  u32 max_chunk = 64 << 10, write;
+
+  session = pool_elt_at_index (utm->sessions, utm->connected_session_index);
+  tx_fifo = session->server_tx_fifo;
+
+  vec_validate (utm->rx_buf, vec_len (test_data) - 1);
+
+  for (i = 0; i < 10; i++)
+    {
+      bytes_to_send = vec_len (test_data);
+      buffer_offset = 0;
+      while (bytes_to_send > 0)
+        {
+          write = bytes_to_send > max_chunk ? max_chunk : bytes_to_send;
+          rv = svm_fifo_enqueue_nowait (tx_fifo, mypid, write,
+                                         test_data + buffer_offset);
+
+          if (rv > 0)
+            {
+              bytes_to_send -= rv;
+              buffer_offset += rv;
+              bytes_sent += rv;
+
+              /* Fabricate TX event, send to vpp */
+              evt.fifo = tx_fifo;
+              evt.event_type = FIFO_EVENT_SERVER_TX;
+              /* $$$$ for event logging */
+              evt.enqueue_length = rv;
+              evt.event_id = serial_number++;
+
+              unix_shared_memory_queue_add (utm->vpp_event_queue, (u8 *) &evt,
+                                            0 /* do wait for mutex */);
+            }
+        }
+    }
+}
+
+static void
+uri_tcp_client_test (uri_tcp_test_main_t * utm)
+{
+  vl_api_connect_uri_t * cmp;
+  vl_api_disconnect_session_t *dmp;
+  session_t *connected_session;
+  int i;
+
+  cmp = vl_msg_api_alloc (sizeof (*cmp));
+  memset (cmp, 0, sizeof (*cmp));
+
+  cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
+  cmp->client_index = utm->my_client_index;
+  cmp->context = ntohl(0xfeedface);
+  memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *)&cmp);
+
+  if (wait_for_state_change (utm, STATE_READY))
+    {
+      return;
+    }
+
+  /* Init test data */
+  vec_validate (utm->connect_test_data, 64 * 1024 - 1);
+  for (i = 0; i < vec_len (utm->connect_test_data); i++)
+    utm->connect_test_data[i] = i & 0xff;
+
+  /* Start reader thread */
+  /* handle_connect_event_queue (utm); */
+
+  /* Start send */
+  uri_tcp_connect_send (utm);
+
+  /* Disconnect */
+  connected_session = pool_elt_at_index(utm->sessions,
+                                       utm->connected_session_index);
+  dmp = vl_msg_api_alloc (sizeof (*dmp));
+  memset (dmp, 0, sizeof (*dmp));
+  dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
+  dmp->client_index = utm->my_client_index;
+  dmp->session_index = connected_session->vpp_session_index;
+  dmp->session_thread_index = connected_session->vpp_session_thread;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *)&dmp);
+}
+
+void
+handle_fifo_event_server_rx (uri_tcp_test_main_t *utm, session_fifo_event_t * e)
+{
+  svm_fifo_t * rx_fifo, * tx_fifo;
+  int n_read;
+
+  session_fifo_event_t evt;
+  unix_shared_memory_queue_t *q;
+  int rv, bytes;
+
+  rx_fifo = e->fifo;
+  tx_fifo = utm->sessions[rx_fifo->client_session_index].server_tx_fifo;
+
+  bytes = e->enqueue_length;
+  do
+    {
+      n_read = svm_fifo_dequeue_nowait (rx_fifo, 0, vec_len(utm->rx_buf),
+                                         utm->rx_buf);
+
+      /* Reflect if a non-drop session */
+      if (!utm->drop_packets && n_read > 0)
+        {
+          do
+            {
+              rv = svm_fifo_enqueue_nowait (tx_fifo, 0, n_read, utm->rx_buf);
+            }
+          while (rv == -2);
+
+          /* Fabricate TX event, send to vpp */
+          evt.fifo = tx_fifo;
+          evt.event_type = FIFO_EVENT_SERVER_TX;
+          /* $$$$ for event logging */
+          evt.enqueue_length = n_read;
+          evt.event_id = e->event_id;
+          q = utm->vpp_event_queue;
+          unix_shared_memory_queue_add (q, (u8 *) &evt, 0 /* do wait for mutex */);
+        }
+
+      if (n_read > 0)
+        bytes -= n_read;
+    }
+  while (n_read < 0 || bytes > 0);
+}
+
+void
+handle_event_queue (uri_tcp_test_main_t * utm)
+{
+  session_fifo_event_t _e, *e = &_e;;
+
+  while (1)
+    {
+      unix_shared_memory_queue_sub (utm->our_event_queue, (u8 *)e,
+                                    0 /* nowait */);
+      switch (e->event_type)
+        {
+        case FIFO_EVENT_SERVER_RX:
+          handle_fifo_event_server_rx (utm, e);
+          break;
+
+        case FIFO_EVENT_SERVER_EXIT:
+          return;
+
+        default:
+          clib_warning ("unknown event type %d", e->event_type);
+          break;
+        }
+      if (PREDICT_FALSE(utm->time_to_stop == 1))
+        break;
+      if (PREDICT_FALSE(utm->time_to_print_stats == 1))
+        {
+          utm->time_to_print_stats = 0;
+          fformat(stdout, "%d connections\n", pool_elts (utm->sessions));
+        }
+    }
+}
+
+static void
+vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  int rv;
+
+  if (mp->retval)
+    {
+      clib_warning("bind failed: %d", mp->retval);
+      return;
+    }
+
+  if (mp->segment_name_length == 0)
+    {
+      clib_warning("segment_name_length zero");
+      return;
+    }
+
+  a->segment_name = (char *) mp->segment_name;
+  a->segment_size = mp->segment_size;
+
+  ASSERT(mp->server_event_queue_address);
+
+  /* Attach to the segment vpp created */
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning("svm_fifo_segment_attach ('%s') failed", mp->segment_name);
+      return;
+    }
+
+  utm->our_event_queue =
+      (unix_shared_memory_queue_t *) mp->server_event_queue_address;
+
+  utm->state = STATE_READY;
+}
+
+static void
+vl_api_connect_uri_reply_t_handler (vl_api_connect_uri_reply_t * mp)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  session_t *session;
+  u32 session_index;
+  svm_fifo_t *rx_fifo, *tx_fifo;
+  int rv;
+
+  if (mp->retval)
+    {
+      clib_warning ("connection failed with code: %d", mp->retval);
+      utm->state = STATE_FAILED;
+      return;
+    }
+  /*
+   * Attatch to segment
+   */
+
+  if (mp->segment_name_length == 0)
+    {
+      clib_warning ("segment_name_length zero");
+      utm->state = STATE_FAILED;
+      return;
+    }
+
+  a->segment_name = (char *) mp->segment_name;
+  a->segment_size = mp->segment_size;
+
+  ASSERT(mp->client_event_queue_address);
+
+  /* Attach to the segment vpp created */
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning ("svm_fifo_segment_attach ('%s') failed",
+                    mp->segment_name);
+      return;
+    }
+
+  /*
+   * Save the queues
+   */
+
+  utm->our_event_queue = (unix_shared_memory_queue_t *)
+    mp->client_event_queue_address;
+
+  utm->vpp_event_queue = (unix_shared_memory_queue_t *)
+    mp->vpp_event_queue_address;
+
+  /*
+   * Setup session
+   */
+
+  pool_get (utm->sessions, session);
+  session_index = session - utm->sessions;
+
+  rx_fifo = (svm_fifo_t *)mp->server_rx_fifo;
+  rx_fifo->client_session_index = session_index;
+  tx_fifo = (svm_fifo_t *)mp->server_tx_fifo;
+  tx_fifo->client_session_index = session_index;
+
+  session->server_rx_fifo = rx_fifo;
+  session->server_tx_fifo = tx_fifo;
+  session->vpp_session_index = mp->session_index;
+  session->vpp_session_thread = mp->session_thread_index;
+
+  /* Save handle */
+  utm->connected_session_index = session_index;
+
+  utm->state = STATE_READY;
+}
+
+void
+uri_tcp_bind (uri_tcp_test_main_t *utm)
+{
+  vl_api_bind_uri_t * bmp;
+  u32 fifo_size = 3 << 20;
+  bmp = vl_msg_api_alloc (sizeof (*bmp));
+  memset (bmp, 0, sizeof (*bmp));
+
+  bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
+  bmp->client_index = utm->my_client_index;
+  bmp->context = ntohl(0xfeedface);
+  bmp->initial_segment_size = 256<<20;    /* size of initial segment */
+  bmp->options[SESSION_OPTIONS_FLAGS] =
+    SESSION_OPTIONS_FLAGS_USE_FIFO | SESSION_OPTIONS_FLAGS_ADD_SEGMENT;
+  bmp->options[SESSION_OPTIONS_RX_FIFO_SIZE] = fifo_size;
+  bmp->options[SESSION_OPTIONS_TX_FIFO_SIZE] = fifo_size;
+  bmp->options[SESSION_OPTIONS_ADD_SEGMENT_SIZE] = 128<<20;
+  memcpy (bmp->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *)&bmp);
+}
+
+static void
+vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t *mp)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+
+  if (mp->retval != 0)
+    clib_warning ("returned %d", ntohl(mp->retval));
+
+  utm->state = STATE_START;
+}
+
+void
+uri_tcp_unbind (uri_tcp_test_main_t *utm)
+{
+  vl_api_unbind_uri_t * ump;
+
+  ump = vl_msg_api_alloc (sizeof (*ump));
+  memset (ump, 0, sizeof (*ump));
+
+  ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
+  ump->client_index = utm->my_client_index;
+  memcpy (ump->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *)&ump);
+}
+
+static void
+vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+  vl_api_accept_session_reply_t *rmp;
+  svm_fifo_t * rx_fifo, * tx_fifo;
+  session_t * session;
+  static f64 start_time;
+  u64 key;
+  u32 session_index;
+
+  if (start_time == 0.0)
+      start_time = clib_time_now (&utm->clib_time);
+
+  utm->vpp_event_queue = (unix_shared_memory_queue_t *)
+    mp->vpp_event_queue_address;
+
+  /* Allocate local session and set it up */
+  pool_get (utm->sessions, session);
+  session_index = session - utm->sessions;
+
+  rx_fifo = (svm_fifo_t *)mp->server_rx_fifo;
+  rx_fifo->client_session_index = session_index;
+  tx_fifo = (svm_fifo_t *)mp->server_tx_fifo;
+  tx_fifo->client_session_index = session_index;
+
+  session->server_rx_fifo = rx_fifo;
+  session->server_tx_fifo = tx_fifo;
+
+  /* Add it to lookup table */
+  key = (((u64)mp->session_thread_index) << 32) | (u64)mp->session_index;
+  hash_set (utm->session_index_by_vpp_handles, key, session_index);
+
+  utm->state = STATE_READY;
+
+  /* Stats printing */
+  if (pool_elts (utm->sessions) && (pool_elts(utm->sessions) % 20000) == 0)
+    {
+      f64 now = clib_time_now (&utm->clib_time);
+      fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
+               pool_elts(utm->sessions), now - start_time,
+               (f64)pool_elts(utm->sessions) / (now - start_time));
+    }
+
+  /* Send accept reply to vpp */
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+  rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
+  rmp->session_type = mp->session_type;
+  rmp->session_index = mp->session_index;
+  rmp->session_thread_index = mp->session_thread_index;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *)&rmp);
+}
+
+void
+uri_tcp_server_test (uri_tcp_test_main_t * utm)
+{
+
+  /* Bind to uri */
+  uri_tcp_bind (utm);
+
+  if (wait_for_state_change (utm, STATE_READY))
+    {
+      clib_warning ("timeout waiting for STATE_READY");
+      return;
+    }
+
+  /* Enter handle event loop */
+  handle_event_queue (utm);
+
+  /* Cleanup */
+  uri_tcp_unbind (utm);
+
+  if (wait_for_state_change (utm, STATE_START))
+    {
+      clib_warning ("timeout waiting for STATE_START");
+      return;
+    }
+
+  fformat (stdout, "Test complete...\n");
+}
+
+#define foreach_uri_msg                         \
+_(BIND_URI_REPLY, bind_uri_reply)               \
+_(UNBIND_URI_REPLY, unbind_uri_reply)           \
+_(ACCEPT_SESSION, accept_session)               \
+_(CONNECT_URI_REPLY, connect_uri_reply)         \
+_(DISCONNECT_SESSION, disconnect_session)       \
+_(RESET_SESSION, reset_session)                \
+_(MAP_ANOTHER_SEGMENT, map_another_segment)
+
+void
+uri_api_hookup (uri_tcp_test_main_t * utm)
+{
+#define _(N,n)                                                  \
+    vl_msg_api_set_handlers(VL_API_##N, #n,                     \
+                           vl_api_##n##_t_handler,              \
+                           vl_noop_handler,                     \
+                           vl_api_##n##_t_endian,               \
+                           vl_api_##n##_t_print,                \
+                           sizeof(vl_api_##n##_t), 1);
+  foreach_uri_msg;
+#undef _
+}
+
+int
+main (int argc, char **argv)
+{
+  uri_tcp_test_main_t *utm = &uri_tcp_test_main;
+  unformat_input_t _argv, *a = &_argv;
+  u8 *chroot_prefix;
+  u8 *heap;
+  u8 * bind_name = (u8 *) "tcp://0.0.0.0/1234";
+  u32 tmp;
+  mheap_t *h;
+  session_t * session;
+  int i;
+  int i_am_master = 1, drop_packets = 0;
+
+  clib_mem_init (0, 256 << 20);
+
+  heap = clib_mem_get_per_cpu_heap ();
+  h = mheap_header (heap);
+
+  /* make the main heap thread-safe */
+  h->flags |= MHEAP_FLAG_THREAD_SAFE;
+
+  vec_validate (utm->rx_buf, 65536);
+
+  utm->session_index_by_vpp_handles =
+    hash_create (0, sizeof(uword));
+
+  utm->my_pid = getpid();
+  utm->configured_segment_size = 1<<20;
+
+  clib_time_init (&utm->clib_time);
+  init_error_string_table (utm);
+  svm_fifo_segment_init(0x200000000ULL, 20);
+  unformat_init_command_line (a, argv);
+
+  while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (a, "chroot prefix %s", &chroot_prefix))
+        {
+          vl_set_memory_root_path ((char *) chroot_prefix);
+        }
+      else if (unformat (a, "uri %s", &bind_name))
+        ;
+      else if (unformat (a, "segment-size %dM", &tmp))
+        utm->configured_segment_size = tmp<<20;
+      else if (unformat (a, "segment-size %dG", &tmp))
+        utm->configured_segment_size = tmp<<30;
+      else if (unformat (a, "master"))
+        i_am_master = 1;
+      else if (unformat (a, "slave"))
+        i_am_master = 0;
+      else if (unformat (a, "drop"))
+        drop_packets = 1;
+      else
+        {
+          fformat (stderr, "%s: usage [master|slave]\n");
+          exit (1);
+        }
+    }
+
+  utm->uri = format (0, "%s%c", bind_name, 0);
+  utm->i_am_master = i_am_master;
+  utm->segment_main = &svm_fifo_segment_main;
+  utm->drop_packets = drop_packets;
+
+  utm->connect_uri = format (0, "tcp://6.0.1.2/1234%c", 0);
+
+  setup_signal_handlers();
+  uri_api_hookup (utm);
+
+  if (connect_to_vpp (i_am_master? "uri_tcp_server":"uri_tcp_client") < 0)
+    {
+      svm_region_exit ();
+      fformat (stderr, "Couldn't connect to vpe, exiting...\n");
+      exit (1);
+    }
+
+  if (i_am_master == 0)
+    {
+      uri_tcp_client_test (utm);
+      exit (0);
+    }
+
+  /* $$$$ hack preallocation */
+  for (i = 0; i < 200000; i++)
+    {
+      pool_get (utm->sessions, session);
+      memset (session, 0, sizeof (*session));
+    }
+  for (i = 0; i < 200000; i++)
+    pool_put_index (utm->sessions, i);
+
+  uri_tcp_server_test (utm);
+
+  vl_client_disconnect_from_vlib ();
+  exit (0);
+}
diff --git a/src/uri/uri_udp_test.c b/src/uri/uri_udp_test.c
new file mode 100644 (file)
index 0000000..6f5284c
--- /dev/null
@@ -0,0 +1,553 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <vppinfra/clib.h>
+#include <vppinfra/format.h>
+#include <vppinfra/error.h>
+#include <vppinfra/time.h>
+#include <vppinfra/macros.h>
+#include <vnet/vnet.h>
+#include <vlib/vlib.h>
+#include <vlib/unix/unix.h>
+#include <vlibapi/api.h>
+#include <vlibmemory/api.h>
+#include <vpp-api/vpe_msg_enum.h>
+#include <svm_fifo_segment.h>
+
+#include <vnet/uri/uri.h>
+
+#define vl_typedefs            /* define message structures */
+#include <vpp-api/vpe_all_api_h.h>
+#undef vl_typedefs
+
+/* declare message handlers for each api */
+
+#define vl_endianfun           /* define message structures */
+#include <vpp-api/vpe_all_api_h.h>
+#undef vl_endianfun
+
+/* instantiate all the print functions we know about */
+#define vl_print(handle, ...)
+#define vl_printfun
+#include <vpp-api/vpe_all_api_h.h>
+#undef vl_printfun
+
+/* Satisfy external references when not linking with -lvlib */
+vlib_main_t vlib_global_main;
+vlib_main_t **vlib_mains;
+
+typedef enum
+{
+  STATE_START,
+  STATE_READY,
+  STATE_DISCONNECTING,
+} connection_state_t;
+
+typedef struct
+{
+  svm_fifo_t *server_rx_fifo;
+  svm_fifo_t *server_tx_fifo;
+} session_t;
+
+typedef struct
+{
+  /* vpe input queue */
+  unix_shared_memory_queue_t *vl_input_queue;
+
+  /* API client handle */
+  u32 my_client_index;
+
+  /* The URI we're playing with */
+  u8 *uri;
+
+  /* Session pool */
+  session_t *sessions;
+
+  /* Hash table for disconnect processing */
+  uword *session_index_by_vpp_handles;
+
+  /* fifo segment */
+  svm_fifo_segment_private_t *seg;
+
+  /* intermediate rx buffer */
+  u8 *rx_buf;
+
+  /* Our event queue */
+  unix_shared_memory_queue_t *our_event_queue;
+
+  /* $$$ single thread only for the moment */
+  unix_shared_memory_queue_t *vpp_event_queue;
+
+  /* For deadman timers */
+  clib_time_t clib_time;
+
+  /* State of the connection, shared between msg RX thread and main thread */
+  volatile connection_state_t state;
+
+  volatile int time_to_stop;
+  volatile int time_to_print_stats;
+
+  /* VNET_API_ERROR_FOO -> "Foo" hash table */
+  uword *error_string_by_error_number;
+} uri_udp_test_main_t;
+
+#if CLIB_DEBUG > 0
+#define NITER 1000
+#else
+#define NITER 1000000
+#endif
+
+uri_udp_test_main_t uri_udp_test_main;
+
+static void
+stop_signal (int signum)
+{
+  uri_udp_test_main_t *um = &uri_udp_test_main;
+
+  um->time_to_stop = 1;
+}
+
+static void
+stats_signal (int signum)
+{
+  uri_udp_test_main_t *um = &uri_udp_test_main;
+
+  um->time_to_print_stats = 1;
+}
+
+static clib_error_t *
+setup_signal_handlers (void)
+{
+  signal (SIGINT, stats_signal);
+  signal (SIGQUIT, stop_signal);
+  signal (SIGTERM, stop_signal);
+
+  return 0;
+}
+
+u8 *
+format_api_error (u8 * s, va_list * args)
+{
+  uri_udp_test_main_t *utm = va_arg (*args, uri_udp_test_main_t *);
+  i32 error = va_arg (*args, u32);
+  uword *p;
+
+  p = hash_get (utm->error_string_by_error_number, -error);
+
+  if (p)
+    s = format (s, "%s", p[0]);
+  else
+    s = format (s, "%d", error);
+  return s;
+}
+
+int
+wait_for_state_change (uri_udp_test_main_t * utm, connection_state_t state)
+{
+  f64 timeout = clib_time_now (&utm->clib_time) + 5.0;
+
+  while (clib_time_now (&utm->clib_time) < timeout)
+    {
+      if (utm->state == state)
+       return 0;
+    }
+  return -1;
+}
+
+static void
+vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  int rv;
+
+  if (mp->segment_name_length == 0)
+    {
+      clib_warning ("segment_name_length zero");
+      return;
+    }
+
+  a->segment_name = (char *) mp->segment_name;
+
+  /* Attach to the segment vpp created */
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning ("sm_fifo_segment_create ('%s') failed", mp->segment_name);
+      return;
+    }
+
+  utm->our_event_queue = (unix_shared_memory_queue_t *)
+    mp->server_event_queue_address;
+
+  utm->state = STATE_READY;
+}
+
+static void
+vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+
+  if (mp->retval != 0)
+    clib_warning ("returned %d", ntohl (mp->retval));
+
+  utm->state = STATE_START;
+}
+
+static void
+vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  vl_api_accept_session_reply_t *rmp;
+  svm_fifo_t *rx_fifo, *tx_fifo;
+  session_t *session;
+  static f64 start_time;
+  u64 key;
+
+  if (start_time == 0.0)
+    start_time = clib_time_now (&utm->clib_time);
+
+  utm->vpp_event_queue = (unix_shared_memory_queue_t *)
+    mp->vpp_event_queue_address;
+
+  pool_get (utm->sessions, session);
+
+  rx_fifo = (svm_fifo_t *) mp->server_rx_fifo;
+  rx_fifo->client_session_index = session - utm->sessions;
+  tx_fifo = (svm_fifo_t *) mp->server_tx_fifo;
+  tx_fifo->client_session_index = session - utm->sessions;
+
+  session->server_rx_fifo = rx_fifo;
+  session->server_tx_fifo = tx_fifo;
+
+  key = (((u64) mp->session_thread_index) << 32) | (u64) mp->session_index;
+
+  hash_set (utm->session_index_by_vpp_handles, key, session - utm->sessions);
+
+  utm->state = STATE_READY;
+
+  if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0)
+    {
+      f64 now = clib_time_now (&utm->clib_time);
+      fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
+              pool_elts (utm->sessions), now - start_time,
+              (f64) pool_elts (utm->sessions) / (now - start_time));
+    }
+
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+  rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
+  rmp->session_type = mp->session_type;
+  rmp->session_index = mp->session_index;
+  rmp->session_thread_index = mp->session_thread_index;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
+}
+
+static void
+vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  session_t *session;
+  vl_api_disconnect_session_reply_t *rmp;
+  uword *p;
+  int rv = 0;
+  u64 key;
+
+  key = (((u64) mp->session_thread_index) << 32) | (u64) mp->session_index;
+
+  p = hash_get (utm->session_index_by_vpp_handles, key);
+
+  if (p)
+    {
+      session = pool_elt_at_index (utm->sessions, p[0]);
+      hash_unset (utm->session_index_by_vpp_handles, key);
+      pool_put (utm->sessions, session);
+    }
+  else
+    {
+      clib_warning ("couldn't find session key %llx", key);
+      rv = -11;
+    }
+
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+  rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
+  rmp->retval = rv;
+  rmp->session_index = mp->session_index;
+  rmp->session_thread_index = mp->session_thread_index;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
+}
+
+#define foreach_uri_msg                         \
+_(BIND_URI_REPLY, bind_uri_reply)               \
+_(UNBIND_URI_REPLY, unbind_uri_reply)           \
+_(ACCEPT_SESSION, accept_session)              \
+_(DISCONNECT_SESSION, disconnect_session)
+
+void
+uri_api_hookup (uri_udp_test_main_t * utm)
+{
+#define _(N,n)                                                  \
+    vl_msg_api_set_handlers(VL_API_##N, #n,                     \
+                           vl_api_##n##_t_handler,             \
+                           vl_noop_handler,                     \
+                           vl_api_##n##_t_endian,               \
+                           vl_api_##n##_t_print,                \
+                           sizeof(vl_api_##n##_t), 1);
+  foreach_uri_msg;
+#undef _
+
+}
+
+
+int
+connect_to_vpp (char *name)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  api_main_t *am = &api_main;
+
+  if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
+    return -1;
+
+  utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
+  utm->my_client_index = am->my_client_index;
+
+  return 0;
+}
+
+void
+vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
+{
+  clib_warning ("BUG");
+}
+
+static void
+init_error_string_table (uri_udp_test_main_t * utm)
+{
+  utm->error_string_by_error_number = hash_create (0, sizeof (uword));
+
+#define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
+  foreach_vnet_api_error;
+#undef _
+
+  hash_set (utm->error_string_by_error_number, 99, "Misc");
+}
+
+void
+handle_fifo_event_server_rx (uri_udp_test_main_t * utm,
+                            session_fifo_event_t * e)
+{
+  svm_fifo_t *rx_fifo, *tx_fifo;
+  int nbytes;
+
+  session_fifo_event_t evt;
+  unix_shared_memory_queue_t *q;
+  int rv;
+
+  rx_fifo = e->fifo;
+  tx_fifo = utm->sessions[rx_fifo->client_session_index].server_tx_fifo;
+
+  do
+    {
+      nbytes = svm_fifo_dequeue_nowait (rx_fifo, 0,
+                                       vec_len (utm->rx_buf), utm->rx_buf);
+    }
+  while (nbytes <= 0);
+  do
+    {
+      rv = svm_fifo_enqueue_nowait (tx_fifo, 0, nbytes, utm->rx_buf);
+    }
+  while (rv == -2);
+
+  /* Fabricate TX event, send to vpp */
+  evt.fifo = tx_fifo;
+  evt.event_type = FIFO_EVENT_SERVER_TX;
+  /* $$$$ for event logging */
+  evt.enqueue_length = nbytes;
+  evt.event_id = e->event_id;
+  q = utm->vpp_event_queue;
+  unix_shared_memory_queue_add (q, (u8 *) & evt, 0 /* do wait for mutex */ );
+}
+
+void
+handle_event_queue (uri_udp_test_main_t * utm)
+{
+  session_fifo_event_t _e, *e = &_e;;
+
+  while (1)
+    {
+      unix_shared_memory_queue_sub (utm->our_event_queue, (u8 *) e,
+                                   0 /* nowait */ );
+      switch (e->event_type)
+       {
+       case FIFO_EVENT_SERVER_RX:
+         handle_fifo_event_server_rx (utm, e);
+         break;
+
+       case FIFO_EVENT_SERVER_EXIT:
+         return;
+
+       default:
+         clib_warning ("unknown event type %d", e->event_type);
+         break;
+       }
+      if (PREDICT_FALSE (utm->time_to_stop == 1))
+       break;
+      if (PREDICT_FALSE (utm->time_to_print_stats == 1))
+       {
+         utm->time_to_print_stats = 0;
+         fformat (stdout, "%d connections\n", pool_elts (utm->sessions));
+       }
+    }
+}
+
+void
+uri_udp_test (uri_udp_test_main_t * utm)
+{
+  vl_api_bind_uri_t *bmp;
+  vl_api_unbind_uri_t *ump;
+
+  bmp = vl_msg_api_alloc (sizeof (*bmp));
+  memset (bmp, 0, sizeof (*bmp));
+
+  bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
+  bmp->client_index = utm->my_client_index;
+  bmp->context = ntohl (0xfeedface);
+  bmp->segment_size = 2 << 30;
+  memcpy (bmp->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
+
+  if (wait_for_state_change (utm, STATE_READY))
+    {
+      clib_warning ("timeout waiting for STATE_READY");
+      return;
+    }
+
+  handle_event_queue (utm);
+
+  ump = vl_msg_api_alloc (sizeof (*ump));
+  memset (ump, 0, sizeof (*ump));
+
+  ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
+  ump->client_index = utm->my_client_index;
+  memcpy (ump->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
+
+  if (wait_for_state_change (utm, STATE_START))
+    {
+      clib_warning ("timeout waiting for STATE_START");
+      return;
+    }
+
+  fformat (stdout, "Test complete...\n");
+}
+
+int
+main (int argc, char **argv)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  unformat_input_t _argv, *a = &_argv;
+  u8 *chroot_prefix;
+  u8 *heap;
+  u8 *bind_name = (u8 *) "udp4:1234";
+  mheap_t *h;
+  session_t *session;
+  int i;
+
+  clib_mem_init (0, 256 << 20);
+
+  heap = clib_mem_get_per_cpu_heap ();
+  h = mheap_header (heap);
+
+  /* make the main heap thread-safe */
+  h->flags |= MHEAP_FLAG_THREAD_SAFE;
+
+  vec_validate (utm->rx_buf, 8192);
+
+  utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
+
+  clib_time_init (&utm->clib_time);
+  init_error_string_table (utm);
+  svm_fifo_segment_init (0x200000000ULL, 20);
+  unformat_init_command_line (a, argv);
+
+  while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (a, "chroot prefix %s", &chroot_prefix))
+       {
+         vl_set_memory_root_path ((char *) chroot_prefix);
+       }
+      else if (unformat (a, "uri %s", &bind_name))
+       ;
+      else
+       {
+         fformat (stderr, "%s: usage [master|slave]\n");
+         exit (1);
+       }
+    }
+
+  utm->uri = format (0, "%s%c", bind_name, 0);
+
+  setup_signal_handlers ();
+
+  uri_api_hookup (utm);
+
+  if (connect_to_vpp ("uri_udp_test") < 0)
+    {
+      svm_region_exit ();
+      fformat (stderr, "Couldn't connect to vpe, exiting...\n");
+      exit (1);
+    }
+
+  /* $$$$ hack preallocation */
+  for (i = 0; i < 200000; i++)
+    {
+      pool_get (utm->sessions, session);
+      memset (session, 0, sizeof (*session));
+    }
+  for (i = 0; i < 200000; i++)
+    pool_put_index (utm->sessions, i);
+
+  uri_udp_test (utm);
+
+  vl_client_disconnect_from_vlib ();
+  exit (0);
+}
+
+#undef vl_api_version
+#define vl_api_version(n,v) static u32 vpe_api_version = v;
+#include <vpp-api/vpe.api.h>
+#undef vl_api_version
+
+void
+vl_client_add_api_signatures (vl_api_memclnt_create_t * mp)
+{
+  /*
+   * Send the main API signature in slot 0. This bit of code must
+   * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
+   */
+  mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/uri/uri_udp_test2.c b/src/uri/uri_udp_test2.c
new file mode 100644 (file)
index 0000000..ddfffaa
--- /dev/null
@@ -0,0 +1,954 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <vppinfra/clib.h>
+#include <vppinfra/format.h>
+#include <vppinfra/error.h>
+#include <vppinfra/time.h>
+#include <vppinfra/macros.h>
+#include <vnet/vnet.h>
+#include <vlib/vlib.h>
+#include <vlib/unix/unix.h>
+#include <vlibapi/api.h>
+#include <vlibmemory/api.h>
+#include <vpp/api/vpe_msg_enum.h>
+#include <svm/svm_fifo_segment.h>
+#include <pthread.h>
+
+#include "../vnet/session/application_interface.h"
+
+#define vl_typedefs            /* define message structures */
+#include <vpp/api/vpe_all_api_h.h>
+#undef vl_typedefs
+
+/* declare message handlers for each api */
+
+#define vl_endianfun           /* define message structures */
+#include <vpp/api/vpe_all_api_h.h>
+#undef vl_endianfun
+
+/* instantiate all the print functions we know about */
+#define vl_print(handle, ...)
+#define vl_printfun
+#include <vpp/api/vpe_all_api_h.h>
+#undef vl_printfun
+
+/* Satisfy external references when not linking with -lvlib */
+vlib_main_t vlib_global_main;
+vlib_main_t **vlib_mains;
+
+typedef enum
+{
+  STATE_START,
+  STATE_READY,
+  STATE_DISCONNECTING,
+} connection_state_t;
+
+typedef struct
+{
+  svm_fifo_t *server_rx_fifo;
+  svm_fifo_t *server_tx_fifo;
+} session_t;
+
+typedef struct
+{
+  /* vpe input queue */
+  unix_shared_memory_queue_t *vl_input_queue;
+
+  /* API client handle */
+  u32 my_client_index;
+
+  /* The URI we're playing with */
+  u8 *uri;
+
+  /* Session pool */
+  session_t *sessions;
+
+  /* Hash table for disconnect processing */
+  uword *session_index_by_vpp_handles;
+
+  /* fifo segment */
+  svm_fifo_segment_private_t *seg;
+
+  /* intermediate rx buffer */
+  u8 *rx_buf;
+
+  /* URI for connect */
+  u8 *connect_uri;
+
+  int i_am_master;
+
+  /* Our event queue */
+  unix_shared_memory_queue_t *our_event_queue;
+
+  /* $$$ single thread only for the moment */
+  unix_shared_memory_queue_t *vpp_event_queue;
+
+  /* $$$$ hack: cut-through session index */
+  volatile u32 cut_through_session_index;
+
+  /* unique segment name counter */
+  u32 unique_segment_index;
+
+  pid_t my_pid;
+
+  /* pthread handle */
+  pthread_t cut_through_thread_handle;
+
+  /* For deadman timers */
+  clib_time_t clib_time;
+
+  /* State of the connection, shared between msg RX thread and main thread */
+  volatile connection_state_t state;
+
+  volatile int time_to_stop;
+  volatile int time_to_print_stats;
+
+  u32 configured_segment_size;
+
+  /* VNET_API_ERROR_FOO -> "Foo" hash table */
+  uword *error_string_by_error_number;
+
+  /* convenience */
+  svm_fifo_segment_main_t *segment_main;
+
+} uri_udp_test_main_t;
+
+#if CLIB_DEBUG > 0
+#define NITER 10000
+#else
+#define NITER 4000000
+#endif
+
+uri_udp_test_main_t uri_udp_test_main;
+
+static void
+stop_signal (int signum)
+{
+  uri_udp_test_main_t *um = &uri_udp_test_main;
+
+  um->time_to_stop = 1;
+}
+
+static void
+stats_signal (int signum)
+{
+  uri_udp_test_main_t *um = &uri_udp_test_main;
+
+  um->time_to_print_stats = 1;
+}
+
+static clib_error_t *
+setup_signal_handlers (void)
+{
+  signal (SIGINT, stats_signal);
+  signal (SIGQUIT, stop_signal);
+  signal (SIGTERM, stop_signal);
+
+  return 0;
+}
+
+u8 *
+format_api_error (u8 * s, va_list * args)
+{
+  uri_udp_test_main_t *utm = va_arg (*args, uri_udp_test_main_t *);
+  i32 error = va_arg (*args, u32);
+  uword *p;
+
+  p = hash_get (utm->error_string_by_error_number, -error);
+
+  if (p)
+    s = format (s, "%s", p[0]);
+  else
+    s = format (s, "%d", error);
+  return s;
+}
+
+int
+wait_for_state_change (uri_udp_test_main_t * utm, connection_state_t state)
+{
+#if CLIB_DEBUG > 0
+#define TIMEOUT 600.0
+#else
+#define TIMEOUT 600.0
+#endif
+
+  f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT;
+
+  while (clib_time_now (&utm->clib_time) < timeout)
+    {
+      if (utm->state == state)
+       return 0;
+    }
+  return -1;
+}
+
+u64 server_bytes_received, server_bytes_sent;
+
+static void *
+cut_through_thread_fn (void *arg)
+{
+  session_t *s;
+  svm_fifo_t *rx_fifo;
+  svm_fifo_t *tx_fifo;
+  u8 *my_copy_buffer = 0;
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  i32 actual_transfer;
+  int rv;
+  u32 buffer_offset;
+
+  while (utm->cut_through_session_index == ~0)
+    ;
+
+  s = pool_elt_at_index (utm->sessions, utm->cut_through_session_index);
+
+  rx_fifo = s->server_rx_fifo;
+  tx_fifo = s->server_tx_fifo;
+
+  vec_validate (my_copy_buffer, 64 * 1024 - 1);
+
+  while (true)
+    {
+      /* We read from the tx fifo and write to the rx fifo */
+      do
+       {
+         actual_transfer = svm_fifo_dequeue_nowait (tx_fifo, 0,
+                                                    vec_len (my_copy_buffer),
+                                                    my_copy_buffer);
+       }
+      while (actual_transfer <= 0);
+
+      server_bytes_received += actual_transfer;
+
+      buffer_offset = 0;
+      while (actual_transfer > 0)
+       {
+         rv = svm_fifo_enqueue_nowait (rx_fifo, 0, actual_transfer,
+                                       my_copy_buffer + buffer_offset);
+         if (rv > 0)
+           {
+             actual_transfer -= rv;
+             buffer_offset += rv;
+             server_bytes_sent += rv;
+           }
+
+       }
+      if (PREDICT_FALSE (utm->time_to_stop))
+       break;
+    }
+
+  pthread_exit (0);
+}
+
+static void
+uri_udp_slave_test (uri_udp_test_main_t * utm)
+{
+  vl_api_connect_uri_t *cmp;
+  int i;
+  u8 *test_data = 0;
+  u64 bytes_received = 0, bytes_sent = 0;
+  i32 bytes_to_read;
+  int rv;
+  int mypid = getpid ();
+  f64 before, after, delta, bytes_per_second;
+  session_t *session;
+  svm_fifo_t *rx_fifo, *tx_fifo;
+  int buffer_offset, bytes_to_send = 0;
+
+  vec_validate (test_data, 64 * 1024 - 1);
+  for (i = 0; i < vec_len (test_data); i++)
+    test_data[i] = i & 0xff;
+
+  cmp = vl_msg_api_alloc (sizeof (*cmp));
+  memset (cmp, 0, sizeof (*cmp));
+
+  cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
+  cmp->client_index = utm->my_client_index;
+  cmp->context = ntohl (0xfeedface);
+  memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp);
+
+  if (wait_for_state_change (utm, STATE_READY))
+    {
+      clib_warning ("timeout waiting for STATE_READY");
+      return;
+    }
+
+  session = pool_elt_at_index (utm->sessions, utm->cut_through_session_index);
+  rx_fifo = session->server_rx_fifo;
+  tx_fifo = session->server_tx_fifo;
+
+  before = clib_time_now (&utm->clib_time);
+
+  vec_validate (utm->rx_buf, vec_len (test_data) - 1);
+
+  for (i = 0; i < NITER; i++)
+    {
+      bytes_to_send = vec_len (test_data);
+      buffer_offset = 0;
+      while (bytes_to_send > 0)
+       {
+         rv = svm_fifo_enqueue_nowait (tx_fifo, mypid,
+                                       bytes_to_send,
+                                       test_data + buffer_offset);
+
+         if (rv > 0)
+           {
+             bytes_to_send -= rv;
+             buffer_offset += rv;
+             bytes_sent += rv;
+           }
+       }
+
+      bytes_to_read = svm_fifo_max_dequeue (rx_fifo);
+
+      bytes_to_read = vec_len (utm->rx_buf) > bytes_to_read ?
+       bytes_to_read : vec_len (utm->rx_buf);
+
+      buffer_offset = 0;
+      while (bytes_to_read > 0)
+       {
+         rv = svm_fifo_dequeue_nowait (rx_fifo, mypid,
+                                       bytes_to_read,
+                                       utm->rx_buf + buffer_offset);
+         if (rv > 0)
+           {
+             bytes_to_read -= rv;
+             buffer_offset += rv;
+             bytes_received += rv;
+           }
+       }
+    }
+  while (bytes_received < bytes_sent)
+    {
+      rv = svm_fifo_dequeue_nowait (rx_fifo, mypid,
+                                   vec_len (utm->rx_buf), utm->rx_buf);
+      if (rv > 0)
+       {
+#if CLIB_DEBUG > 0
+         int j;
+         for (j = 0; j < rv; j++)
+           {
+             if (utm->rx_buf[j] != ((bytes_received + j) & 0xff))
+               {
+                 clib_warning ("error at byte %lld, 0x%x not 0x%x",
+                               bytes_received + j,
+                               utm->rx_buf[j],
+                               ((bytes_received + j) & 0xff));
+               }
+           }
+#endif
+         bytes_received += (u64) rv;
+       }
+    }
+
+  after = clib_time_now (&utm->clib_time);
+  delta = after - before;
+  bytes_per_second = 0.0;
+
+  if (delta > 0.0)
+    bytes_per_second = (f64) bytes_received / delta;
+
+  fformat (stdout,
+          "Done: %lld recv bytes in %.2f seconds, %.2f bytes/sec...\n\n",
+          bytes_received, delta, bytes_per_second);
+  fformat (stdout,
+          "Done: %lld sent bytes in %.2f seconds, %.2f bytes/sec...\n\n",
+          bytes_sent, delta, bytes_per_second);
+  fformat (stdout,
+          "client -> server -> client round trip: %.2f Gbit/sec \n\n",
+          (bytes_per_second * 8.0) / 1e9);
+}
+
+static void
+vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  int rv;
+
+  if (mp->segment_name_length == 0)
+    {
+      clib_warning ("segment_name_length zero");
+      return;
+    }
+
+  a->segment_name = (char *) mp->segment_name;
+  a->segment_size = mp->segment_size;
+
+  ASSERT (mp->server_event_queue_address);
+
+  /* Attach to the segment vpp created */
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning ("svm_fifo_segment_attach ('%s') failed",
+                   mp->segment_name);
+      return;
+    }
+
+  utm->our_event_queue = (unix_shared_memory_queue_t *)
+    mp->server_event_queue_address;
+
+  utm->state = STATE_READY;
+}
+
+static void
+vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
+{
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  int rv;
+
+  a->segment_name = (char *) mp->segment_name;
+  a->segment_size = mp->segment_size;
+  /* Attach to the segment vpp created */
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning ("svm_fifo_segment_attach ('%s') failed",
+                   mp->segment_name);
+      return;
+    }
+  clib_warning ("Mapped new segment '%s' size %d", mp->segment_name,
+               mp->segment_size);
+}
+
+static void
+vl_api_connect_uri_t_handler (vl_api_connect_uri_t * mp)
+{
+  u32 segment_index;
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  svm_fifo_segment_private_t *seg;
+  unix_shared_memory_queue_t *client_q;
+  vl_api_connect_uri_reply_t *rmp;
+  session_t *session;
+  int rv = 0;
+
+  /* Create the segment */
+  a->segment_name = (char *) format (0, "%d:segment%d%c", utm->my_pid,
+                                    utm->unique_segment_index++, 0);
+  a->segment_size = utm->configured_segment_size;
+
+  rv = svm_fifo_segment_create (a);
+  if (rv)
+    {
+      clib_warning ("sm_fifo_segment_create ('%s') failed", a->segment_name);
+      rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
+      goto send_reply;
+    }
+
+  vec_add2 (utm->seg, seg, 1);
+
+  segment_index = vec_len (sm->segments) - 1;
+
+  memcpy (seg, sm->segments + segment_index, sizeof (utm->seg[0]));
+
+  pool_get (utm->sessions, session);
+
+  /*
+   * By construction the master's idea of the rx fifo ends up in
+   * fsh->fifos[0], and the master's idea of the tx fifo ends up in
+   * fsh->fifos[1].
+   */
+  session->server_rx_fifo = svm_fifo_segment_alloc_fifo (utm->seg,
+                                                        128 * 1024);
+  ASSERT (session->server_rx_fifo);
+
+  session->server_tx_fifo = svm_fifo_segment_alloc_fifo (utm->seg,
+                                                        128 * 1024);
+  ASSERT (session->server_tx_fifo);
+
+  session->server_rx_fifo->server_session_index = session - utm->sessions;
+  session->server_tx_fifo->server_session_index = session - utm->sessions;
+  utm->cut_through_session_index = session - utm->sessions;
+
+  rv = pthread_create (&utm->cut_through_thread_handle,
+                      NULL /*attr */ , cut_through_thread_fn, 0);
+  if (rv)
+    {
+      clib_warning ("pthread_create returned %d", rv);
+      rv = VNET_API_ERROR_SYSCALL_ERROR_1;
+    }
+
+send_reply:
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+
+  rmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI_REPLY);
+  rmp->context = mp->context;
+  rmp->retval = ntohl (rv);
+  rmp->segment_name_length = vec_len (a->segment_name);
+  memcpy (rmp->segment_name, a->segment_name, vec_len (a->segment_name));
+
+  vec_free (a->segment_name);
+
+  client_q = (unix_shared_memory_queue_t *) mp->client_queue_address;
+  vl_msg_api_send_shmem (client_q, (u8 *) & rmp);
+}
+
+static void
+vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+
+  if (mp->retval != 0)
+    clib_warning ("returned %d", ntohl (mp->retval));
+
+  utm->state = STATE_START;
+}
+
+static void
+vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  vl_api_accept_session_reply_t *rmp;
+  svm_fifo_t *rx_fifo, *tx_fifo;
+  session_t *session;
+  static f64 start_time;
+  u64 key;
+
+  if (start_time == 0.0)
+    start_time = clib_time_now (&utm->clib_time);
+
+  utm->vpp_event_queue = (unix_shared_memory_queue_t *)
+    mp->vpp_event_queue_address;
+
+  pool_get (utm->sessions, session);
+
+  rx_fifo = (svm_fifo_t *) mp->server_rx_fifo;
+  rx_fifo->client_session_index = session - utm->sessions;
+  tx_fifo = (svm_fifo_t *) mp->server_tx_fifo;
+  tx_fifo->client_session_index = session - utm->sessions;
+
+  session->server_rx_fifo = rx_fifo;
+  session->server_tx_fifo = tx_fifo;
+
+  key = (((u64) mp->session_thread_index) << 32) | (u64) mp->session_index;
+
+  hash_set (utm->session_index_by_vpp_handles, key, session - utm->sessions);
+
+  utm->state = STATE_READY;
+
+  if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0)
+    {
+      f64 now = clib_time_now (&utm->clib_time);
+      fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
+              pool_elts (utm->sessions), now - start_time,
+              (f64) pool_elts (utm->sessions) / (now - start_time));
+    }
+
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+  rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
+  rmp->session_type = mp->session_type;
+  rmp->session_index = mp->session_index;
+  rmp->session_thread_index = mp->session_thread_index;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
+}
+
+static void
+vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  session_t *session;
+  vl_api_disconnect_session_reply_t *rmp;
+  uword *p;
+  int rv = 0;
+  u64 key;
+
+  key = (((u64) mp->session_thread_index) << 32) | (u64) mp->session_index;
+
+  p = hash_get (utm->session_index_by_vpp_handles, key);
+
+  if (p)
+    {
+      session = pool_elt_at_index (utm->sessions, p[0]);
+      hash_unset (utm->session_index_by_vpp_handles, key);
+      pool_put (utm->sessions, session);
+    }
+  else
+    {
+      clib_warning ("couldn't find session key %llx", key);
+      rv = -11;
+    }
+
+  rmp = vl_msg_api_alloc (sizeof (*rmp));
+  memset (rmp, 0, sizeof (*rmp));
+  rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
+  rmp->retval = rv;
+  rmp->session_index = mp->session_index;
+  rmp->session_thread_index = mp->session_thread_index;
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
+}
+
+static void
+vl_api_connect_uri_reply_t_handler (vl_api_connect_uri_reply_t * mp)
+{
+  svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  ssvm_shared_header_t *sh;
+  svm_fifo_segment_private_t *seg;
+  svm_fifo_segment_header_t *fsh;
+  session_t *session;
+  u32 segment_index;
+  int rv;
+
+  ASSERT (utm->i_am_master == 0);
+
+  if (mp->segment_name_length == 0)
+    {
+      clib_warning ("segment_name_length zero");
+      return;
+    }
+
+  memset (a, 0, sizeof (*a));
+
+  a->segment_name = (char *) mp->segment_name;
+
+  sleep (1);
+
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning ("sm_fifo_segment_create ('%v') failed", mp->segment_name);
+      return;
+    }
+
+  segment_index = vec_len (sm->segments) - 1;
+
+  vec_add2 (utm->seg, seg, 1);
+
+  memcpy (seg, sm->segments + segment_index, sizeof (*seg));
+  sh = seg->ssvm.sh;
+  fsh = (svm_fifo_segment_header_t *) sh->opaque[0];
+
+  while (vec_len (fsh->fifos) < 2)
+    sleep (1);
+
+  pool_get (utm->sessions, session);
+  utm->cut_through_session_index = session - utm->sessions;
+
+  session->server_rx_fifo = (svm_fifo_t *) fsh->fifos[0];
+  ASSERT (session->server_rx_fifo);
+  session->server_tx_fifo = (svm_fifo_t *) fsh->fifos[1];
+  ASSERT (session->server_tx_fifo);
+
+  /* security: could unlink /dev/shm/<mp->segment_name> here, maybe */
+
+  utm->state = STATE_READY;
+}
+
+#define foreach_uri_msg                         \
+_(BIND_URI_REPLY, bind_uri_reply)               \
+_(CONNECT_URI, connect_uri)                     \
+_(CONNECT_URI_REPLY, connect_uri_reply)         \
+_(UNBIND_URI_REPLY, unbind_uri_reply)           \
+_(ACCEPT_SESSION, accept_session)              \
+_(DISCONNECT_SESSION, disconnect_session)      \
+_(MAP_ANOTHER_SEGMENT, map_another_segment)
+
+void
+uri_api_hookup (uri_udp_test_main_t * utm)
+{
+#define _(N,n)                                                  \
+    vl_msg_api_set_handlers(VL_API_##N, #n,                     \
+                           vl_api_##n##_t_handler,              \
+                           vl_noop_handler,                     \
+                           vl_api_##n##_t_endian,               \
+                           vl_api_##n##_t_print,                \
+                           sizeof(vl_api_##n##_t), 1);
+  foreach_uri_msg;
+#undef _
+
+}
+
+
+int
+connect_to_vpp (char *name)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  api_main_t *am = &api_main;
+
+  if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
+    return -1;
+
+  utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
+  utm->my_client_index = am->my_client_index;
+
+  return 0;
+}
+
+void
+vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
+{
+  clib_warning ("BUG");
+}
+
+static void
+init_error_string_table (uri_udp_test_main_t * utm)
+{
+  utm->error_string_by_error_number = hash_create (0, sizeof (uword));
+
+#define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
+  foreach_vnet_api_error;
+#undef _
+
+  hash_set (utm->error_string_by_error_number, 99, "Misc");
+}
+
+void
+handle_fifo_event_server_rx (uri_udp_test_main_t * utm,
+                            session_fifo_event_t * e)
+{
+  svm_fifo_t *rx_fifo, *tx_fifo;
+  int nbytes;
+
+  session_fifo_event_t evt;
+  unix_shared_memory_queue_t *q;
+  int rv;
+
+  rx_fifo = e->fifo;
+  tx_fifo = utm->sessions[rx_fifo->client_session_index].server_tx_fifo;
+
+  do
+    {
+      nbytes = svm_fifo_dequeue_nowait (rx_fifo, 0,
+                                       vec_len (utm->rx_buf), utm->rx_buf);
+    }
+  while (nbytes <= 0);
+  do
+    {
+      rv = svm_fifo_enqueue_nowait (tx_fifo, 0, nbytes, utm->rx_buf);
+    }
+  while (rv == -2);
+
+  /* Fabricate TX event, send to vpp */
+  evt.fifo = tx_fifo;
+  evt.event_type = FIFO_EVENT_SERVER_TX;
+  /* $$$$ for event logging */
+  evt.enqueue_length = nbytes;
+  evt.event_id = e->event_id;
+  q = utm->vpp_event_queue;
+  unix_shared_memory_queue_add (q, (u8 *) & evt, 0 /* do wait for mutex */ );
+}
+
+void
+handle_event_queue (uri_udp_test_main_t * utm)
+{
+  session_fifo_event_t _e, *e = &_e;;
+
+  while (1)
+    {
+      unix_shared_memory_queue_sub (utm->our_event_queue, (u8 *) e,
+                                   0 /* nowait */ );
+      switch (e->event_type)
+       {
+       case FIFO_EVENT_SERVER_RX:
+         handle_fifo_event_server_rx (utm, e);
+         break;
+
+       case FIFO_EVENT_SERVER_EXIT:
+         return;
+
+       default:
+         clib_warning ("unknown event type %d", e->event_type);
+         break;
+       }
+      if (PREDICT_FALSE (utm->time_to_stop == 1))
+       break;
+      if (PREDICT_FALSE (utm->time_to_print_stats == 1))
+       {
+         utm->time_to_print_stats = 0;
+         fformat (stdout, "%d connections\n", pool_elts (utm->sessions));
+       }
+    }
+}
+
+void
+uri_udp_test (uri_udp_test_main_t * utm)
+{
+  vl_api_bind_uri_t *bmp;
+  vl_api_unbind_uri_t *ump;
+
+  bmp = vl_msg_api_alloc (sizeof (*bmp));
+  memset (bmp, 0, sizeof (*bmp));
+
+  bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
+  bmp->client_index = utm->my_client_index;
+  bmp->context = ntohl (0xfeedface);
+  bmp->initial_segment_size = 256 << 20;       /* size of initial segment */
+  bmp->options[SESSION_OPTIONS_FLAGS] =
+    SESSION_OPTIONS_FLAGS_USE_FIFO | SESSION_OPTIONS_FLAGS_ADD_SEGMENT;
+  bmp->options[SESSION_OPTIONS_RX_FIFO_SIZE] = 16 << 10;
+  bmp->options[SESSION_OPTIONS_TX_FIFO_SIZE] = 16 << 10;
+  bmp->options[SESSION_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20;
+  memcpy (bmp->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
+
+  if (wait_for_state_change (utm, STATE_READY))
+    {
+      clib_warning ("timeout waiting for STATE_READY");
+      return;
+    }
+
+  handle_event_queue (utm);
+
+  ump = vl_msg_api_alloc (sizeof (*ump));
+  memset (ump, 0, sizeof (*ump));
+
+  ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
+  ump->client_index = utm->my_client_index;
+  memcpy (ump->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
+
+  if (wait_for_state_change (utm, STATE_START))
+    {
+      clib_warning ("timeout waiting for STATE_START");
+      return;
+    }
+
+  fformat (stdout, "Test complete...\n");
+}
+
+int
+main (int argc, char **argv)
+{
+  uri_udp_test_main_t *utm = &uri_udp_test_main;
+  unformat_input_t _argv, *a = &_argv;
+  u8 *chroot_prefix;
+  u8 *heap;
+  u8 *bind_name = (u8 *) "udp://0.0.0.0/1234";
+  u32 tmp;
+  mheap_t *h;
+  session_t *session;
+  int i;
+  int i_am_master = 1;
+
+  clib_mem_init (0, 256 << 20);
+
+  heap = clib_mem_get_per_cpu_heap ();
+  h = mheap_header (heap);
+
+  /* make the main heap thread-safe */
+  h->flags |= MHEAP_FLAG_THREAD_SAFE;
+
+  vec_validate (utm->rx_buf, 8192);
+
+  utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
+
+  utm->my_pid = getpid ();
+  utm->configured_segment_size = 1 << 20;
+
+  clib_time_init (&utm->clib_time);
+  init_error_string_table (utm);
+  svm_fifo_segment_init (0x200000000ULL, 20);
+  unformat_init_command_line (a, argv);
+
+  while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (a, "chroot prefix %s", &chroot_prefix))
+       {
+         vl_set_memory_root_path ((char *) chroot_prefix);
+       }
+      else if (unformat (a, "uri %s", &bind_name))
+       ;
+      else if (unformat (a, "segment-size %dM", &tmp))
+       utm->configured_segment_size = tmp << 20;
+      else if (unformat (a, "segment-size %dG", &tmp))
+       utm->configured_segment_size = tmp << 30;
+      else if (unformat (a, "master"))
+       i_am_master = 1;
+      else if (unformat (a, "slave"))
+       i_am_master = 0;
+      else
+       {
+         fformat (stderr, "%s: usage [master|slave]\n");
+         exit (1);
+       }
+    }
+
+  utm->cut_through_session_index = ~0;
+  utm->uri = format (0, "%s%c", bind_name, 0);
+  utm->i_am_master = i_am_master;
+  utm->segment_main = &svm_fifo_segment_main;
+
+  utm->connect_uri = format (0, "udp://10.0.0.1/1234%c", 0);
+
+  setup_signal_handlers ();
+
+  uri_api_hookup (utm);
+
+  if (connect_to_vpp (i_am_master ? "uri_udp_master" : "uri_udp_slave") < 0)
+    {
+      svm_region_exit ();
+      fformat (stderr, "Couldn't connect to vpe, exiting...\n");
+      exit (1);
+    }
+
+  if (i_am_master == 0)
+    {
+      uri_udp_slave_test (utm);
+      exit (0);
+    }
+
+  /* $$$$ hack preallocation */
+  for (i = 0; i < 200000; i++)
+    {
+      pool_get (utm->sessions, session);
+      memset (session, 0, sizeof (*session));
+    }
+  for (i = 0; i < 200000; i++)
+    pool_put_index (utm->sessions, i);
+
+  uri_udp_test (utm);
+
+  vl_client_disconnect_from_vlib ();
+  exit (0);
+}
+
+#undef vl_api_version
+#define vl_api_version(n,v) static u32 vpe_api_version = v;
+#include <vpp/api/vpe.api.h>
+#undef vl_api_version
+
+void
+vl_client_add_api_signatures (vl_api_memclnt_create_t * mp)
+{
+  /*
+   * Send the main API signature in slot 0. This bit of code must
+   * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
+   */
+  mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
+}
+
+u32
+vl (void *p)
+{
+  return vec_len (p);
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/uri/uritest.c b/src/uri/uritest.c
new file mode 100644 (file)
index 0000000..edcdb3a
--- /dev/null
@@ -0,0 +1,484 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <setjmp.h>
+#include <vppinfra/clib.h>
+#include <vppinfra/format.h>
+#include <vppinfra/error.h>
+#include <vppinfra/time.h>
+#include <vppinfra/macros.h>
+#include <vnet/vnet.h>
+#include <vlib/vlib.h>
+#include <vlib/unix/unix.h>
+#include <vlibapi/api.h>
+#include <vlibmemory/api.h>
+#include <vpp-api/vpe_msg_enum.h>
+#include <svm_fifo_segment.h>
+
+#define vl_typedefs            /* define message structures */
+#include <vpp-api/vpe_all_api_h.h>
+#undef vl_typedefs
+
+/* declare message handlers for each api */
+
+#define vl_endianfun           /* define message structures */
+#include <vpp-api/vpe_all_api_h.h>
+#undef vl_endianfun
+
+/* instantiate all the print functions we know about */
+#define vl_print(handle, ...)
+#define vl_printfun
+#include <vpp-api/vpe_all_api_h.h>
+#undef vl_printfun
+
+typedef enum
+{
+  STATE_START,
+  STATE_READY,
+  STATE_DISCONNECTING,
+} connection_state_t;
+
+typedef struct
+{
+  /* vpe input queue */
+  unix_shared_memory_queue_t *vl_input_queue;
+
+  /* API client handle */
+  u32 my_client_index;
+
+  /* role */
+  int i_am_master;
+
+  /* The URI we're playing with */
+  u8 *uri;
+
+  /* fifo segment */
+  svm_fifo_segment_private_t *seg;
+
+  svm_fifo_t *rx_fifo;
+  svm_fifo_t *tx_fifo;
+
+  /* For deadman timers */
+  clib_time_t clib_time;
+
+  /* State of the connection, shared between msg RX thread and main thread */
+  volatile connection_state_t state;
+
+  /* VNET_API_ERROR_FOO -> "Foo" hash table */
+  uword *error_string_by_error_number;
+} uritest_main_t;
+
+#if CLIB_DEBUG > 0
+#define NITER 1000
+#else
+#define NITER 1000000
+#endif
+
+uritest_main_t uritest_main;
+
+u8 *
+format_api_error (u8 * s, va_list * args)
+{
+  uritest_main_t *utm = va_arg (*args, uritest_main_t *);
+  i32 error = va_arg (*args, u32);
+  uword *p;
+
+  p = hash_get (utm->error_string_by_error_number, -error);
+
+  if (p)
+    s = format (s, "%s", p[0]);
+  else
+    s = format (s, "%d", error);
+  return s;
+}
+
+int
+wait_for_state_change (uritest_main_t * utm, connection_state_t state)
+{
+  f64 timeout = clib_time_now (&utm->clib_time) + 1.0;
+
+  while (clib_time_now (&utm->clib_time) < timeout)
+    {
+      if (utm->state == state)
+       return 0;
+    }
+  return -1;
+}
+
+static void
+vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
+{
+  uritest_main_t *utm = &uritest_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  int rv;
+
+  ASSERT (utm->i_am_master);
+
+  if (mp->segment_name_length == 0)
+    {
+      clib_warning ("segment_name_length zero");
+      return;
+    }
+
+  a->segment_name = (char *) mp->segment_name;
+  a->segment_size = mp->segment_size;
+
+  /* Create the segment */
+  rv = svm_fifo_segment_create (a);
+  if (rv)
+    {
+      clib_warning ("sm_fifo_segment_create ('%s') failed", mp->segment_name);
+      return;
+    }
+
+  vec_validate (utm->seg, 0);
+
+  memcpy (utm->seg, a->rv, sizeof (*utm->seg));
+
+  /*
+   * By construction the master's idea of the rx fifo ends up in
+   * fsh->fifos[0], and the master's idea of the tx fifo ends up in
+   * fsh->fifos[1].
+   */
+  utm->rx_fifo = svm_fifo_segment_alloc_fifo (utm->seg, 10240);
+  ASSERT (utm->rx_fifo);
+
+  utm->tx_fifo = svm_fifo_segment_alloc_fifo (utm->seg, 10240);
+  ASSERT (utm->tx_fifo);
+
+  utm->state = STATE_READY;
+}
+
+static void
+vl_api_connect_uri_reply_t_handler (vl_api_connect_uri_reply_t * mp)
+{
+  uritest_main_t *utm = &uritest_main;
+  svm_fifo_segment_create_args_t _a, *a = &_a;
+  ssvm_shared_header_t *sh;
+  svm_fifo_segment_header_t *fsh;
+  int rv;
+
+  ASSERT (utm->i_am_master == 0);
+
+  if (mp->segment_name_length == 0)
+    {
+      clib_warning ("segment_name_length zero");
+      return;
+    }
+
+  memset (a, 0, sizeof (*a));
+
+  a->segment_name = (char *) mp->segment_name;
+
+  rv = svm_fifo_segment_attach (a);
+  if (rv)
+    {
+      clib_warning ("sm_fifo_segment_create ('%s') failed", mp->segment_name);
+      return;
+    }
+
+  vec_validate (utm->seg, 0);
+
+  memcpy (utm->seg, a->rv, sizeof (*utm->seg));
+  sh = utm->seg->ssvm.sh;
+  fsh = (svm_fifo_segment_header_t *) sh->opaque[0];
+
+  while (vec_len (fsh->fifos) < 2)
+    sleep (1);
+
+  utm->rx_fifo = (svm_fifo_t *) fsh->fifos[1];
+  ASSERT (utm->rx_fifo);
+  utm->tx_fifo = (svm_fifo_t *) fsh->fifos[0];
+  ASSERT (utm->tx_fifo);
+
+  /* security: could unlink /dev/shm/<mp->segment_name> here, maybe */
+
+  utm->state = STATE_READY;
+}
+
+static void
+vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
+{
+  uritest_main_t *utm = &uritest_main;
+
+  if (mp->retval != 0)
+    clib_warning ("returned %d", ntohl (mp->retval));
+
+  utm->state = STATE_START;
+}
+
+#define foreach_uri_msg                         \
+_(BIND_URI_REPLY, bind_uri_reply)               \
+_(CONNECT_URI_REPLY, connect_uri_reply)         \
+_(UNBIND_URI_REPLY, unbind_uri_reply)
+
+void
+uri_api_hookup (uritest_main_t * utm)
+{
+#define _(N,n)                                                  \
+    vl_msg_api_set_handlers(VL_API_##N, #n,                     \
+                           vl_api_##n##_t_handler,             \
+                           vl_noop_handler,                     \
+                           vl_api_##n##_t_endian,               \
+                           vl_api_##n##_t_print,                \
+                           sizeof(vl_api_##n##_t), 1);
+  foreach_uri_msg;
+#undef _
+
+}
+
+
+int
+connect_to_vpp (char *name)
+{
+  uritest_main_t *utm = &uritest_main;
+  api_main_t *am = &api_main;
+
+  if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
+    return -1;
+
+  utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
+  utm->my_client_index = am->my_client_index;
+
+  return 0;
+}
+
+void
+vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
+{
+  clib_warning ("BUG");
+}
+
+static void
+init_error_string_table (uritest_main_t * utm)
+{
+  utm->error_string_by_error_number = hash_create (0, sizeof (uword));
+
+#define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
+  foreach_vnet_api_error;
+#undef _
+
+  hash_set (utm->error_string_by_error_number, 99, "Misc");
+}
+
+void
+uritest_master (uritest_main_t * utm)
+{
+  vl_api_bind_uri_t *bmp;
+  vl_api_unbind_uri_t *ump;
+  int i;
+  u8 *test_data = 0;
+  u8 *reply = 0;
+  u32 reply_len;
+  int mypid = getpid ();
+
+  for (i = 0; i < 2048; i++)
+    vec_add1 (test_data, 'a' + (i % 32));
+
+  bmp = vl_msg_api_alloc (sizeof (*bmp));
+  memset (bmp, 0, sizeof (*bmp));
+
+  bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
+  bmp->client_index = utm->my_client_index;
+  bmp->context = ntohl (0xfeedface);
+  bmp->segment_size = 256 << 10;
+  memcpy (bmp->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
+
+  if (wait_for_state_change (utm, STATE_READY))
+    {
+      clib_warning ("timeout waiting for STATE_READY");
+      return;
+    }
+
+  for (i = 0; i < NITER; i++)
+    svm_fifo_enqueue (utm->tx_fifo, mypid, vec_len (test_data), test_data);
+
+  vec_validate (reply, 0);
+
+  reply_len = svm_fifo_dequeue (utm->rx_fifo, mypid, vec_len (reply), reply);
+
+  if (reply_len != 1)
+    clib_warning ("reply length %d", reply_len);
+
+  if (reply[0] == 1)
+    fformat (stdout, "Test OK...");
+
+  ump = vl_msg_api_alloc (sizeof (*ump));
+  memset (ump, 0, sizeof (*ump));
+
+  ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
+  ump->client_index = utm->my_client_index;
+  memcpy (ump->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
+
+  if (wait_for_state_change (utm, STATE_START))
+    {
+      clib_warning ("timeout waiting for STATE_READY");
+      return;
+    }
+
+  fformat (stdout, "Master done...\n");
+}
+
+void
+uritest_slave (uritest_main_t * utm)
+{
+  vl_api_connect_uri_t *cmp;
+  int i, j;
+  u8 *test_data = 0;
+  u8 *reply = 0;
+  u32 bytes_received = 0;
+  u32 actual_bytes;
+  int mypid = getpid ();
+  u8 ok;
+  f64 before, after, delta, bytes_per_second;
+
+  vec_validate (test_data, 4095);
+
+  cmp = vl_msg_api_alloc (sizeof (*cmp));
+  memset (cmp, 0, sizeof (*cmp));
+
+  cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
+  cmp->client_index = utm->my_client_index;
+  cmp->context = ntohl (0xfeedface);
+  memcpy (cmp->uri, utm->uri, vec_len (utm->uri));
+  vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp);
+
+  if (wait_for_state_change (utm, STATE_READY))
+    {
+      clib_warning ("timeout waiting for STATE_READY");
+      return;
+    }
+
+  ok = 1;
+  before = clib_time_now (&utm->clib_time);
+  for (i = 0; i < NITER; i++)
+    {
+      actual_bytes = svm_fifo_dequeue (utm->rx_fifo, mypid,
+                                      vec_len (test_data), test_data);
+      j = 0;
+      while (j < actual_bytes)
+       {
+         if (test_data[j] != ('a' + (bytes_received % 32)))
+           ok = 0;
+         bytes_received++;
+         j++;
+       }
+      if (bytes_received == NITER * 2048)
+       break;
+    }
+
+  vec_add1 (reply, ok);
+
+  svm_fifo_enqueue (utm->tx_fifo, mypid, vec_len (reply), reply);
+  after = clib_time_now (&utm->clib_time);
+  delta = after - before;
+  bytes_per_second = 0.0;
+
+  if (delta > 0.0)
+    bytes_per_second = (f64) bytes_received / delta;
+
+  fformat (stdout,
+          "Slave done, %d bytes in %.2f seconds, %.2f bytes/sec...\n",
+          bytes_received, delta, bytes_per_second);
+}
+
+int
+main (int argc, char **argv)
+{
+  uritest_main_t *utm = &uritest_main;
+  unformat_input_t _argv, *a = &_argv;
+  u8 *chroot_prefix;
+  u8 *heap;
+  char *bind_name = "fifo:uritest";
+  mheap_t *h;
+  int i_am_master = 0;
+
+  clib_mem_init (0, 128 << 20);
+
+  heap = clib_mem_get_per_cpu_heap ();
+  h = mheap_header (heap);
+
+  /* make the main heap thread-safe */
+  h->flags |= MHEAP_FLAG_THREAD_SAFE;
+
+  clib_time_init (&utm->clib_time);
+  init_error_string_table (utm);
+  svm_fifo_segment_init (0x200000000ULL, 20);
+  unformat_init_command_line (a, argv);
+
+  utm->uri = format (0, "%s%c", bind_name, 0);
+
+  while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (a, "master"))
+       i_am_master = 1;
+      else if (unformat (a, "slave"))
+       i_am_master = 0;
+      else if (unformat (a, "chroot prefix %s", &chroot_prefix))
+       {
+         vl_set_memory_root_path ((char *) chroot_prefix);
+       }
+      else
+       {
+         fformat (stderr, "%s: usage [master|slave]\n");
+         exit (1);
+       }
+    }
+
+  uri_api_hookup (utm);
+
+  if (connect_to_vpp (i_am_master ? "uritest_master" : "uritest_slave") < 0)
+    {
+      svm_region_exit ();
+      fformat (stderr, "Couldn't connect to vpe, exiting...\n");
+      exit (1);
+    }
+
+  utm->i_am_master = i_am_master;
+
+  if (i_am_master)
+    uritest_master (utm);
+  else
+    uritest_slave (utm);
+
+  vl_client_disconnect_from_vlib ();
+  exit (0);
+}
+
+#undef vl_api_version
+#define vl_api_version(n,v) static u32 vpe_api_version = v;
+#include <vpp-api/vpe.api.h>
+#undef vl_api_version
+
+void
+vl_client_add_api_signatures (vl_api_memclnt_create_t * mp)
+{
+  /*
+   * Send the main API signature in slot 0. This bit of code must
+   * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
+   */
+  mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
index 4f5eb09..9f26bec 100644 (file)
@@ -360,7 +360,7 @@ vlib_buffer_create_free_list_helper (vlib_main_t * vm,
   memset (f, 0, sizeof (f[0]));
   f->index = f - bm->buffer_free_list_pool;
   f->n_data_bytes = vlib_buffer_round_size (n_data_bytes);
-  f->min_n_buffers_each_physmem_alloc = 16;
+  f->min_n_buffers_each_physmem_alloc = VLIB_FRAME_SIZE;
   f->name = clib_mem_is_heap_object (name) ? name : format (0, "%s", name);
 
   /* Setup free buffer template. */
index 1f723f3..69c8c7c 100644 (file)
@@ -240,6 +240,74 @@ vlib_get_buffer_opaque2 (vlib_buffer_t * b)
   return (void *) b->opaque2;
 }
 
+/** \brief Get pointer to the end of buffer's data
+ * @param b     pointer to the buffer
+ * @return      pointer to tail of packet's data
+ */
+always_inline u8 *
+vlib_buffer_get_tail (vlib_buffer_t * b)
+{
+  return b->data + b->current_data + b->current_length;
+}
+
+/** \brief Append uninitialized data to buffer
+ * @param b     pointer to the buffer
+ * @param size  number of uninitialized bytes
+ * @return      pointer to beginning of uninitialized data
+ */
+always_inline void *
+vlib_buffer_put_uninit (vlib_buffer_t * b, u8 size)
+{
+  void *p = vlib_buffer_get_tail (b);
+  /* XXX make sure there's enough space */
+  b->current_length += size;
+  return p;
+}
+
+/** \brief Prepend uninitialized data to buffer
+ * @param b     pointer to the buffer
+ * @param size  number of uninitialized bytes
+ * @return      pointer to beginning of uninitialized data
+ */
+always_inline void *
+vlib_buffer_push_uninit (vlib_buffer_t * b, u8 size)
+{
+  ASSERT (b->current_data + VLIB_BUFFER_PRE_DATA_SIZE >= size);
+  b->current_data -= size;
+  b->current_length += size;
+
+  return vlib_buffer_get_current (b);
+}
+
+/** \brief Make head room, typically for packet headers
+ * @param b     pointer to the buffer
+ * @param size  number of head room bytes
+ * @return      pointer to start of buffer (current data)
+ */
+always_inline void *
+vlib_buffer_make_headroom (vlib_buffer_t * b, u8 size)
+{
+  ASSERT (b->current_data + VLIB_BUFFER_PRE_DATA_SIZE >= size);
+  b->current_data += size;
+  return vlib_buffer_get_current (b);
+}
+
+/** \brief Retrieve bytes from buffer head
+ * @param b     pointer to the buffer
+ * @param size  number of bytes to pull
+ * @return      pointer to start of buffer (current data)
+ */
+always_inline void *
+vlib_buffer_pull (vlib_buffer_t * b, u8 size)
+{
+  if (b->current_length + VLIB_BUFFER_PRE_DATA_SIZE < size)
+    return 0;
+
+  void *data = vlib_buffer_get_current (b);
+  vlib_buffer_advance (b, size);
+  return data;
+}
+
 /* Forward declaration. */
 struct vlib_main_t;
 
index 25d2891..e86edec 100644 (file)
  * nels = number of elements on the queue
  * elsize = element size, presumably 4 and cacheline-size will
  *          be popular choices.
- * coid  = consumer coid, from ChannelCreate
  * pid   = consumer pid
- * pulse_code  = pulse code consumer expects
- * pulse_value = pulse value consumer expects
- * consumer_prio = consumer's priority, so pulses won't change
- *                 the consumer's priority.
  *
  * The idea is to call this function in the queue consumer,
  * and e-mail the queue pointer to the producer(s).
  *
- * The spp process / main thread allocates one of these
- * at startup; its main input queue. The spp main input queue
+ * The vpp process / main thread allocates one of these
+ * at startup; its main input queue. The vpp main input queue
  * has a pointer to it in the shared memory segment header.
  *
  * You probably want to be on an svm data heap before calling this
@@ -70,7 +65,7 @@ unix_shared_memory_queue_init (int nels,
   q->signal_when_queue_non_empty = signal_when_queue_non_empty;
 
   memset (&attr, 0, sizeof (attr));
-  memset (&cattr, 0, sizeof (attr));
+  memset (&cattr, 0, sizeof (cattr));
 
   if (pthread_mutexattr_init (&attr))
     clib_unix_warning ("mutexattr_init");
@@ -277,6 +272,7 @@ unix_shared_memory_queue_sub (unix_shared_memory_queue_t * q,
   clib_memcpy (elem, headp, q->elsize);
 
   q->head++;
+  /* $$$$ JFC shouldn't this be == 0? */
   if (q->cursize == q->maxsize)
     need_broadcast = 1;
 
index f758f17..1380006 100644 (file)
@@ -29,7 +29,7 @@ typedef struct _unix_shared_memory_queue
   pthread_cond_t condvar;      /* 8 bytes */
   int head;
   int tail;
-  int cursize;
+  volatile int cursize;
   int maxsize;
   int elsize;
   int consumer_pid;
index 64484e1..923f61d 100644 (file)
@@ -324,11 +324,7 @@ libvnet_la_SOURCES +=                              \
  vnet/ip/ip_input_acl.c                                \
  vnet/ip/lookup.c                              \
  vnet/ip/ping.c                                        \
- vnet/ip/punt.c                                        \
- vnet/ip/udp_format.c                          \
- vnet/ip/udp_init.c                            \
- vnet/ip/udp_local.c                           \
- vnet/ip/udp_pg.c
+ vnet/ip/punt.c
 
 nobase_include_HEADERS +=                      \
  vnet/ip/format.h                              \
@@ -354,11 +350,7 @@ nobase_include_HEADERS +=                  \
  vnet/ip/ports.def                             \
  vnet/ip/protocols.def                         \
  vnet/ip/punt_error.def                                \
- vnet/ip/punt.h                                        \
- vnet/ip/tcp_packet.h                          \
- vnet/ip/udp_error.def                         \
- vnet/ip/udp.h                                 \
- vnet/ip/udp_packet.h
+ vnet/ip/punt.h
 
 API_FILES += vnet/ip/ip.api
 
@@ -473,6 +465,38 @@ test_map_LDADD = libvnet.la libvppinfra.la libvlib.la      \
 test_map_LDFLAGS = -static
 endif
 
+########################################
+# Layer 4 protocol: tcp
+########################################
+libvnet_la_SOURCES +=                          \
+ vnet/tcp/tcp_format.c                         \
+ vnet/tcp/tcp_pg.c                             \
+ vnet/tcp/tcp_syn_filter4.c                    \
+ vnet/tcp/tcp_output.c                         \
+ vnet/tcp/tcp_input.c                          \
+ vnet/tcp/tcp_newreno.c                                \
+ vnet/tcp/tcp.c
+
+nobase_include_HEADERS +=                      \
+ vnet/tcp/tcp_packet.h                         \
+ vnet/tcp/tcp_timer.h                          \
+ vnet/tcp/tcp.h
+
+########################################
+# Layer 4 protocol: udp
+########################################
+libvnet_la_SOURCES +=                          \
+ vnet/udp/udp.c                                        \
+ vnet/udp/udp_input.c                          \
+ vnet/udp/builtin_server.c                     \
+ vnet/udp/udp_format.c                         \
+ vnet/udp/udp_local.c                          \
+ vnet/udp/udp_pg.c
+
+nobase_include_HEADERS +=                      \
+  vnet/udp/udp_error.def                               \
+  vnet/udp/udp.h                                       \
+  vnet/udp/udp_packet.h
 
 ########################################
 # Tunnel protocol: gre
@@ -833,6 +857,28 @@ libvnet_la_SOURCES +=                              \
 nobase_include_HEADERS +=                      \
   vnet/devices/ssvm/ssvm_eth.h
 
+########################################
+# session managmeent
+########################################
+
+libvnet_la_SOURCES +=                          \
+  vnet/session/session.c                       \
+  vnet/session/node.c                          \
+  vnet/session/transport.c                     \
+  vnet/session/application.c                   \
+  vnet/session/session_cli.c                   \
+  vnet/session/hashes.c                                \
+  vnet/session/application_interface.c         \
+  vnet/session/session_api.c
+
+nobase_include_HEADERS +=                      \
+  vnet/session/session.h                       \
+  vnet/session/application.h                   \
+  vnet/session/transport.h                     \
+  vnet/session/application_interface.h
+
+API_FILES += vnet/session/session.api
+
 ########################################
 # Linux packet interface
 ########################################
index 8680ef7..861a576 100644 (file)
@@ -91,14 +91,19 @@ _(INVALID_ADDRESS_FAMILY, -97, "Invalid address family")                \
 _(INVALID_SUB_SW_IF_INDEX, -98, "Invalid sub-interface sw_if_index")    \
 _(TABLE_TOO_BIG, -99, "Table too big")                                  \
 _(CANNOT_ENABLE_DISABLE_FEATURE, -100, "Cannot enable/disable feature") \
-_(BFD_EEXIST, -101, "Duplicate BFD object") \
-_(BFD_ENOENT, -102, "No such BFD object") \
-_(BFD_EINUSE, -103, "BFD object in use") \
-_(BFD_NOTSUPP, -104, "BFD feature not supported") \
-_(LISP_RLOC_LOCAL, -105, "RLOC address is local") \
-_(BFD_EAGAIN, -106, "BFD object cannot be manipulated at this time")    \
-_(INVALID_GPE_MODE, -107, "Invalid GPE mode")                           \
-_(LISP_GPE_ENTRIES_PRESENT, -108, "LISP GPE entries are present")
+_(BFD_EEXIST, -101, "Duplicate BFD object")                             \
+_(BFD_ENOENT, -102, "No such BFD object")                               \
+_(BFD_EINUSE, -103, "BFD object in use")                                \
+_(BFD_NOTSUPP, -104, "BFD feature not supported")                       \
+_(ADDRESS_IN_USE, -105, "Address in use")                              \
+_(ADDRESS_NOT_IN_USE, -106, "Address not in use")                      \
+_(QUEUE_FULL, -107, "Queue full")                                       \
+_(UNKNOWN_URI_TYPE, -108, "Unknown URI type")                          \
+_(URI_FIFO_CREATE_FAILED, -109, "URI FIFO segment create failed")       \
+_(LISP_RLOC_LOCAL, -110, "RLOC address is local")                       \
+_(BFD_EAGAIN, -111, "BFD object cannot be manipulated at this time")   \
+_(INVALID_GPE_MODE, -112, "Invalid GPE mode")                           \
+_(LISP_GPE_ENTRIES_PRESENT, -113, "LISP GPE entries are present")
 
 typedef enum
 {
index 146faad..cf05089 100644 (file)
 #include <vlib/buffer.h>
 #include <vnet/ip/format.h>
 #include <vnet/ethernet/packet.h>
-#include <vnet/ip/udp_packet.h>
+#include <vnet/udp/udp_packet.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ip/lookup.h>
 #include <vnet/ip/icmp46_packet.h>
 #include <vnet/ip/ip4.h>
 #include <vnet/ip/ip6.h>
-#include <vnet/ip/udp.h>
 #include <vnet/ip/ip6_packet.h>
 #include <vnet/adj/adj.h>
 #include <vnet/adj/adj_nbr.h>
index f1cc637..3de01f2 100644 (file)
@@ -277,6 +277,16 @@ typedef struct
       u16 buffer_advance;
     } device_input_feat;
 
+    /* TCP */
+    struct
+    {
+      u32 connection_index;
+      u32 seq_number;
+      u32 seq_end;
+      u32 ack_number;
+      u8 flags;
+    } tcp;
+
     u32 unused[6];
   };
 } vnet_buffer_opaque_t;
index 6093e2a..b651a1f 100644 (file)
@@ -695,8 +695,8 @@ int vnet_classify_add_del_table (vnet_classify_main_t * cm,
 }
 
 #define foreach_tcp_proto_field                 \
-_(src_port)                                     \
-_(dst_port)
+_(src)                                          \
+_(dst)
 
 #define foreach_udp_proto_field                 \
 _(src_port)                                     \
index c0d79c4..4586d88 100644 (file)
@@ -26,7 +26,7 @@
 #include <vnet/ip/ip4_packet.h>
 #include <vnet/pg/pg.h>
 #include <vnet/ip/format.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 
 typedef enum {
 #define dhcp_proxy_error(n,s) DHCP_PROXY_ERROR_##n,
index 4e76437..e8ed381 100644 (file)
@@ -23,7 +23,7 @@
 #include <vnet/ip/ip_packet.h>
 #include <vnet/ip/ip4_packet.h>
 #include <vnet/ip/ip6_packet.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vlib/cli.h>
 #include <vppinfra/error.h>
 #include <vppinfra/hash.h>
index 02a1a96..70b4ccd 100644 (file)
@@ -50,8 +50,8 @@
 #include <vnet/ip/ip_packet.h>
 #include <vnet/ip/lookup.h>
 
-#include <vnet/ip/tcp_packet.h>
-#include <vnet/ip/udp_packet.h>
+#include <vnet/tcp/tcp_packet.h>
+#include <vnet/udp/udp_packet.h>
 #include <vnet/ip/icmp46_packet.h>
 
 #include <vnet/ip/ip4.h>
index b184fba..4e075d0 100644 (file)
@@ -309,8 +309,8 @@ ip4_compute_flow_hash (const ip4_header_t * ip,
   b = (flow_hash_config & IP_FLOW_HASH_REVERSE_SRC_DST) ? t1 : t2;
   b ^= (flow_hash_config & IP_FLOW_HASH_PROTO) ? ip->protocol : 0;
 
-  t1 = is_tcp_udp ? tcp->ports.src : 0;
-  t2 = is_tcp_udp ? tcp->ports.dst : 0;
+  t1 = is_tcp_udp ? tcp->src : 0;
+  t2 = is_tcp_udp ? tcp->dst : 0;
 
   t1 = (flow_hash_config & IP_FLOW_HASH_SRC_PORT) ? t1 : 0;
   t2 = (flow_hash_config & IP_FLOW_HASH_DST_PORT) ? t2 : 0;
@@ -334,6 +334,44 @@ u8 *format_ip4_forward_next_trace (u8 * s, va_list * args);
 
 u32 ip4_tcp_udp_validate_checksum (vlib_main_t * vm, vlib_buffer_t * p0);
 
+#define IP_DF 0x4000           /* don't fragment */
+
+/**
+ * Push IPv4 header to buffer
+ *
+ * This does not support fragmentation.
+ *
+ * @param vm - vlib_main
+ * @param b - buffer to write the header to
+ * @param src - source IP
+ * @param dst - destination IP
+ * @param prot - payload proto
+ *
+ * @return - pointer to start of IP header
+ */
+always_inline void *
+vlib_buffer_push_ip4 (vlib_main_t * vm, vlib_buffer_t * b,
+                     ip4_address_t * src, ip4_address_t * dst, int proto)
+{
+  ip4_header_t *ih;
+
+  /* make some room */
+  ih = vlib_buffer_push_uninit (b, sizeof (ip4_header_t));
+
+  ih->ip_version_and_header_length = 0x45;
+  ih->tos = 0;
+  ih->length = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, b));
+
+  /* No fragments */
+  ih->flags_and_fragment_offset = clib_host_to_net_u16 (IP_DF);
+  ih->ttl = 255;
+  ih->protocol = proto;
+  ih->src_address.as_u32 = src->as_u32;
+  ih->dst_address.as_u32 = dst->as_u32;
+
+  ih->checksum = ip4_header_checksum (ih);
+  return ih;
+}
 #endif /* included_ip_ip4_h */
 
 /*
index 8081b34..66d91ab 100644 (file)
@@ -1478,8 +1478,18 @@ ip4_tcp_udp_validate_checksum (vlib_main_t * vm, vlib_buffer_t * p0)
   return p0->flags;
 }
 
-static uword
-ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
+/* *INDENT-OFF* */
+VNET_FEATURE_ARC_INIT (ip4_local) =
+{
+  .arc_name  = "ip4-local",
+  .start_nodes = VNET_FEATURES ("ip4-local"),
+};
+/* *INDENT-ON* */
+
+static inline uword
+ip4_local_inline (vlib_main_t * vm,
+                 vlib_node_runtime_t * node,
+                 vlib_frame_t * frame, int head_of_feature_arc)
 {
   ip4_main_t *im = &ip4_main;
   ip_lookup_main_t *lm = &im->lookup_main;
@@ -1487,6 +1497,7 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
   u32 *from, *to_next, n_left_from, n_left_to_next;
   vlib_node_runtime_t *error_node =
     vlib_node_get_runtime (vm, ip4_input_node.index);
+  u8 arc_index = vnet_feat_arc_ip4_local.feature_arc_index;
 
   from = vlib_frame_vector_args (frame);
   n_left_from = frame->n_vectors;
@@ -1513,7 +1524,7 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          i32 len_diff0, len_diff1;
          u8 error0, is_udp0, is_tcp_udp0, good_tcp_udp0, proto0;
          u8 error1, is_udp1, is_tcp_udp1, good_tcp_udp1, proto1;
-         u8 enqueue_code;
+         u32 sw_if_index0, sw_if_index1;
 
          pi0 = to_next[0] = from[0];
          pi1 = to_next[1] = from[1];
@@ -1522,6 +1533,8 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          to_next += 2;
          n_left_to_next -= 2;
 
+         next0 = next1 = IP_LOCAL_NEXT_DROP;
+
          p0 = vlib_get_buffer (vm, pi0);
          p1 = vlib_get_buffer (vm, pi1);
 
@@ -1531,14 +1544,18 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          vnet_buffer (p0)->ip.start_of_ip_header = p0->current_data;
          vnet_buffer (p1)->ip.start_of_ip_header = p1->current_data;
 
-         fib_index0 = vec_elt (im->fib_index_by_sw_if_index,
-                               vnet_buffer (p0)->sw_if_index[VLIB_RX]);
+         sw_if_index0 = vnet_buffer (p0)->sw_if_index[VLIB_RX];
+         sw_if_index1 = vnet_buffer (p1)->sw_if_index[VLIB_RX];
+
+         fib_index0 = vec_elt (im->fib_index_by_sw_if_index, sw_if_index0);
+         fib_index1 = vec_elt (im->fib_index_by_sw_if_index, sw_if_index1);
+
+         fib_index0 = vec_elt (im->fib_index_by_sw_if_index, sw_if_index0);
          fib_index0 =
            (vnet_buffer (p0)->sw_if_index[VLIB_TX] ==
             (u32) ~ 0) ? fib_index0 : vnet_buffer (p0)->sw_if_index[VLIB_TX];
 
-         fib_index1 = vec_elt (im->fib_index_by_sw_if_index,
-                               vnet_buffer (p1)->sw_if_index[VLIB_RX]);
+         fib_index1 = vec_elt (im->fib_index_by_sw_if_index, sw_if_index1);
          fib_index1 =
            (vnet_buffer (p1)->sw_if_index[VLIB_TX] ==
             (u32) ~ 0) ? fib_index1 : vnet_buffer (p1)->sw_if_index[VLIB_TX];
@@ -1557,6 +1574,13 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
             until support of IP frag reassembly is implemented */
          proto0 = ip4_is_fragment (ip0) ? 0xfe : ip0->protocol;
          proto1 = ip4_is_fragment (ip1) ? 0xfe : ip1->protocol;
+
+         if (head_of_feature_arc == 0)
+           {
+             error0 = error1 = IP4_ERROR_UNKNOWN_PROTOCOL;
+             goto skip_checks;
+           }
+
          is_udp0 = proto0 == IP_PROTOCOL_UDP;
          is_udp1 = proto1 == IP_PROTOCOL_UDP;
          is_tcp_udp0 = is_udp0 || proto0 == IP_PROTOCOL_TCP;
@@ -1686,6 +1710,7 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          next0 = lm->local_next_by_ip_protocol[proto0];
          next1 = lm->local_next_by_ip_protocol[proto1];
 
+       skip_checks:
          next0 =
            error0 != IP4_ERROR_UNKNOWN_PROTOCOL ? IP_LOCAL_NEXT_DROP : next0;
          next1 =
@@ -1694,44 +1719,17 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          p0->error = error0 ? error_node->errors[error0] : 0;
          p1->error = error1 ? error_node->errors[error1] : 0;
 
-         enqueue_code = (next0 != next_index) + 2 * (next1 != next_index);
-
-         if (PREDICT_FALSE (enqueue_code != 0))
+         if (head_of_feature_arc)
            {
-             switch (enqueue_code)
-               {
-               case 1:
-                 /* A B A */
-                 to_next[-2] = pi1;
-                 to_next -= 1;
-                 n_left_to_next += 1;
-                 vlib_set_next_frame_buffer (vm, node, next0, pi0);
-                 break;
-
-               case 2:
-                 /* A A B */
-                 to_next -= 1;
-                 n_left_to_next += 1;
-                 vlib_set_next_frame_buffer (vm, node, next1, pi1);
-                 break;
-
-               case 3:
-                 /* A B B or A B C */
-                 to_next -= 2;
-                 n_left_to_next += 2;
-                 vlib_set_next_frame_buffer (vm, node, next0, pi0);
-                 vlib_set_next_frame_buffer (vm, node, next1, pi1);
-                 if (next0 == next1)
-                   {
-                     vlib_put_next_frame (vm, node, next_index,
-                                          n_left_to_next);
-                     next_index = next1;
-                     vlib_get_next_frame (vm, node, next_index, to_next,
-                                          n_left_to_next);
-                   }
-                 break;
-               }
+             if (PREDICT_TRUE (error0 == (u8) IP4_ERROR_UNKNOWN_PROTOCOL))
+               vnet_feature_arc_start (arc_index, sw_if_index0, &next0, p0);
+             if (PREDICT_TRUE (error1 == (u8) IP4_ERROR_UNKNOWN_PROTOCOL))
+               vnet_feature_arc_start (arc_index, sw_if_index1, &next1, p1);
            }
+
+         vlib_validate_buffer_enqueue_x2 (vm, node, next_index, to_next,
+                                          n_left_to_next, pi0, pi1,
+                                          next0, next1);
        }
 
       while (n_left_from > 0 && n_left_to_next > 0)
@@ -1746,6 +1744,7 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          u8 error0, is_udp0, is_tcp_udp0, good_tcp_udp0, proto0;
          load_balance_t *lb0;
          const dpo_id_t *dpo0;
+         u32 sw_if_index0;
 
          pi0 = to_next[0] = from[0];
          from += 1;
@@ -1753,14 +1752,18 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          to_next += 1;
          n_left_to_next -= 1;
 
+         next0 = IP_LOCAL_NEXT_DROP;
+
          p0 = vlib_get_buffer (vm, pi0);
 
          ip0 = vlib_buffer_get_current (p0);
 
          vnet_buffer (p0)->ip.start_of_ip_header = p0->current_data;
 
-         fib_index0 = vec_elt (im->fib_index_by_sw_if_index,
-                               vnet_buffer (p0)->sw_if_index[VLIB_RX]);
+         sw_if_index0 = vnet_buffer (p0)->sw_if_index[VLIB_RX];
+
+         fib_index0 = vec_elt (im->fib_index_by_sw_if_index, sw_if_index0);
+
          fib_index0 =
            (vnet_buffer (p0)->sw_if_index[VLIB_TX] ==
             (u32) ~ 0) ? fib_index0 : vnet_buffer (p0)->sw_if_index[VLIB_TX];
@@ -1775,6 +1778,13 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
          /* Treat IP frag packets as "experimental" protocol for now
             until support of IP frag reassembly is implemented */
          proto0 = ip4_is_fragment (ip0) ? 0xfe : ip0->protocol;
+
+         if (head_of_feature_arc == 0)
+           {
+             error0 = IP4_ERROR_UNKNOWN_PROTOCOL;
+             goto skip_check;
+           }
+
          is_udp0 = proto0 == IP_PROTOCOL_UDP;
          is_tcp_udp0 = is_udp0 || proto0 == IP_PROTOCOL_TCP;
 
@@ -1847,6 +1857,8 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
                     ip0->dst_address.as_u32 != 0xFFFFFFFF)
                    ? IP4_ERROR_SRC_LOOKUP_MISS : error0);
 
+       skip_check:
+
          next0 = lm->local_next_by_ip_protocol[proto0];
 
          next0 =
@@ -1854,18 +1866,15 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
 
          p0->error = error0 ? error_node->errors[error0] : 0;
 
-         if (PREDICT_FALSE (next0 != next_index))
+         if (head_of_feature_arc)
            {
-             n_left_to_next += 1;
-             vlib_put_next_frame (vm, node, next_index, n_left_to_next);
-
-             next_index = next0;
-             vlib_get_next_frame (vm, node, next_index, to_next,
-                                  n_left_to_next);
-             to_next[0] = pi0;
-             to_next += 1;
-             n_left_to_next -= 1;
+             if (PREDICT_TRUE (error0 == (u8) IP4_ERROR_UNKNOWN_PROTOCOL))
+               vnet_feature_arc_start (arc_index, sw_if_index0, &next0, p0);
            }
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, pi0, next0);
+
        }
 
       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
@@ -1874,21 +1883,57 @@ ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
   return frame->n_vectors;
 }
 
+static uword
+ip4_local (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame)
+{
+  return ip4_local_inline (vm, node, frame, 1 /* head of feature arc */ );
+}
+
+/* *INDENT-OFF* */
 VLIB_REGISTER_NODE (ip4_local_node) =
 {
-  .function = ip4_local,.name = "ip4-local",.vector_size =
-    sizeof (u32),.format_trace =
-    format_ip4_forward_next_trace,.n_next_nodes =
-    IP_LOCAL_N_NEXT,.next_nodes =
+  .function = ip4_local,
+  .name = "ip4-local",
+  .vector_size = sizeof (u32),
+  .format_trace = format_ip4_forward_next_trace,
+  .n_next_nodes = IP_LOCAL_N_NEXT,
+  .next_nodes =
   {
-  [IP_LOCAL_NEXT_DROP] = "error-drop",
-      [IP_LOCAL_NEXT_PUNT] = "error-punt",
-      [IP_LOCAL_NEXT_UDP_LOOKUP] = "ip4-udp-lookup",
-      [IP_LOCAL_NEXT_ICMP] = "ip4-icmp-input",}
-,};
+    [IP_LOCAL_NEXT_DROP] = "error-drop",
+    [IP_LOCAL_NEXT_PUNT] = "error-punt",
+    [IP_LOCAL_NEXT_UDP_LOOKUP] = "ip4-udp-lookup",
+    [IP_LOCAL_NEXT_ICMP] = "ip4-icmp-input",},
+};
+/* *INDENT-ON* */
 
 VLIB_NODE_FUNCTION_MULTIARCH (ip4_local_node, ip4_local);
 
+static uword
+ip4_local_end_of_arc (vlib_main_t * vm,
+                     vlib_node_runtime_t * node, vlib_frame_t * frame)
+{
+  return ip4_local_inline (vm, node, frame, 0 /* head of feature arc */ );
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (ip4_local_end_of_arc_node,static) = {
+  .function = ip4_local_end_of_arc,
+  .name = "ip4-local-end-of-arc",
+  .vector_size = sizeof (u32),
+
+  .format_trace = format_ip4_forward_next_trace,
+  .sibling_of = "ip4-local",
+};
+
+VLIB_NODE_FUNCTION_MULTIARCH (ip4_local_end_of_arc_node, ip4_local_end_of_arc)
+
+VNET_FEATURE_INIT (ip4_local_end_of_arc, static) = {
+  .arc_name = "ip4-local",
+  .node_name = "ip4-local-end-of-arc",
+  .runs_before = 0, /* not before any other features */
+};
+/* *INDENT-ON* */
+
 void
 ip4_register_protocol (u32 protocol, u32 node_index)
 {
index 8da788b..b2c1fcd 100644 (file)
@@ -41,7 +41,7 @@
 #define included_ip4_packet_h
 
 #include <vnet/ip/ip_packet.h> /* for ip_csum_t */
-#include <vnet/ip/tcp_packet.h>        /* for tcp_header_t */
+#include <vnet/tcp/tcp_packet.h>       /* for tcp_header_t */
 #include <vppinfra/byte_order.h>       /* for clib_net_to_host_u16 */
 
 /* IP4 address which can be accessed either as 4 bytes
@@ -342,10 +342,10 @@ ip4_tcp_reply_x1 (ip4_header_t * ip0, tcp_header_t * tcp0)
   ip0->src_address.data_u32 = dst0;
   ip0->dst_address.data_u32 = src0;
 
-  src0 = tcp0->ports.src;
-  dst0 = tcp0->ports.dst;
-  tcp0->ports.src = dst0;
-  tcp0->ports.dst = src0;
+  src0 = tcp0->src;
+  dst0 = tcp0->dst;
+  tcp0->src = dst0;
+  tcp0->dst = src0;
 }
 
 always_inline void
@@ -363,14 +363,14 @@ ip4_tcp_reply_x2 (ip4_header_t * ip0, ip4_header_t * ip1,
   ip0->dst_address.data_u32 = src0;
   ip1->dst_address.data_u32 = src1;
 
-  src0 = tcp0->ports.src;
-  src1 = tcp1->ports.src;
-  dst0 = tcp0->ports.dst;
-  dst1 = tcp1->ports.dst;
-  tcp0->ports.src = dst0;
-  tcp1->ports.src = dst1;
-  tcp0->ports.dst = src0;
-  tcp1->ports.dst = src1;
+  src0 = tcp0->src;
+  src1 = tcp1->src;
+  dst0 = tcp0->dst;
+  dst1 = tcp1->dst;
+  tcp0->src = dst0;
+  tcp1->src = dst1;
+  tcp0->dst = src0;
+  tcp1->dst = src1;
 }
 
 #endif /* included_ip4_packet_h */
index 5456f0f..2615fbf 100644 (file)
@@ -461,8 +461,8 @@ ip6_compute_flow_hash (const ip6_header_t * ip,
   b = (flow_hash_config & IP_FLOW_HASH_REVERSE_SRC_DST) ? t1 : t2;
   b ^= (flow_hash_config & IP_FLOW_HASH_PROTO) ? ip->protocol : 0;
 
-  t1 = is_tcp_udp ? tcp->ports.src : 0;
-  t2 = is_tcp_udp ? tcp->ports.dst : 0;
+  t1 = is_tcp_udp ? tcp->src : 0;
+  t2 = is_tcp_udp ? tcp->dst : 0;
 
   t1 = (flow_hash_config & IP_FLOW_HASH_SRC_PORT) ? t1 : 0;
   t2 = (flow_hash_config & IP_FLOW_HASH_DST_PORT) ? t2 : 0;
@@ -497,6 +497,46 @@ int ip6_hbh_register_option (u8 option,
 int ip6_hbh_unregister_option (u8 option);
 void ip6_hbh_set_next_override (uword next);
 
+/**
+ * Push IPv6 header to buffer
+ *
+ * @param vm - vlib_main
+ * @param b - buffer to write the header to
+ * @param src - source IP
+ * @param dst - destination IP
+ * @param prot - payload proto
+ *
+ * @return - pointer to start of IP header
+ */
+always_inline void *
+vlib_buffer_push_ip6 (vlib_main_t * vm, vlib_buffer_t * b,
+                     ip6_address_t * src, ip6_address_t * dst, int proto)
+{
+  ip6_header_t *ip6h;
+  u16 payload_length;
+
+  /* make some room */
+  ip6h = vlib_buffer_push_uninit (b, sizeof (ip6_header_t));
+
+  ip6h->ip_version_traffic_class_and_flow_label =
+    clib_host_to_net_u32 (0x6 << 28);
+
+  /* calculate ip6 payload length */
+  payload_length = vlib_buffer_length_in_chain (vm, b);
+  payload_length -= sizeof (*ip6h);
+
+  ip6h->payload_length = clib_host_to_net_u16 (payload_length);
+
+  ip6h->hop_limit = 0xff;
+  ip6h->protocol = proto;
+  clib_memcpy (ip6h->src_address.as_u8, src->as_u8,
+              sizeof (ip6h->src_address));
+  clib_memcpy (ip6h->dst_address.as_u8, dst->as_u8,
+              sizeof (ip6h->src_address));
+
+  return ip6h;
+}
+
 #endif /* included_ip_ip6_h */
 
 /*
index 1e551c8..4fd14b9 100644 (file)
@@ -40,7 +40,7 @@
 #ifndef included_ip6_packet_h
 #define included_ip6_packet_h
 
-#include <vnet/ip/tcp_packet.h>
+#include <vnet/tcp/tcp_packet.h>
 #include <vnet/ip/ip4_packet.h>
 
 typedef union
@@ -373,10 +373,10 @@ ip6_tcp_reply_x1 (ip6_header_t * ip0, tcp_header_t * tcp0)
   {
     u16 src0, dst0;
 
-    src0 = tcp0->ports.src;
-    dst0 = tcp0->ports.dst;
-    tcp0->ports.src = dst0;
-    tcp0->ports.dst = src0;
+    src0 = tcp0->src;
+    dst0 = tcp0->dst;
+    tcp0->src = dst0;
+    tcp0->dst = src0;
   }
 }
 
@@ -400,14 +400,14 @@ ip6_tcp_reply_x2 (ip6_header_t * ip0, ip6_header_t * ip1,
   {
     u16 src0, dst0, src1, dst1;
 
-    src0 = tcp0->ports.src;
-    src1 = tcp1->ports.src;
-    dst0 = tcp0->ports.dst;
-    dst1 = tcp1->ports.dst;
-    tcp0->ports.src = dst0;
-    tcp1->ports.src = dst1;
-    tcp0->ports.dst = src0;
-    tcp1->ports.dst = src1;
+    src0 = tcp0->src;
+    src1 = tcp1->src;
+    dst0 = tcp0->dst;
+    dst1 = tcp1->dst;
+    tcp0->src = dst0;
+    tcp1->src = dst1;
+    tcp0->dst = src0;
+    tcp1->dst = src1;
   }
 }
 
index 9c73512..4855840 100644 (file)
@@ -23,7 +23,7 @@
  */
 #include <vlib/vlib.h>
 #include <vnet/pg/pg.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ip/punt.h>
 
 #define foreach_punt_next \
diff --git a/src/vnet/ip/tcp_packet.h b/src/vnet/ip/tcp_packet.h
deleted file mode 100644 (file)
index 93f73e0..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright (c) 2015 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * ip4/tcp_packet.h: TCP packet format (see RFC 793)
- *
- * Copyright (c) 2008 Eliot Dresselhaus
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef included_tcp_packet_h
-#define included_tcp_packet_h
-
-/* TCP flags bit 0 first. */
-#define foreach_tcp_flag                       \
-  _ (FIN)                                      \
-  _ (SYN)                                      \
-  _ (RST)                                      \
-  _ (PSH)                                      \
-  _ (ACK)                                      \
-  _ (URG)                                      \
-  _ (ECE)                                      \
-  _ (CWR)
-
-enum
-{
-#define _(f) TCP_FLAG_BIT_##f,
-  foreach_tcp_flag
-#undef _
-    TCP_N_FLAG_BITS,
-
-#define _(f) TCP_FLAG_##f = 1 << TCP_FLAG_BIT_##f,
-  foreach_tcp_flag
-#undef _
-};
-
-typedef struct
-{
-  /* Source and destination port. */
-  union
-  {
-    union
-    {
-      struct
-      {
-       u16 src, dst;
-      };
-      u32 src_and_dst;
-    } ports;
-    struct
-    {
-      u16 src_port, dst_port;
-    };
-  };
-
-  /* Sequence and acknowledgment number. */
-  u32 seq_number, ack_number;
-
-  /* Size of TCP header in 32-bit units plus 4 reserved bits. */
-  u8 tcp_header_u32s_and_reserved;
-
-  /* see foreach_tcp_flag for enumation of tcp flags. */
-  u8 flags;
-
-  /* Current window advertised by sender.
-     This is the number of bytes sender is willing to receive
-     right now. */
-  u16 window;
-
-  /* Checksum of TCP pseudo header and data. */
-  u16 checksum;
-
-  u16 urgent_pointer;
-} tcp_header_t;
-
-always_inline int
-tcp_header_bytes (tcp_header_t * t)
-{
-  return (t->tcp_header_u32s_and_reserved >> 4) * sizeof (u32);
-}
-
-/* TCP options. */
-typedef enum tcp_option_type
-{
-  TCP_OPTION_END = 0,
-  TCP_OPTION_NOP = 1,
-  TCP_OPTION_MSS = 2,
-  TCP_OPTION_WINDOW_SCALE = 3,
-  TCP_OPTION_SACK_PERMITTED = 4,
-  TCP_OPTION_SACK_BLOCK = 5,
-  TCP_OPTION_TIME_STAMP = 8,
-} tcp_option_type_t;
-
-/* All except NOP and END have 1 byte length field. */
-typedef struct
-{
-  tcp_option_type_t type:8;
-
-  /* Length of this option in bytes. */
-  u8 length;
-} tcp_option_with_length_t;
-
-#endif /* included_tcp_packet_h */
-
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables:
- * eval: (c-set-style "gnu")
- * End:
- */
diff --git a/src/vnet/ip/udp_init.c b/src/vnet/ip/udp_init.c
deleted file mode 100644 (file)
index 1241ca4..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2015 Cisco and/or its affiliates.
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * ip/udp_init.c: udp initialization
- *
- * Copyright (c) 2008 Eliot Dresselhaus
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#include <vnet/ip/ip.h>
-
-clib_error_t *
-udp_init (vlib_main_t * vm)
-{
-  ip_main_t *im = &ip_main;
-  ip_protocol_info_t *pi;
-  clib_error_t *error;
-
-  error = vlib_call_init_function (vm, ip_main_init);
-
-  if (!error)
-    {
-      pi = ip_get_protocol_info (im, IP_PROTOCOL_UDP);
-      if (pi == 0)
-       return clib_error_return (0, "UDP protocol info AWOL");
-      pi->format_header = format_udp_header;
-      pi->unformat_pg_edit = unformat_pg_udp_header;
-    }
-
-  return 0;
-}
-
-VLIB_INIT_FUNCTION (udp_init);
-
-/*
- * fd.io coding-style-patch-verification: ON
- *
- * Local Variables:
- * eval: (c-set-style "gnu")
- * End:
- */
index 0920933..2c1074d 100644 (file)
@@ -17,7 +17,7 @@
 #include <vnet/vnet.h>
 #include <vnet/pg/pg.h>
 #include <vppinfra/error.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ipsec/ipsec.h>
 #include <vnet/ipsec/ikev2.h>
 #include <vnet/ipsec/ikev2_priv.h>
index 5c88d8d..05ed4e6 100644 (file)
@@ -16,7 +16,7 @@
 #include <vnet/vnet.h>
 #include <vnet/pg/pg.h>
 #include <vppinfra/error.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ipsec/ikev2.h>
 #include <vnet/ipsec/ikev2_priv.h>
 
index c201d3e..ca56158 100644 (file)
@@ -17,7 +17,7 @@
 #include <vnet/vnet.h>
 #include <vnet/pg/pg.h>
 #include <vppinfra/error.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ipsec/ikev2.h>
 #include <vnet/ipsec/ikev2_priv.h>
 #include <openssl/obj_mac.h>
index 3a4f421..f24024f 100644 (file)
@@ -15,7 +15,7 @@
 
 #include <vnet/lisp-cp/packets.h>
 #include <vnet/lisp-cp/lisp_cp_messages.h>
-#include <vnet/ip/udp_packet.h>
+#include <vnet/udp/udp_packet.h>
 
 /* Returns IP ID for the packet */
 /* static u16 ip_id = 0;
@@ -141,61 +141,6 @@ pkt_push_udp (vlib_main_t * vm, vlib_buffer_t * b, u16 sp, u16 dp)
   return uh;
 }
 
-void *
-pkt_push_ipv4 (vlib_main_t * vm, vlib_buffer_t * b, ip4_address_t * src,
-              ip4_address_t * dst, int proto)
-{
-  ip4_header_t *ih;
-
-  /* make some room */
-  ih = vlib_buffer_push_uninit (b, sizeof (ip4_header_t));
-
-  ih->ip_version_and_header_length = 0x45;
-  ih->tos = 0;
-  ih->length = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, b));
-
-  /* iph->fragment_id = clib_host_to_net_u16(get_IP_ID ()); */
-
-  /* TODO: decide if we allow fragments in case of control */
-  ih->flags_and_fragment_offset = clib_host_to_net_u16 (IP_DF);
-  ih->ttl = 255;
-  ih->protocol = proto;
-  ih->src_address.as_u32 = src->as_u32;
-  ih->dst_address.as_u32 = dst->as_u32;
-
-  ih->checksum = ip4_header_checksum (ih);
-  return ih;
-}
-
-void *
-pkt_push_ipv6 (vlib_main_t * vm, vlib_buffer_t * b, ip6_address_t * src,
-              ip6_address_t * dst, int proto)
-{
-  ip6_header_t *ip6h;
-  u16 payload_length;
-
-  /* make some room */
-  ip6h = vlib_buffer_push_uninit (b, sizeof (ip6_header_t));
-
-  ip6h->ip_version_traffic_class_and_flow_label =
-    clib_host_to_net_u32 (0x6 << 28);
-
-  /* calculate ip6 payload length */
-  payload_length = vlib_buffer_length_in_chain (vm, b);
-  payload_length -= sizeof (*ip6h);
-
-  ip6h->payload_length = clib_host_to_net_u16 (payload_length);
-
-  ip6h->hop_limit = 0xff;
-  ip6h->protocol = proto;
-  clib_memcpy (ip6h->src_address.as_u8, src->as_u8,
-              sizeof (ip6h->src_address));
-  clib_memcpy (ip6h->dst_address.as_u8, dst->as_u8,
-              sizeof (ip6h->src_address));
-
-  return ip6h;
-}
-
 void *
 pkt_push_ip (vlib_main_t * vm, vlib_buffer_t * b, ip_address_t * src,
             ip_address_t * dst, u32 proto)
@@ -210,12 +155,12 @@ pkt_push_ip (vlib_main_t * vm, vlib_buffer_t * b, ip_address_t * src,
   switch (ip_addr_version (src))
     {
     case IP4:
-      return pkt_push_ipv4 (vm, b, &ip_addr_v4 (src), &ip_addr_v4 (dst),
-                           proto);
+      return vlib_buffer_push_ip4 (vm, b, &ip_addr_v4 (src),
+                                  &ip_addr_v4 (dst), proto);
       break;
     case IP6:
-      return pkt_push_ipv6 (vm, b, &ip_addr_v6 (src), &ip_addr_v6 (dst),
-                           proto);
+      return vlib_buffer_push_ip6 (vm, b, &ip_addr_v6 (src),
+                                  &ip_addr_v6 (dst), proto);
       break;
     }
 
index 212a1d7..f6da3bf 100644 (file)
@@ -26,51 +26,6 @@ void *pkt_push_udp_and_ip (vlib_main_t * vm, vlib_buffer_t * b, u16 sp,
 
 void *pkt_push_ecm_hdr (vlib_buffer_t * b);
 
-always_inline u8 *
-vlib_buffer_get_tail (vlib_buffer_t * b)
-{
-  return b->data + b->current_data + b->current_length;
-}
-
-always_inline void *
-vlib_buffer_put_uninit (vlib_buffer_t * b, u8 size)
-{
-  /* XXX should make sure there's enough space! */
-  void *p = vlib_buffer_get_tail (b);
-  b->current_length += size;
-  return p;
-}
-
-always_inline void *
-vlib_buffer_push_uninit (vlib_buffer_t * b, u8 size)
-{
-  /* XXX should make sure there's enough space! */
-  ASSERT (b->current_data >= size);
-  b->current_data -= size;
-  b->current_length += size;
-
-  return vlib_buffer_get_current (b);
-}
-
-always_inline void *
-vlib_buffer_make_headroom (vlib_buffer_t * b, u8 size)
-{
-  /* XXX should make sure there's enough space! */
-  b->current_data += size;
-  return vlib_buffer_get_current (b);
-}
-
-always_inline void *
-vlib_buffer_pull (vlib_buffer_t * b, u8 size)
-{
-  if (b->current_length < size)
-    return 0;
-
-  void *data = vlib_buffer_get_current (b);
-  vlib_buffer_advance (b, size);
-  return data;
-}
-
 /* *INDENT-ON* */
 
 /*
index 1335927..292c7e6 100644 (file)
@@ -23,7 +23,7 @@
 #include <vppinfra/hash.h>
 #include <vnet/vnet.h>
 #include <vnet/ip/ip.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/ethernet/ethernet.h>
 #include <vnet/lisp-gpe/lisp_gpe.h>
 #include <vnet/lisp-gpe/lisp_gpe_fwd_entry.h>
index c898a7d..b5a50ec 100644 (file)
 #include <vnet/l2/l2_input.h>
 #include <vnet/ethernet/ethernet.h>
 #include <vnet/ip/ip4_packet.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/lisp-cp/lisp_types.h>
 #include <vnet/lisp-gpe/lisp_gpe_packet.h>
 #include <vnet/adj/adj_types.h>
+#include <vppinfra/bihash_24_8.h>
+#include <vppinfra/bihash_template.h>
 
 /** IP4-UDP-LISP encap header */
 /* *INDENT-OFF* */
index 65006b8..dbcf713 100644 (file)
@@ -25,6 +25,8 @@
 #include <vnet/lisp-gpe/lisp_gpe_tunnel.h>
 #include <vnet/fib/fib_entry.h>
 #include <vnet/adj/adj_midchain.h>
+#include <vppinfra/bihash_24_8.h>
+#include <vppinfra/bihash_template.h>
 
 /**
  * Memory pool of all adjacencies
diff --git a/src/vnet/session/application.c b/src/vnet/session/application.c
new file mode 100644 (file)
index 0000000..a561e7d
--- /dev/null
@@ -0,0 +1,343 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vnet/session/application.h>
+#include <vnet/session/session.h>
+
+/*
+ * Pool from which we allocate all applications
+ */
+static application_t *app_pool;
+
+/*
+ * Hash table of apps by api client index
+ */
+static uword *app_by_api_client_index;
+
+int
+application_api_queue_is_full (application_t * app)
+{
+  unix_shared_memory_queue_t *q;
+
+  /* builtin servers are always OK */
+  if (app->api_client_index == ~0)
+    return 0;
+
+  q = vl_api_client_index_to_input_queue (app->api_client_index);
+  if (!q)
+    return 1;
+
+  if (q->cursize == q->maxsize)
+    return 1;
+  return 0;
+}
+
+static void
+application_table_add (application_t * app)
+{
+  hash_set (app_by_api_client_index, app->api_client_index, app->index);
+}
+
+static void
+application_table_del (application_t * app)
+{
+  hash_unset (app_by_api_client_index, app->api_client_index);
+}
+
+application_t *
+application_lookup (u32 api_client_index)
+{
+  uword *p;
+  p = hash_get (app_by_api_client_index, api_client_index);
+  if (p)
+    return application_get (p[0]);
+
+  return 0;
+}
+
+void
+application_del (application_t * app)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  api_main_t *am = &api_main;
+  void *oldheap;
+  session_manager_t *sm;
+
+  if (app->mode == APP_SERVER)
+    {
+      sm = session_manager_get (app->session_manager_index);
+      session_manager_del (smm, sm);
+    }
+
+  /* Free the event fifo in the /vpe-api shared-memory segment */
+  oldheap = svm_push_data_heap (am->vlib_rp);
+  if (app->event_queue)
+    unix_shared_memory_queue_free (app->event_queue);
+  svm_pop_heap (oldheap);
+
+  application_table_del (app);
+
+  pool_put (app_pool, app);
+}
+
+application_t *
+application_new (application_type_t type, session_type_t sst,
+                u32 api_client_index, u32 flags, session_cb_vft_t * cb_fns)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  api_main_t *am = &api_main;
+  application_t *app;
+  void *oldheap;
+  session_manager_t *sm;
+
+  pool_get (app_pool, app);
+  memset (app, 0, sizeof (*app));
+
+  /* Allocate event fifo in the /vpe-api shared-memory segment */
+  oldheap = svm_push_data_heap (am->vlib_rp);
+
+  /* Allocate server event queue */
+  app->event_queue =
+    unix_shared_memory_queue_init (128 /* nels $$$$ config */ ,
+                                  sizeof (session_fifo_event_t),
+                                  0 /* consumer pid */ ,
+                                  0
+                                  /* (do not) signal when queue non-empty */
+    );
+
+  svm_pop_heap (oldheap);
+
+  /* If a server, allocate session manager */
+  if (type == APP_SERVER)
+    {
+      pool_get (smm->session_managers, sm);
+      memset (sm, 0, sizeof (*sm));
+
+      app->session_manager_index = sm - smm->session_managers;
+    }
+  else if (type == APP_CLIENT)
+    {
+      /* Allocate connect session manager if needed */
+      if (smm->connect_manager_index[sst] == INVALID_INDEX)
+       connects_session_manager_init (smm, sst);
+      app->session_manager_index = smm->connect_manager_index[sst];
+    }
+
+  app->mode = type;
+  app->index = application_get_index (app);
+  app->session_type = sst;
+  app->api_client_index = api_client_index;
+  app->flags = flags;
+  app->cb_fns = *cb_fns;
+
+  /* Add app to lookup by api_client_index table */
+  application_table_add (app);
+
+  return app;
+}
+
+application_t *
+application_get (u32 index)
+{
+  return pool_elt_at_index (app_pool, index);
+}
+
+u32
+application_get_index (application_t * app)
+{
+  return app - app_pool;
+}
+
+int
+application_server_init (application_t * server, u32 segment_size,
+                        u32 add_segment_size, u32 rx_fifo_size,
+                        u32 tx_fifo_size, u8 ** segment_name)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  session_manager_t *sm;
+  int rv;
+
+  sm = session_manager_get (server->session_manager_index);
+
+  /* Add first segment */
+  if ((rv = session_manager_add_first_segment (smm, sm, segment_size,
+                                              segment_name)))
+    {
+      return rv;
+    }
+
+  /* Setup session manager */
+  sm->add_segment_size = add_segment_size;
+  sm->rx_fifo_size = rx_fifo_size;
+  sm->tx_fifo_size = tx_fifo_size;
+  sm->add_segment = sm->add_segment_size != 0;
+  return 0;
+}
+
+u8 *
+format_application_server (u8 * s, va_list * args)
+{
+  application_t *srv = va_arg (*args, application_t *);
+  int verbose = va_arg (*args, int);
+  vl_api_registration_t *regp;
+  stream_session_t *listener;
+  u8 *server_name, *str, *seg_name;
+  u32 segment_size;
+
+  if (srv == 0)
+    {
+      if (verbose)
+       s = format (s, "%-40s%-20s%-15s%-15s%-10s", "Connection", "Server",
+                   "Segment", "API Client", "Cookie");
+      else
+       s = format (s, "%-40s%-20s", "Connection", "Server");
+
+      return s;
+    }
+
+  regp = vl_api_client_index_to_registration (srv->api_client_index);
+  if (!regp)
+    server_name = format (0, "%s%c", regp->name, 0);
+  else
+    server_name = regp->name;
+
+  listener = stream_session_listener_get (srv->session_type,
+                                         srv->session_index);
+  str = format (0, "%U", format_stream_session, listener, verbose);
+
+  session_manager_get_segment_info (listener->server_segment_index, &seg_name,
+                                   &segment_size);
+  if (verbose)
+    {
+      s = format (s, "%-40s%-20s%-20s%-10d%-10d", str, server_name,
+                 seg_name, srv->api_client_index, srv->accept_cookie);
+    }
+  else
+    s = format (s, "%-40s%-20s", str, server_name);
+  return s;
+}
+
+u8 *
+format_application_client (u8 * s, va_list * args)
+{
+  application_t *client = va_arg (*args, application_t *);
+  int verbose = va_arg (*args, int);
+  stream_session_t *session;
+  u8 *str, *seg_name;
+  u32 segment_size;
+
+  if (client == 0)
+    {
+      if (verbose)
+       s =
+         format (s, "%-40s%-20s%-10s", "Connection", "Segment",
+                 "API Client");
+      else
+       s = format (s, "%-40s", "Connection");
+
+      return s;
+    }
+
+  session = stream_session_get (client->session_index, client->thread_index);
+  str = format (0, "%U", format_stream_session, session, verbose);
+
+  session_manager_get_segment_info (session->server_segment_index, &seg_name,
+                                   &segment_size);
+  if (verbose)
+    {
+      s = format (s, "%-40s%-20s%-10d%", str, seg_name,
+                 client->api_client_index);
+    }
+  else
+    s = format (s, "%-40s", str);
+  return s;
+}
+
+static clib_error_t *
+show_app_command_fn (vlib_main_t * vm, unformat_input_t * input,
+                    vlib_cli_command_t * cmd)
+{
+  application_t *app;
+  int do_server = 0;
+  int do_client = 0;
+  int verbose = 0;
+
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "server"))
+       do_server = 1;
+      else if (unformat (input, "client"))
+       do_client = 1;
+      else if (unformat (input, "verbose"))
+       verbose = 1;
+      else
+       break;
+    }
+
+  if (do_server)
+    {
+      if (pool_elts (app_pool))
+       {
+         vlib_cli_output (vm, "%U", format_application_server,
+                          0 /* header */ ,
+                          verbose);
+          /* *INDENT-OFF* */
+          pool_foreach (app, app_pool,
+          ({
+            if (app->mode == APP_SERVER)
+              vlib_cli_output (vm, "%U", format_application_server, app,
+                               verbose);
+          }));
+          /* *INDENT-ON* */
+       }
+      else
+       vlib_cli_output (vm, "No active server bindings");
+    }
+
+  if (do_client)
+    {
+      if (pool_elts (app_pool))
+       {
+         vlib_cli_output (vm, "%U", format_application_client,
+                          0 /* header */ ,
+                          verbose);
+          /* *INDENT-OFF* */
+          pool_foreach (app, app_pool,
+          ({
+            if (app->mode == APP_CLIENT)
+              vlib_cli_output (vm, "%U", format_application_client, app,
+                               verbose);
+          }));
+          /* *INDENT-ON* */
+       }
+      else
+       vlib_cli_output (vm, "No active server bindings");
+    }
+
+  return 0;
+}
+
+VLIB_CLI_COMMAND (show_app_command, static) =
+{
+.path = "show app",.short_help =
+    "show app [server|client] [verbose]",.function = show_app_command_fn,};
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/application.h b/src/vnet/session/application.h
new file mode 100644 (file)
index 0000000..027d696
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef SRC_VNET_SESSION_APPLICATION_H_
+#define SRC_VNET_SESSION_APPLICATION_H_
+
+#include <vnet/vnet.h>
+#include <vnet/session/session.h>
+
+typedef enum
+{
+  APP_SERVER,
+  APP_CLIENT
+} application_type_t;
+
+typedef struct _stream_session_cb_vft
+{
+  /** Notify server of new segment */
+  int (*add_segment_callback) (u32 api_client_index, const u8 * seg_name,
+                              u32 seg_size);
+
+  /** Notify server of newly accepted session */
+  int (*session_accept_callback) (stream_session_t * new_session);
+
+  /* Connection request callback */
+  int (*session_connected_callback) (u32 api_client_index,
+                                    stream_session_t * s, u8 code);
+
+  /** Notify app that session is closing */
+  void (*session_disconnect_callback) (stream_session_t * s);
+
+  /** Notify app that session was reset */
+  void (*session_reset_callback) (stream_session_t * s);
+
+  /* Direct RX callback, for built-in servers */
+  int (*builtin_server_rx_callback) (stream_session_t * session);
+
+  /* Redirect connection to local server */
+  int (*redirect_connect_callback) (u32 api_client_index, void *mp);
+} session_cb_vft_t;
+
+typedef struct _application
+{
+  /** Index in server pool */
+  u32 index;
+
+  /** Flags */
+  u32 flags;
+
+  /** Binary API connection index, ~0 if internal */
+  u32 api_client_index;
+
+  /* */
+  u32 api_context;
+
+  /** Application listens for events on this svm queue */
+  unix_shared_memory_queue_t *event_queue;
+
+  /** Stream session type */
+  u8 session_type;
+
+  /* Stream server mode: accept or connect */
+  u8 mode;
+
+  u32 session_manager_index;
+
+  /*
+   * Bind/Listen specific
+   */
+
+  /** Accept cookie, for multiple session flavors ($$$ maybe) */
+  u32 accept_cookie;
+
+  /** Index of the listen session or connect session */
+  u32 session_index;
+
+  /** Session thread index for client connect sessions */
+  u32 thread_index;
+
+  /*
+   * Callbacks: shoulder-taps for the server/client
+   */
+  session_cb_vft_t cb_fns;
+} application_t;
+
+application_t *application_new (application_type_t type, session_type_t sst,
+                               u32 api_client_index, u32 flags,
+                               session_cb_vft_t * cb_fns);
+void application_del (application_t * app);
+application_t *application_get (u32 index);
+application_t *application_lookup (u32 api_client_index);
+u32 application_get_index (application_t * app);
+
+int
+application_server_init (application_t * server, u32 segment_size,
+                        u32 add_segment_size, u32 rx_fifo_size,
+                        u32 tx_fifo_size, u8 ** segment_name);
+int application_api_queue_is_full (application_t * app);
+
+#endif /* SRC_VNET_SESSION_APPLICATION_H_ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/application_interface.c b/src/vnet/session/application_interface.c
new file mode 100644 (file)
index 0000000..0ea77fd
--- /dev/null
@@ -0,0 +1,459 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <vnet/session/application_interface.h>
+
+#include <vnet/session/session.h>
+#include <vlibmemory/api.h>
+#include <vnet/dpo/load_balance.h>
+#include <vnet/fib/ip4_fib.h>
+
+/** @file
+    VPP's application/session API bind/unbind/connect/disconnect calls
+*/
+
+static u8
+ip_is_zero (ip46_address_t * ip46_address, u8 is_ip4)
+{
+  if (is_ip4)
+    return (ip46_address->ip4.as_u32 == 0);
+  else
+    return (ip46_address->as_u64[0] == 0 && ip46_address->as_u64[1] == 0);
+}
+
+static u8
+ip_is_local (ip46_address_t * ip46_address, u8 is_ip4)
+{
+  fib_node_index_t fei;
+  fib_entry_flag_t flags;
+  fib_prefix_t prefix;
+
+  /* Check if requester is local */
+  if (is_ip4)
+    {
+      prefix.fp_len = 32;
+      prefix.fp_proto = FIB_PROTOCOL_IP4;
+    }
+  else
+    {
+      prefix.fp_len = 128;
+      prefix.fp_proto = FIB_PROTOCOL_IP6;
+    }
+
+  clib_memcpy (&prefix.fp_addr, ip46_address, sizeof (ip46_address));
+  fei = fib_table_lookup (0, &prefix);
+  flags = fib_entry_get_flags (fei);
+
+  return (flags & FIB_ENTRY_FLAG_LOCAL);
+}
+
+int
+api_parse_session_handle (u64 handle, u32 * session_index, u32 * thread_index)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  stream_session_t *pool;
+
+  *thread_index = handle & 0xFFFFFFFF;
+  *session_index = handle >> 32;
+
+  if (*thread_index >= vec_len (smm->sessions))
+    return VNET_API_ERROR_INVALID_VALUE;
+
+  pool = smm->sessions[*thread_index];
+
+  if (pool_is_free_index (pool, *session_index))
+    return VNET_API_ERROR_INVALID_VALUE_2;
+
+  return 0;
+}
+
+int
+vnet_bind_i (u32 api_client_index, ip46_address_t * ip46, u16 port_host_order,
+            session_type_t sst, u64 * options, session_cb_vft_t * cb_fns,
+            application_t ** app, u32 * len_seg_name, char *seg_name)
+{
+  u8 *segment_name = 0;
+  application_t *server = 0;
+  stream_session_t *listener;
+  u8 is_ip4;
+
+  listener =
+    stream_session_lookup_listener (ip46,
+                                   clib_host_to_net_u16 (port_host_order),
+                                   sst);
+
+  if (listener)
+    return VNET_API_ERROR_ADDRESS_IN_USE;
+
+  if (application_lookup (api_client_index))
+    {
+      clib_warning ("Only one bind supported for now");
+      return VNET_API_ERROR_ADDRESS_IN_USE;
+    }
+
+  is_ip4 = SESSION_TYPE_IP4_UDP == sst || SESSION_TYPE_IP4_TCP == sst;
+  if (!ip_is_zero (ip46, is_ip4) && !ip_is_local (ip46, is_ip4))
+    return VNET_API_ERROR_INVALID_VALUE;
+
+  /* Allocate and initialize stream server */
+  server = application_new (APP_SERVER, sst, api_client_index,
+                           options[SESSION_OPTIONS_FLAGS], cb_fns);
+
+  application_server_init (server, options[SESSION_OPTIONS_SEGMENT_SIZE],
+                          options[SESSION_OPTIONS_ADD_SEGMENT_SIZE],
+                          options[SESSION_OPTIONS_RX_FIFO_SIZE],
+                          options[SESSION_OPTIONS_TX_FIFO_SIZE],
+                          &segment_name);
+
+  /* Setup listen path down to transport */
+  stream_session_start_listen (server->index, ip46, port_host_order);
+
+  /*
+   * Return values
+   */
+
+  ASSERT (vec_len (segment_name) <= 128);
+  *len_seg_name = vec_len (segment_name);
+  memcpy (seg_name, segment_name, *len_seg_name);
+  *app = server;
+
+  return 0;
+}
+
+int
+vnet_unbind_i (u32 api_client_index)
+{
+  application_t *server;
+
+  /*
+   * Find the stream_server_t corresponding to the api client
+   */
+  server = application_lookup (api_client_index);
+  if (!server)
+    return VNET_API_ERROR_INVALID_VALUE_2;
+
+  /* Clear the listener */
+  stream_session_stop_listen (server->index);
+  application_del (server);
+
+  return 0;
+}
+
+int
+vnet_connect_i (u32 api_client_index, u32 api_context, session_type_t sst,
+               ip46_address_t * ip46, u16 port, u64 * options, void *mp,
+               session_cb_vft_t * cb_fns)
+{
+  stream_session_t *listener;
+  application_t *server, *app;
+
+  /*
+   * Figure out if connecting to a local server
+   */
+  listener = stream_session_lookup_listener (ip46,
+                                            clib_host_to_net_u16 (port),
+                                            sst);
+  if (listener)
+    {
+      server = application_get (listener->app_index);
+
+      /*
+       * Server is willing to have a direct fifo connection created
+       * instead of going through the state machine, etc.
+       */
+      if (server->flags & SESSION_OPTIONS_FLAGS_USE_FIFO)
+       return server->cb_fns.
+         redirect_connect_callback (server->api_client_index, mp);
+    }
+
+  /* Create client app */
+  app = application_new (APP_CLIENT, sst, api_client_index,
+                        options[SESSION_OPTIONS_FLAGS], cb_fns);
+
+  app->api_context = api_context;
+
+  /*
+   * Not connecting to a local server. Create regular session
+   */
+  stream_session_open (sst, ip46, port, app->index);
+
+  return 0;
+}
+
+/**
+ * unformat a vnet URI
+ *
+ * fifo://name
+ * tcp://ip46-addr:port
+ * udp://ip46-addr:port
+ *
+ * u8 ip46_address[16];
+ * u16  port_in_host_byte_order;
+ * stream_session_type_t sst;
+ * u8 *fifo_name;
+ *
+ * if (unformat (input, "%U", unformat_vnet_uri, &ip46_address,
+ *              &sst, &port, &fifo_name))
+ *  etc...
+ *
+ */
+uword
+unformat_vnet_uri (unformat_input_t * input, va_list * args)
+{
+  ip46_address_t *address = va_arg (*args, ip46_address_t *);
+  session_type_t *sst = va_arg (*args, session_type_t *);
+  u16 *port = va_arg (*args, u16 *);
+
+  if (unformat (input, "tcp://%U/%d", unformat_ip4_address, &address->ip4,
+               port))
+    {
+      *sst = SESSION_TYPE_IP4_TCP;
+      return 1;
+    }
+  if (unformat (input, "udp://%U/%d", unformat_ip4_address, &address->ip4,
+               port))
+    {
+      *sst = SESSION_TYPE_IP4_UDP;
+      return 1;
+    }
+  if (unformat (input, "udp://%U/%d", unformat_ip6_address, &address->ip6,
+               port))
+    {
+      *sst = SESSION_TYPE_IP6_UDP;
+      return 1;
+    }
+  if (unformat (input, "tcp://%U/%d", unformat_ip6_address, &address->ip6,
+               port))
+    {
+      *sst = SESSION_TYPE_IP6_TCP;
+      return 1;
+    }
+
+  return 0;
+}
+
+int
+parse_uri (char *uri, session_type_t * sst, ip46_address_t * addr,
+          u16 * port_number_host_byte_order)
+{
+  unformat_input_t _input, *input = &_input;
+
+  /* Make sure */
+  uri = (char *) format (0, "%s%c", uri, 0);
+
+  /* Parse uri */
+  unformat_init_string (input, uri, strlen (uri));
+  if (!unformat (input, "%U", unformat_vnet_uri, addr, sst,
+                port_number_host_byte_order))
+    {
+      unformat_free (input);
+      return VNET_API_ERROR_INVALID_VALUE;
+    }
+  unformat_free (input);
+
+  return 0;
+}
+
+int
+vnet_bind_uri (vnet_bind_args_t * a)
+{
+  application_t *server = 0;
+  u16 port_host_order;
+  session_type_t sst = SESSION_N_TYPES;
+  ip46_address_t ip46;
+  int rv;
+
+  memset (&ip46, 0, sizeof (ip46));
+  rv = parse_uri (a->uri, &sst, &ip46, &port_host_order);
+  if (rv)
+    return rv;
+
+  if ((rv = vnet_bind_i (a->api_client_index, &ip46, port_host_order, sst,
+                        a->options, a->session_cb_vft, &server,
+                        &a->segment_name_length, a->segment_name)))
+    return rv;
+
+  a->server_event_queue_address = (u64) server->event_queue;
+  return 0;
+}
+
+session_type_t
+session_type_from_proto_and_ip (session_api_proto_t proto, u8 is_ip4)
+{
+  if (proto == SESSION_PROTO_TCP)
+    {
+      if (is_ip4)
+       return SESSION_TYPE_IP4_TCP;
+      else
+       return SESSION_TYPE_IP6_TCP;
+    }
+  else
+    {
+      if (is_ip4)
+       return SESSION_TYPE_IP4_UDP;
+      else
+       return SESSION_TYPE_IP6_UDP;
+    }
+
+  return SESSION_N_TYPES;
+}
+
+int
+vnet_unbind_uri (char *uri, u32 api_client_index)
+{
+  u16 port_number_host_byte_order;
+  session_type_t sst = SESSION_N_TYPES;
+  ip46_address_t ip46_address;
+  stream_session_t *listener;
+  int rv;
+
+  rv = parse_uri (uri, &sst, &ip46_address, &port_number_host_byte_order);
+  if (rv)
+    return rv;
+
+  listener =
+    stream_session_lookup_listener (&ip46_address,
+                                   clib_host_to_net_u16
+                                   (port_number_host_byte_order), sst);
+
+  if (!listener)
+    return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
+
+  /* External client? */
+  if (api_client_index != ~0)
+    {
+      ASSERT (vl_api_client_index_to_registration (api_client_index));
+    }
+
+  return vnet_unbind_i (api_client_index);
+}
+
+int
+vnet_connect_uri (vnet_connect_args_t * a)
+{
+  ip46_address_t ip46_address;
+  u16 port;
+  session_type_t sst;
+  application_t *app;
+  int rv;
+
+  app = application_lookup (a->api_client_index);
+  if (app)
+    {
+      clib_warning ("Already have a connect from this app");
+      return VNET_API_ERROR_INVALID_VALUE_2;
+    }
+
+  /* Parse uri */
+  rv = parse_uri (a->uri, &sst, &ip46_address, &port);
+  if (rv)
+    return rv;
+
+  return vnet_connect_i (a->api_client_index, a->api_context, sst,
+                        &ip46_address, port, a->options, a->mp,
+                        a->session_cb_vft);
+}
+
+int
+vnet_disconnect_session (u32 client_index, u32 session_index,
+                        u32 thread_index)
+{
+  stream_session_t *session;
+
+  session = stream_session_get (session_index, thread_index);
+  stream_session_disconnect (session);
+
+  return 0;
+}
+
+
+int
+vnet_bind (vnet_bind_args_t * a)
+{
+  application_t *server = 0;
+  session_type_t sst = SESSION_N_TYPES;
+  int rv;
+
+  sst = session_type_from_proto_and_ip (a->proto, a->tep.is_ip4);
+  if ((rv = vnet_bind_i (a->api_client_index, &a->tep.ip, a->tep.port, sst,
+                        a->options, a->session_cb_vft, &server,
+                        &a->segment_name_length, a->segment_name)))
+    return rv;
+
+  a->server_event_queue_address = (u64) server->event_queue;
+  a->handle = (u64) a->tep.vrf << 32 | (u64) server->session_index;
+  return 0;
+}
+
+int
+vnet_unbind (vnet_unbind_args_t * a)
+{
+  application_t *server;
+
+  if (a->api_client_index != ~0)
+    {
+      ASSERT (vl_api_client_index_to_registration (a->api_client_index));
+    }
+
+  /* Make sure this is the right one */
+  server = application_lookup (a->api_client_index);
+  ASSERT (server->session_index == (0xFFFFFFFF & a->handle));
+
+  /* TODO use handle to disambiguate namespaces/vrfs */
+  return vnet_unbind_i (a->api_client_index);
+}
+
+int
+vnet_connect (vnet_connect_args_t * a)
+{
+  session_type_t sst;
+  application_t *app;
+
+  app = application_lookup (a->api_client_index);
+  if (app)
+    {
+      clib_warning ("Already have a connect from this app");
+      return VNET_API_ERROR_INVALID_VALUE_2;
+    }
+
+  sst = session_type_from_proto_and_ip (a->proto, a->tep.is_ip4);
+  return vnet_connect_i (a->api_client_index, a->api_context, sst, &a->tep.ip,
+                        a->tep.port, a->options, a->mp, a->session_cb_vft);
+}
+
+int
+vnet_disconnect (vnet_disconnect_args_t * a)
+{
+  stream_session_t *session;
+  u32 session_index, thread_index;
+
+  if (api_parse_session_handle (a->handle, &session_index, &thread_index))
+    {
+      clib_warning ("Invalid handle");
+      return -1;
+    }
+
+  session = stream_session_get (session_index, thread_index);
+  stream_session_disconnect (session);
+
+  return 0;
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/application_interface.h b/src/vnet/session/application_interface.h
new file mode 100644 (file)
index 0000000..8d87c06
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __included_uri_h__
+#define __included_uri_h__
+
+#include <vlib/vlib.h>
+#include <vnet/vnet.h>
+#include <svm/svm_fifo_segment.h>
+#include <vnet/session/session.h>
+#include <vnet/session/application.h>
+#include <vnet/session/transport.h>
+
+typedef enum _session_api_proto
+{
+  SESSION_PROTO_TCP,
+  SESSION_PROTO_UDP
+} session_api_proto_t;
+
+typedef struct _vnet_bind_args_t
+{
+  union
+  {
+    char *uri;
+    struct
+    {
+      transport_endpoint_t tep;
+      session_api_proto_t proto;
+    };
+  };
+
+  u32 api_client_index;
+  u64 *options;
+  session_cb_vft_t *session_cb_vft;
+
+  /*
+   * Results
+   */
+  char *segment_name;
+  u32 segment_name_length;
+  u64 server_event_queue_address;
+  u64 handle;
+} vnet_bind_args_t;
+
+typedef struct _vnet_unbind_args_t
+{
+  union
+  {
+    char *uri;
+    u64 handle;
+  };
+  u32 api_client_index;
+} vnet_unbind_args_t;
+
+typedef struct _vnet_connect_args
+{
+  union
+  {
+    char *uri;
+    struct
+    {
+      transport_endpoint_t tep;
+      session_api_proto_t proto;
+    };
+  };
+  u32 api_client_index;
+  u32 api_context;
+  u64 *options;
+  session_cb_vft_t *session_cb_vft;
+
+  /* Used for redirects */
+  void *mp;
+} vnet_connect_args_t;
+
+typedef struct _vnet_disconnect_args_t
+{
+  u64 handle;
+  u32 api_client_index;
+} vnet_disconnect_args_t;
+
+/* Bind / connect options */
+typedef enum
+{
+  SESSION_OPTIONS_FLAGS,
+  SESSION_OPTIONS_SEGMENT_SIZE,
+  SESSION_OPTIONS_ADD_SEGMENT_SIZE,
+  SESSION_OPTIONS_RX_FIFO_SIZE,
+  SESSION_OPTIONS_TX_FIFO_SIZE,
+  SESSION_OPTIONS_ACCEPT_COOKIE,
+  SESSION_OPTIONS_N_OPTIONS
+} session_options_index_t;
+
+/** Server can handle delegated connect requests from local clients */
+#define SESSION_OPTIONS_FLAGS_USE_FIFO (1<<0)
+
+/** Server wants vpp to add segments when out of memory for fifos */
+#define SESSION_OPTIONS_FLAGS_ADD_SEGMENT   (1<<1)
+
+#define VNET_CONNECT_REDIRECTED        123
+
+int vnet_bind_uri (vnet_bind_args_t *);
+int vnet_unbind_uri (char *uri, u32 api_client_index);
+int vnet_connect_uri (vnet_connect_args_t * a);
+int
+vnet_disconnect_session (u32 client_index, u32 session_index,
+                        u32 thread_index);
+
+int vnet_bind (vnet_bind_args_t * a);
+int vnet_connect (vnet_connect_args_t * a);
+int vnet_unbind (vnet_unbind_args_t * a);
+int vnet_disconnect (vnet_disconnect_args_t * a);
+
+int
+api_parse_session_handle (u64 handle, u32 * session_index,
+                         u32 * thread_index);
+
+#endif /* __included_uri_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/hashes.c b/src/vnet/session/hashes.c
new file mode 100644 (file)
index 0000000..1808dd7
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Generate typed init functions for multiple hash table styles... */
+
+#include <vppinfra/bihash_16_8.h>
+#include <vppinfra/bihash_template.h>
+
+#include <vppinfra/bihash_template.c>
+
+#undef __included_bihash_template_h__
+
+#include <vppinfra/bihash_48_8.h>
+#include <vppinfra/bihash_template.h>
+
+#include <vppinfra/bihash_template.c>
diff --git a/src/vnet/session/node.c b/src/vnet/session/node.c
new file mode 100644 (file)
index 0000000..e467f4e
--- /dev/null
@@ -0,0 +1,435 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vlib/vlib.h>
+#include <vnet/vnet.h>
+#include <vnet/pg/pg.h>
+#include <vnet/ip/ip.h>
+
+#include <vnet/tcp/tcp.h>
+
+#include <vppinfra/hash.h>
+#include <vppinfra/error.h>
+#include <vppinfra/elog.h>
+#include <vlibmemory/unix_shared_memory_queue.h>
+
+#include <vnet/udp/udp_packet.h>
+#include <vnet/lisp-cp/packets.h>
+#include <math.h>
+
+vlib_node_registration_t session_queue_node;
+
+typedef struct
+{
+  u32 session_index;
+  u32 server_thread_index;
+} session_queue_trace_t;
+
+/* packet trace format function */
+static u8 *
+format_session_queue_trace (u8 * s, va_list * args)
+{
+  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+  session_queue_trace_t *t = va_arg (*args, session_queue_trace_t *);
+
+  s = format (s, "SESSION_QUEUE: session index %d, server thread index %d",
+             t->session_index, t->server_thread_index);
+  return s;
+}
+
+vlib_node_registration_t session_queue_node;
+
+#define foreach_session_queue_error                 \
+_(TX, "Packets transmitted")                    \
+_(TIMER, "Timer events")
+
+typedef enum
+{
+#define _(sym,str) SESSION_QUEUE_ERROR_##sym,
+  foreach_session_queue_error
+#undef _
+    SESSION_QUEUE_N_ERROR,
+} session_queue_error_t;
+
+static char *session_queue_error_strings[] = {
+#define _(sym,string) string,
+  foreach_session_queue_error
+#undef _
+};
+
+static u32 session_type_to_next[] = {
+  SESSION_QUEUE_NEXT_TCP_IP4_OUTPUT,
+  SESSION_QUEUE_NEXT_IP4_LOOKUP,
+  SESSION_QUEUE_NEXT_TCP_IP6_OUTPUT,
+  SESSION_QUEUE_NEXT_IP6_LOOKUP,
+};
+
+always_inline int
+session_fifo_rx_i (vlib_main_t * vm, vlib_node_runtime_t * node,
+                  session_manager_main_t * smm, session_fifo_event_t * e0,
+                  stream_session_t * s0, u32 thread_index, int *n_tx_packets,
+                  u8 peek_data)
+{
+  u32 n_trace = vlib_get_trace_count (vm, node);
+  u32 left_to_snd0, max_len_to_snd0, len_to_deq0, n_bufs, snd_space0;
+  u32 n_frame_bytes, n_frames_per_evt;
+  transport_connection_t *tc0;
+  transport_proto_vft_t *transport_vft;
+  u32 next_index, next0, *to_next, n_left_to_next, bi0;
+  vlib_buffer_t *b0;
+  u32 rx_offset;
+  u16 snd_mss0;
+  u8 *data0;
+  int i;
+
+  next_index = next0 = session_type_to_next[s0->session_type];
+
+  transport_vft = session_get_transport_vft (s0->session_type);
+  tc0 = transport_vft->get_connection (s0->connection_index, thread_index);
+
+  /* Make sure we have space to send and there's something to dequeue */
+  snd_space0 = transport_vft->send_space (tc0);
+  snd_mss0 = transport_vft->send_mss (tc0);
+
+  if (snd_space0 == 0 || svm_fifo_max_dequeue (s0->server_tx_fifo) == 0
+      || snd_mss0 == 0)
+    return 0;
+
+  ASSERT (e0->enqueue_length > 0);
+
+  /* Ensure we're not writing more than transport window allows */
+  max_len_to_snd0 = clib_min (e0->enqueue_length, snd_space0);
+
+  if (peek_data)
+    {
+      /* Offset in rx fifo from where to peek data  */
+      rx_offset = transport_vft->rx_fifo_offset (tc0);
+    }
+
+  /* TODO check if transport is willing to send len_to_snd0
+   * bytes (Nagle) */
+
+  n_frame_bytes = snd_mss0 * VLIB_FRAME_SIZE;
+  n_frames_per_evt = ceil ((double) max_len_to_snd0 / n_frame_bytes);
+
+  n_bufs = vec_len (smm->tx_buffers[thread_index]);
+  left_to_snd0 = max_len_to_snd0;
+  for (i = 0; i < n_frames_per_evt; i++)
+    {
+      /* Make sure we have at least one full frame of buffers ready */
+      if (PREDICT_FALSE (n_bufs < VLIB_FRAME_SIZE))
+       {
+         vec_validate (smm->tx_buffers[thread_index],
+                       n_bufs + VLIB_FRAME_SIZE - 1);
+         n_bufs +=
+           vlib_buffer_alloc (vm, &smm->tx_buffers[thread_index][n_bufs],
+                              VLIB_FRAME_SIZE);
+
+         /* buffer shortage
+          * XXX 0.9 because when debugging we might not get a full frame */
+         if (PREDICT_FALSE (n_bufs < 0.9 * VLIB_FRAME_SIZE))
+           {
+             /* Keep track of how much we've dequeued and exit */
+             e0->enqueue_length -= max_len_to_snd0 - left_to_snd0;
+             return -1;
+           }
+
+         _vec_len (smm->tx_buffers[thread_index]) = n_bufs;
+       }
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+      while (left_to_snd0 && n_left_to_next)
+       {
+         /* Get free buffer */
+         n_bufs--;
+         bi0 = smm->tx_buffers[thread_index][n_bufs];
+         _vec_len (smm->tx_buffers[thread_index]) = n_bufs;
+
+         b0 = vlib_get_buffer (vm, bi0);
+         b0->error = 0;
+         b0->flags = VLIB_BUFFER_TOTAL_LENGTH_VALID
+           | VNET_BUFFER_LOCALLY_ORIGINATED;
+         b0->current_data = 0;
+
+         /* RX on the local interface. tx in default fib */
+         vnet_buffer (b0)->sw_if_index[VLIB_RX] = 0;
+         vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
+
+         /* usual speculation, or the enqueue_x1 macro will barf */
+         to_next[0] = bi0;
+         to_next += 1;
+         n_left_to_next -= 1;
+
+         VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b0);
+         if (PREDICT_FALSE (n_trace > 0))
+           {
+             session_queue_trace_t *t0;
+             vlib_trace_buffer (vm, node, next_index, b0,
+                                1 /* follow_chain */ );
+             vlib_set_trace_count (vm, node, --n_trace);
+             t0 = vlib_add_trace (vm, node, b0, sizeof (*t0));
+             t0->session_index = s0->session_index;
+             t0->server_thread_index = s0->thread_index;
+           }
+
+         if (1)
+           {
+             ELOG_TYPE_DECLARE (e) =
+             {
+             .format = "evt-dequeue: id %d length %d",.format_args =
+                 "i4i4",};
+             struct
+             {
+               u32 data[2];
+             } *ed;
+             ed = ELOG_DATA (&vm->elog_main, e);
+             ed->data[0] = e0->event_id;
+             ed->data[1] = e0->enqueue_length;
+           }
+
+         len_to_deq0 = (left_to_snd0 < snd_mss0) ? left_to_snd0 : snd_mss0;
+
+         /* Make room for headers */
+         data0 = vlib_buffer_make_headroom (b0, MAX_HDRS_LEN);
+
+         /* Dequeue the data
+          * TODO 1) peek instead of dequeue
+          *      2) buffer chains */
+         if (peek_data)
+           {
+             int n_bytes_read;
+             n_bytes_read = svm_fifo_peek (s0->server_tx_fifo, s0->pid,
+                                           rx_offset, len_to_deq0, data0);
+             if (n_bytes_read < 0)
+               goto dequeue_fail;
+
+             /* Keep track of progress locally, transport is also supposed to
+              * increment it independently when pushing header */
+             rx_offset += n_bytes_read;
+           }
+         else
+           {
+             if (svm_fifo_dequeue_nowait (s0->server_tx_fifo, s0->pid,
+                                          len_to_deq0, data0) < 0)
+               goto dequeue_fail;
+           }
+
+         b0->current_length = len_to_deq0;
+
+         /* Ask transport to push header */
+         transport_vft->push_header (tc0, b0);
+
+         left_to_snd0 -= len_to_deq0;
+         *n_tx_packets = *n_tx_packets + 1;
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
+                                          to_next, n_left_to_next,
+                                          bi0, next0);
+       }
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  /* If we couldn't dequeue all bytes store progress */
+  if (max_len_to_snd0 < e0->enqueue_length)
+    {
+      e0->enqueue_length -= max_len_to_snd0;
+      vec_add1 (smm->evts_partially_read[thread_index], *e0);
+    }
+  return 0;
+
+dequeue_fail:
+  /* Can't read from fifo. Store event rx progress, save as partially read,
+   * return buff to free list and return  */
+  e0->enqueue_length -= max_len_to_snd0 - left_to_snd0;
+  vec_add1 (smm->evts_partially_read[thread_index], *e0);
+
+  to_next -= 1;
+  n_left_to_next += 1;
+  _vec_len (smm->tx_buffers[thread_index]) += 1;
+
+  clib_warning ("dequeue fail");
+  return 0;
+}
+
+int
+session_fifo_rx_peek (vlib_main_t * vm, vlib_node_runtime_t * node,
+                     session_manager_main_t * smm, session_fifo_event_t * e0,
+                     stream_session_t * s0, u32 thread_index, int *n_tx_pkts)
+{
+  return session_fifo_rx_i (vm, node, smm, e0, s0, thread_index, n_tx_pkts,
+                           1);
+}
+
+int
+session_fifo_rx_dequeue (vlib_main_t * vm, vlib_node_runtime_t * node,
+                        session_manager_main_t * smm,
+                        session_fifo_event_t * e0, stream_session_t * s0,
+                        u32 thread_index, int *n_tx_pkts)
+{
+  return session_fifo_rx_i (vm, node, smm, e0, s0, thread_index, n_tx_pkts,
+                           0);
+}
+
+static uword
+session_queue_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
+                      vlib_frame_t * frame)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  session_fifo_event_t *my_fifo_events, *e;
+  u32 n_to_dequeue;
+  unix_shared_memory_queue_t *q;
+  int n_tx_packets = 0;
+  u32 my_thread_index = vm->cpu_index;
+  int i, rv;
+
+  /*
+   *  Update TCP time
+   */
+  tcp_update_time (vlib_time_now (vm), my_thread_index);
+
+  /*
+   * Get vpp queue events
+   */
+  q = smm->vpp_event_queues[my_thread_index];
+  if (PREDICT_FALSE (q == 0))
+    return 0;
+
+  /* min number of events we can dequeue without blocking */
+  n_to_dequeue = q->cursize;
+  if (n_to_dequeue == 0)
+    return 0;
+
+  my_fifo_events = smm->fifo_events[my_thread_index];
+
+  /* If we didn't manage to process previous events try going
+   * over them again without dequeuing new ones.
+   * XXX: Block senders to sessions that can't keep up */
+  if (vec_len (my_fifo_events) >= 100)
+    goto skip_dequeue;
+
+  /* See you in the next life, don't be late */
+  if (pthread_mutex_trylock (&q->mutex))
+    return 0;
+
+  for (i = 0; i < n_to_dequeue; i++)
+    {
+      vec_add2 (my_fifo_events, e, 1);
+      unix_shared_memory_queue_sub_raw (q, (u8 *) e);
+    }
+
+  /* The other side of the connection is not polling */
+  if (q->cursize < (q->maxsize / 8))
+    (void) pthread_cond_broadcast (&q->condvar);
+  pthread_mutex_unlock (&q->mutex);
+
+  smm->fifo_events[my_thread_index] = my_fifo_events;
+
+skip_dequeue:
+
+  for (i = 0; i < n_to_dequeue; i++)
+    {
+      svm_fifo_t *f0;          /* $$$ prefetch 1 ahead maybe */
+      stream_session_t *s0;
+      u32 server_session_index0, server_thread_index0;
+      session_fifo_event_t *e0;
+
+      e0 = &my_fifo_events[i];
+      f0 = e0->fifo;
+      server_session_index0 = f0->server_session_index;
+      server_thread_index0 = f0->server_thread_index;
+
+      /* $$$ add multiple event queues, per vpp worker thread */
+      ASSERT (server_thread_index0 == my_thread_index);
+
+      s0 = pool_elt_at_index (smm->sessions[my_thread_index],
+                             server_session_index0);
+
+      ASSERT (s0->thread_index == my_thread_index);
+
+      switch (e0->event_type)
+       {
+       case FIFO_EVENT_SERVER_TX:
+         /* Spray packets in per session type frames, since they go to
+          * different nodes */
+         rv = (smm->session_rx_fns[s0->session_type]) (vm, node, smm, e0, s0,
+                                                       my_thread_index,
+                                                       &n_tx_packets);
+         if (rv < 0)
+           goto done;
+
+         break;
+
+       default:
+         clib_warning ("unhandled event type %d", e0->event_type);
+       }
+    }
+
+done:
+
+  /* Couldn't process all events. Probably out of buffers */
+  if (PREDICT_FALSE (i < n_to_dequeue))
+    {
+      session_fifo_event_t *partially_read =
+       smm->evts_partially_read[my_thread_index];
+      vec_add (partially_read, &my_fifo_events[i], n_to_dequeue - i);
+      vec_free (my_fifo_events);
+      smm->fifo_events[my_thread_index] = partially_read;
+      smm->evts_partially_read[my_thread_index] = 0;
+    }
+  else
+    {
+      vec_free (smm->fifo_events[my_thread_index]);
+      smm->fifo_events[my_thread_index] =
+       smm->evts_partially_read[my_thread_index];
+      smm->evts_partially_read[my_thread_index] = 0;
+    }
+
+  vlib_node_increment_counter (vm, session_queue_node.index,
+                              SESSION_QUEUE_ERROR_TX, n_tx_packets);
+
+  return n_tx_packets;
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (session_queue_node) =
+{
+  .function = session_queue_node_fn,
+  .name = "session-queue",
+  .format_trace = format_session_queue_trace,
+  .type = VLIB_NODE_TYPE_INPUT,
+  .n_errors = ARRAY_LEN (session_queue_error_strings),
+  .error_strings = session_queue_error_strings,
+  .n_next_nodes = SESSION_QUEUE_N_NEXT,
+  /* .state = VLIB_NODE_STATE_DISABLED, enable on-demand? */
+  /* edit / add dispositions here */
+  .next_nodes =
+  {
+      [SESSION_QUEUE_NEXT_DROP] = "error-drop",
+      [SESSION_QUEUE_NEXT_IP4_LOOKUP] = "ip4-lookup",
+      [SESSION_QUEUE_NEXT_IP6_LOOKUP] = "ip6-lookup",
+      [SESSION_QUEUE_NEXT_TCP_IP4_OUTPUT] = "tcp4-output",
+      [SESSION_QUEUE_NEXT_TCP_IP6_OUTPUT] = "tcp6-output",
+  },
+};
+/* *INDENT-ON* */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/session.api b/src/vnet/session/session.api
new file mode 100644 (file)
index 0000000..a7b28c1
--- /dev/null
@@ -0,0 +1,429 @@
+/*
+ * Copyright (c) 2015-2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+ /** \brief Bind to a given URI
+    @param client_index - opaque cookie to identify the sender
+    @param context - sender context, to match reply w/ request
+    @param accept_cookie - sender accept cookie, to identify this bind flavor
+    @param uri - a URI, e.g. "tcp://0.0.0.0/0/80" [ipv4]
+                 "tcp://::/0/80" [ipv6] etc.
+    @param options - socket options, fifo sizes, etc.
+*/
+define bind_uri {
+  u32 client_index;
+  u32 context;
+  u32 accept_cookie;
+  u32 initial_segment_size;
+  u8 uri[128];
+  u64 options[16];
+};
+
+/** \brief Unbind a given URI
+    @param client_index - opaque cookie to identify the sender
+    @param context - sender context, to match reply w/ request
+    @param uri - a URI, e.g. "tcp://0.0.0.0/0/80" [ipv4]
+                 "tcp://::/0/80" [ipv6], etc.
+    @param options - socket options, fifo sizes, etc.
+*/
+define unbind_uri {
+  u32 client_index;
+  u32 context;
+  u8 uri[128];
+};
+
+/** \brief Connect to a given URI
+    @param client_index - opaque cookie to identify the sender
+    @param context - sender context, to match reply w/ request
+    @param accept_cookie - sender accept cookie, to identify this bind flavor
+    @param uri - a URI, e.g. "tcp4://0.0.0.0/0/80"
+                 "tcp6://::/0/80" [ipv6], etc.
+    @param options - socket options, fifo sizes, etc.
+*/
+define connect_uri {
+  u32 client_index;
+  u32 context;
+  u8 uri[128];
+  u64 client_queue_address;
+  u64 options[16];
+};
+
+/** \brief Bind reply
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+    @param event_queue_address - vpp event queue address or 0 if this 
+                                 connection shouldn't send events
+    @param segment_name_length - length of segment name 
+    @param segment_name - name of segment client needs to attach to
+*/
+define bind_uri_reply {
+    u32 context;
+    i32 retval;
+    u64 server_event_queue_address;
+    u8 segment_name_length;
+    u32 segment_size;
+    u8 segment_name[128];
+};
+
+/** \brief unbind reply
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+*/
+define unbind_uri_reply {
+    u32 context;
+    i32 retval;
+};
+
+/** \brief vpp->client, connect reply
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+    @param server_rx_fifo - rx (vpp -> vpp-client) fifo address 
+    @param server_tx_fifo - tx (vpp-client -> vpp) fifo address 
+    @param session_index - session index;
+    @param session_thread_index - session thread index
+    @param session_type - session thread type
+    @param vpp_event_queue_address - vpp's event queue address
+    @param client_event_queue_address - client's event queue address
+    @param segment_name_length - non-zero if the client needs to attach to 
+                                 the fifo segment
+    @param segment_name - set if the client needs to attach to the segment
+*/
+define connect_uri_reply {
+  u32 context;
+  i32 retval;
+  u64 server_rx_fifo;
+  u64 server_tx_fifo;
+  u32 session_index;
+  u32 session_thread_index;
+  u8 session_type;
+  u64 client_event_queue_address;
+  u64 vpp_event_queue_address;
+  u32 segment_size;
+  u8 segment_name_length;
+  u8 segment_name[128];
+};
+
+/** \brief vpp->client, please map an additional shared memory segment
+    @param context - sender context, to match reply w/ request
+    @param segment_name - 
+*/
+define map_another_segment {
+    u32 client_index;
+    u32 context;
+    u32 segment_size;
+    u8 segment_name[128];
+};
+
+/** \brief client->vpp
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+*/
+define map_another_segment_reply {
+    u32 context;
+    i32 retval;
+};
+
+/** \brief vpp->client, accept this session
+    @param context - sender context, to match reply w/ request
+    @param accept_cookie - tells client which bind flavor just occurred
+    @param rx_fifo_address - rx (vpp -> vpp-client) fifo address 
+    @param tx_fifo_address - tx (vpp-client -> vpp) fifo address 
+    @param session_index - index of new session
+    @param session_thread_index - thread index of new session
+    @param vpp_event_queue_address - vpp's event queue address
+    @param session_type - type of session
+    
+*/
+define accept_session {
+  u32 client_index;
+  u32 context;
+  u32 accept_cookie;
+  u64 server_rx_fifo;
+  u64 server_tx_fifo;
+  u32 session_index;
+  u32 session_thread_index;
+  u64 vpp_event_queue_address;
+  u8 session_type;
+};
+
+/** \brief client->vpp, reply to an accept message
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+    @param session_index - session index from accept_session / connect_reply
+    @param session_thread_index - thread index from accept_session /
+                                  connect_reply
+*/
+define accept_session_reply {
+  u32 context;
+  i32 retval;
+  u8 session_type;
+  u8 session_thread_index;
+  u32 session_index;
+};
+
+/** \brief bidirectional disconnect API
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param context - sender context, to match reply w/ request
+    @param session_index - cookie #1 from accept_session / connect_reply
+    @param session_thread_index - cookie #2
+*/
+define disconnect_session {
+  u32 client_index;
+  u32 context;
+  u32 session_index;
+  u32 session_thread_index;
+};
+
+/** \brief bidirectional disconnect reply API
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+    @param session_index - session index from accept_session / connect_reply
+    @param session_thread_index - thread index from accept_session /
+                                  connect_reply
+*/
+define disconnect_session_reply {
+  u32 client_index;
+  u32 context;
+  i32 retval;
+  u32 session_index;
+  u32 session_thread_index;
+};
+
+/** \brief vpp->client reset session API
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param context - sender context, to match reply w/ request
+    @param session_index - session index from accept_session / connect_reply
+    @param session_thread_index - thread index from accept_session /
+                                  connect_reply
+*/
+define reset_session {
+  u32 client_index;
+  u32 context;
+  u32 session_index;
+  u32 session_thread_index;
+};
+
+/** \brief client->vpp reset session reply
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+    @param session_index - session index from accept_session / connect_reply
+    @param session_thread_index - thread index from accept_session /
+                                  connect_reply
+*/
+define reset_session_reply {
+  u32 client_index;
+  u32 context;
+  i32 retval;
+  u32 session_index;
+  u32 session_thread_index;
+};
+
+/** \brief Bind to an ip:port pair for a given transport protocol
+    @param client_index - opaque cookie to identify the sender
+    @param context - sender context, to match reply w/ request
+    @param vrf - bind namespace
+    @param is_ip4 - flag that is 1 if ip address family is IPv4
+    @param ip - ip address
+    @param port - port 
+    @param proto - protocol 0 - TCP 1 - UDP
+    @param options - socket options, fifo sizes, etc.
+*/
+define bind_sock {
+  u32 client_index;
+  u32 context;
+  u32 vrf;
+  u8 is_ip4;
+  u8 ip[16];
+  u16 port;
+  u8 proto;
+  u64 options[16];
+};
+
+/** \brief Unbind 
+    @param client_index - opaque cookie to identify the sender
+    @param context - sender context, to match reply w/ request
+    @param handle - bind handle obtained from bind reply
+*/
+define unbind_sock {
+  u32 client_index;
+  u32 context;
+  u64 handle;
+};
+
+/** \brief Connect to a remote peer
+    @param client_index - opaque cookie to identify the sender
+    @param context - sender context, to match reply w/ request
+    @param vrf - connection namespace
+    @param is_ip4 - flag that is 1 if ip address family is IPv4
+    @param ip - ip address
+    @param port - port 
+    @param proto - protocol 0 - TCP 1 - UDP
+    @param client_queue_address - client's API queue address. Non-zero when 
+                                  used to perform redirects
+    @param options - socket options, fifo sizes, etc.
+*/
+define connect_sock {
+  u32 client_index;
+  u32 context;
+  u32 vrf;
+  u8 is_ip4;
+  u8 ip[16];
+  u16 port;
+  u8 proto;
+  u64 client_queue_address;
+  u64 options[16];
+};
+
+/** \brief Bind reply
+    @param context - sender context, to match reply w/ request
+    @param handle - bind handle
+    @param retval - return code for the request
+    @param event_queue_address - vpp event queue address or 0 if this 
+                                 connection shouldn't send events
+    @param segment_name_length - length of segment name 
+    @param segment_name - name of segment client needs to attach to
+*/
+define bind_sock_reply {
+  u32 context;
+  u64 handle;
+  i32 retval;
+  u64 server_event_queue_address;
+  u32 segment_size;
+  u8 segment_name_length;
+  u8 segment_name[128];
+};
+
+/** \brief unbind reply
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+*/
+define unbind_sock_reply {
+  u32 context;
+  i32 retval;
+};
+
+/** \brief vpp/server->client, connect reply
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+    @param handle - connection handle
+    @param server_rx_fifo - rx (vpp -> vpp-client) fifo address 
+    @param server_tx_fifo - tx (vpp-client -> vpp) fifo address 
+    @param vpp_event_queue_address - vpp's event queue address
+    @param client_event_queue_address - client's event queue address
+    @param segment_name_length - non-zero if the client needs to attach to 
+                                 the fifo segment
+    @param segment_name - set if the client needs to attach to the segment
+*/
+define connect_sock_reply {
+  u32 context;
+  i32 retval;
+  u64 handle;
+  u64 server_rx_fifo;
+  u64 server_tx_fifo;
+  u64 client_event_queue_address;
+  u64 vpp_event_queue_address;
+  u32 segment_size;
+  u8 segment_name_length;
+  u8 segment_name[128];
+};
+
+/** \brief bidirectional disconnect API
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param context - sender context, to match reply w/ request
+    @param handle - session handle obtained through accept/connect
+*/
+define disconnect_sock {
+  u32 client_index;
+  u32 context;
+  u64 handle;
+};
+
+/** \brief bidirectional disconnect reply API
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param client_context - sender context, to match reply w/ request
+    @param handle - session handle obtained through accept/connect
+*/
+define disconnect_sock_reply {
+  u32 client_index;
+  u32 context;
+  i32 retval;
+  u64 handle;
+};
+
+/** \brief vpp->client, accept this session
+    @param context - sender context, to match reply w/ request
+    @param accept_cookie - tells client which bind flavor just occurred
+    @param handle - session handle obtained through accept/connect
+    @param rx_fifo_address - rx (vpp -> vpp-client) fifo address 
+    @param tx_fifo_address - tx (vpp-client -> vpp) fifo address 
+    @param vpp_event_queue_address - vpp's event queue address
+*/
+define accept_sock {
+  u32 client_index;
+  u32 context;
+  u32 accept_cookie;
+  u64 handle;
+  u64 server_rx_fifo;
+  u64 server_tx_fifo;
+  u64 vpp_event_queue_address;
+};
+
+/** \brief client->vpp, reply to an accept message
+    @param context - sender context, to match reply w/ request
+    @param retval - return code for the request
+    @param handle - session handle obtained through accept/connect
+*/
+define accept_sock_reply {
+  u32 context;
+  i32 retval;
+  u64 handle;
+};
+
+/** \brief vpp->client reset session API
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param context - sender context, to match reply w/ request
+    @param handle - session handle obtained through accept/connect
+*/
+define reset_sock {
+  u32 client_index;
+  u32 context;
+  u64 handle;
+};
+
+/** \brief client->vpp reset session reply
+    @param client_index - opaque cookie to identify the sender
+                          client to vpp direction only
+    @param context - sender context, to match reply w/ request
+    @param handle - session handle obtained through accept/connect
+*/
+define reset_sock_reply {
+  u32 client_index;
+  u32 context;
+  i32 retval;
+  u64 handle;
+};
+/*
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
\ No newline at end of file
diff --git a/src/vnet/session/session.c b/src/vnet/session/session.c
new file mode 100644 (file)
index 0000000..539da61
--- /dev/null
@@ -0,0 +1,1286 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * @file
+ * @brief Session and session manager
+ */
+
+#include <vnet/session/session.h>
+#include <vlibmemory/api.h>
+#include <vnet/dpo/load_balance.h>
+#include <vnet/fib/ip4_fib.h>
+#include <vnet/session/application.h>
+
+/**
+ * Per-type vector of transport protocol virtual function tables
+ */
+static transport_proto_vft_t *tp_vfts;
+
+session_manager_main_t session_manager_main;
+
+/*
+ * Session lookup key; (src-ip, dst-ip, src-port, dst-port, session-type)
+ * Value: (owner thread index << 32 | session_index);
+ */
+static void
+stream_session_table_add_for_tc (u8 sst, transport_connection_t * tc,
+                                u64 value)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  session_kv4_t kv4;
+  session_kv6_t kv6;
+
+  switch (sst)
+    {
+    case SESSION_TYPE_IP4_UDP:
+    case SESSION_TYPE_IP4_TCP:
+      make_v4_ss_kv_from_tc (&kv4, tc);
+      kv4.value = value;
+      clib_bihash_add_del_16_8 (&smm->v4_session_hash, &kv4, 1 /* is_add */ );
+      break;
+    case SESSION_TYPE_IP6_UDP:
+    case SESSION_TYPE_IP6_TCP:
+      make_v6_ss_kv_from_tc (&kv6, tc);
+      kv6.value = value;
+      clib_bihash_add_del_48_8 (&smm->v6_session_hash, &kv6, 1 /* is_add */ );
+      break;
+    default:
+      clib_warning ("Session type not supported");
+      ASSERT (0);
+    }
+}
+
+void
+stream_session_table_add (session_manager_main_t * smm, stream_session_t * s,
+                         u64 value)
+{
+  transport_connection_t *tc;
+
+  tc = tp_vfts[s->session_type].get_connection (s->connection_index,
+                                               s->thread_index);
+  stream_session_table_add_for_tc (s->session_type, tc, value);
+}
+
+static void
+stream_session_half_open_table_add (u8 sst, transport_connection_t * tc,
+                                   u64 value)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  session_kv4_t kv4;
+  session_kv6_t kv6;
+
+  switch (sst)
+    {
+    case SESSION_TYPE_IP4_UDP:
+    case SESSION_TYPE_IP4_TCP:
+      make_v4_ss_kv_from_tc (&kv4, tc);
+      kv4.value = value;
+      clib_bihash_add_del_16_8 (&smm->v4_half_open_hash, &kv4,
+                               1 /* is_add */ );
+      break;
+    case SESSION_TYPE_IP6_UDP:
+    case SESSION_TYPE_IP6_TCP:
+      make_v6_ss_kv_from_tc (&kv6, tc);
+      kv6.value = value;
+      clib_bihash_add_del_48_8 (&smm->v6_half_open_hash, &kv6,
+                               1 /* is_add */ );
+      break;
+    default:
+      clib_warning ("Session type not supported");
+      ASSERT (0);
+    }
+}
+
+static int
+stream_session_table_del_for_tc (session_manager_main_t * smm, u8 sst,
+                                transport_connection_t * tc)
+{
+  session_kv4_t kv4;
+  session_kv6_t kv6;
+
+  switch (sst)
+    {
+    case SESSION_TYPE_IP4_UDP:
+    case SESSION_TYPE_IP4_TCP:
+      make_v4_ss_kv_from_tc (&kv4, tc);
+      return clib_bihash_add_del_16_8 (&smm->v4_session_hash, &kv4,
+                                      0 /* is_add */ );
+      break;
+    case SESSION_TYPE_IP6_UDP:
+    case SESSION_TYPE_IP6_TCP:
+      make_v6_ss_kv_from_tc (&kv6, tc);
+      return clib_bihash_add_del_48_8 (&smm->v6_session_hash, &kv6,
+                                      0 /* is_add */ );
+      break;
+    default:
+      clib_warning ("Session type not supported");
+      ASSERT (0);
+    }
+
+  return 0;
+}
+
+static int
+stream_session_table_del (session_manager_main_t * smm, stream_session_t * s)
+{
+  transport_connection_t *ts;
+
+  ts = tp_vfts[s->session_type].get_connection (s->connection_index,
+                                               s->thread_index);
+  return stream_session_table_del_for_tc (smm, s->session_type, ts);
+}
+
+static void
+stream_session_half_open_table_del (session_manager_main_t * smm, u8 sst,
+                                   transport_connection_t * tc)
+{
+  session_kv4_t kv4;
+  session_kv6_t kv6;
+
+  switch (sst)
+    {
+    case SESSION_TYPE_IP4_UDP:
+    case SESSION_TYPE_IP4_TCP:
+      make_v4_ss_kv_from_tc (&kv4, tc);
+      clib_bihash_add_del_16_8 (&smm->v4_half_open_hash, &kv4,
+                               0 /* is_add */ );
+      break;
+    case SESSION_TYPE_IP6_UDP:
+    case SESSION_TYPE_IP6_TCP:
+      make_v6_ss_kv_from_tc (&kv6, tc);
+      clib_bihash_add_del_48_8 (&smm->v6_half_open_hash, &kv6,
+                               0 /* is_add */ );
+      break;
+    default:
+      clib_warning ("Session type not supported");
+      ASSERT (0);
+    }
+}
+
+stream_session_t *
+stream_session_lookup_listener4 (ip4_address_t * lcl, u16 lcl_port, u8 proto)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  session_kv4_t kv4;
+  int rv;
+
+  make_v4_listener_kv (&kv4, lcl, lcl_port, proto);
+  rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
+  if (rv == 0)
+    return pool_elt_at_index (smm->listen_sessions[proto], (u32) kv4.value);
+
+  /* Zero out the lcl ip */
+  kv4.key[0] = 0;
+  rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
+  if (rv == 0)
+    return pool_elt_at_index (smm->listen_sessions[proto], kv4.value);
+
+  return 0;
+}
+
+/** Looks up a session based on the 5-tuple passed as argument.
+ *
+ * First it tries to find an established session, if this fails, it tries
+ * finding a listener session if this fails, it tries a lookup with a
+ * wildcarded local source (listener bound to all interfaces)
+ */
+stream_session_t *
+stream_session_lookup4 (ip4_address_t * lcl, ip4_address_t * rmt,
+                       u16 lcl_port, u16 rmt_port, u8 proto,
+                       u32 my_thread_index)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  session_kv4_t kv4;
+  int rv;
+
+  /* Lookup session amongst established ones */
+  make_v4_ss_kv (&kv4, lcl, rmt, lcl_port, rmt_port, proto);
+  rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
+  if (rv == 0)
+    return stream_session_get_tsi (kv4.value, my_thread_index);
+
+  /* If nothing is found, check if any listener is available */
+  return stream_session_lookup_listener4 (lcl, lcl_port, proto);
+}
+
+stream_session_t *
+stream_session_lookup_listener6 (ip6_address_t * lcl, u16 lcl_port, u8 proto)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  session_kv6_t kv6;
+  int rv;
+
+  make_v6_listener_kv (&kv6, lcl, lcl_port, proto);
+  rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
+  if (rv == 0)
+    return pool_elt_at_index (smm->listen_sessions[proto], kv6.value);
+
+  /* Zero out the lcl ip */
+  kv6.key[0] = kv6.key[1] = 0;
+  rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
+  if (rv == 0)
+    return pool_elt_at_index (smm->listen_sessions[proto], kv6.value);
+
+  return 0;
+}
+
+/* Looks up a session based on the 5-tuple passed as argument.
+ * First it tries to find an established session, if this fails, it tries
+ * finding a listener session if this fails, it tries a lookup with a
+ * wildcarded local source (listener bound to all interfaces) */
+stream_session_t *
+stream_session_lookup6 (ip6_address_t * lcl, ip6_address_t * rmt,
+                       u16 lcl_port, u16 rmt_port, u8 proto,
+                       u32 my_thread_index)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  session_kv6_t kv6;
+  int rv;
+
+  make_v6_ss_kv (&kv6, lcl, rmt, lcl_port, rmt_port, proto);
+  rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
+  if (rv == 0)
+    return stream_session_get_tsi (kv6.value, my_thread_index);
+
+  /* If nothing is found, check if any listener is available */
+  return stream_session_lookup_listener6 (lcl, lcl_port, proto);
+}
+
+stream_session_t *
+stream_session_lookup_listener (ip46_address_t * lcl, u16 lcl_port, u8 proto)
+{
+  switch (proto)
+    {
+    case SESSION_TYPE_IP4_UDP:
+    case SESSION_TYPE_IP4_TCP:
+      return stream_session_lookup_listener4 (&lcl->ip4, lcl_port, proto);
+      break;
+    case SESSION_TYPE_IP6_UDP:
+    case SESSION_TYPE_IP6_TCP:
+      return stream_session_lookup_listener6 (&lcl->ip6, lcl_port, proto);
+      break;
+    }
+  return 0;
+}
+
+static u64
+stream_session_half_open_lookup (session_manager_main_t * smm,
+                                ip46_address_t * lcl, ip46_address_t * rmt,
+                                u16 lcl_port, u16 rmt_port, u8 proto)
+{
+  session_kv4_t kv4;
+  session_kv6_t kv6;
+  int rv;
+
+  switch (proto)
+    {
+    case SESSION_TYPE_IP4_UDP:
+    case SESSION_TYPE_IP4_TCP:
+      make_v4_ss_kv (&kv4, &lcl->ip4, &rmt->ip4, lcl_port, rmt_port, proto);
+      rv = clib_bihash_search_inline_16_8 (&smm->v4_half_open_hash, &kv4);
+
+      if (rv == 0)
+       return kv4.value;
+
+      return (u64) ~ 0;
+      break;
+    case SESSION_TYPE_IP6_UDP:
+    case SESSION_TYPE_IP6_TCP:
+      make_v6_ss_kv (&kv6, &lcl->ip6, &rmt->ip6, lcl_port, rmt_port, proto);
+      rv = clib_bihash_search_inline_48_8 (&smm->v6_half_open_hash, &kv6);
+
+      if (rv == 0)
+       return kv6.value;
+
+      return (u64) ~ 0;
+      break;
+    }
+  return 0;
+}
+
+transport_connection_t *
+stream_session_lookup_transport4 (session_manager_main_t * smm,
+                                 ip4_address_t * lcl, ip4_address_t * rmt,
+                                 u16 lcl_port, u16 rmt_port, u8 proto,
+                                 u32 my_thread_index)
+{
+  session_kv4_t kv4;
+  stream_session_t *s;
+  int rv;
+
+  /* Lookup session amongst established ones */
+  make_v4_ss_kv (&kv4, lcl, rmt, lcl_port, rmt_port, proto);
+  rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
+  if (rv == 0)
+    {
+      s = stream_session_get_tsi (kv4.value, my_thread_index);
+
+      return tp_vfts[s->session_type].get_connection (s->connection_index,
+                                                     my_thread_index);
+    }
+
+  /* If nothing is found, check if any listener is available */
+  s = stream_session_lookup_listener4 (lcl, lcl_port, proto);
+  if (s)
+    return tp_vfts[s->session_type].get_listener (s->connection_index);
+
+  /* Finally, try half-open connections */
+  rv = clib_bihash_search_inline_16_8 (&smm->v4_half_open_hash, &kv4);
+  if (rv == 0)
+    return tp_vfts[proto].get_half_open (kv4.value & 0xFFFFFFFF);
+
+  return 0;
+}
+
+transport_connection_t *
+stream_session_lookup_transport6 (session_manager_main_t * smm,
+                                 ip6_address_t * lcl, ip6_address_t * rmt,
+                                 u16 lcl_port, u16 rmt_port, u8 proto,
+                                 u32 my_thread_index)
+{
+  stream_session_t *s;
+  session_kv6_t kv6;
+  int rv;
+
+  make_v6_ss_kv (&kv6, lcl, rmt, lcl_port, rmt_port, proto);
+  rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
+  if (rv == 0)
+    {
+      s = stream_session_get_tsi (kv6.value, my_thread_index);
+
+      return tp_vfts[s->session_type].get_connection (s->connection_index,
+                                                     my_thread_index);
+    }
+
+  /* If nothing is found, check if any listener is available */
+  s = stream_session_lookup_listener6 (lcl, lcl_port, proto);
+  if (s)
+    return tp_vfts[s->session_type].get_listener (s->connection_index);
+
+  /* Finally, try half-open connections */
+  rv = clib_bihash_search_inline_48_8 (&smm->v6_half_open_hash, &kv6);
+  if (rv == 0)
+    return tp_vfts[s->session_type].get_half_open (kv6.value & 0xFFFFFFFF);
+
+  return 0;
+}
+
+/**
+ * Allocate vpp event queue (once) per worker thread
+ */
+void
+vpp_session_event_queue_allocate (session_manager_main_t * smm,
+                                 u32 thread_index)
+{
+  api_main_t *am = &api_main;
+  void *oldheap;
+
+  if (smm->vpp_event_queues[thread_index] == 0)
+    {
+      /* Allocate event fifo in the /vpe-api shared-memory segment */
+      oldheap = svm_push_data_heap (am->vlib_rp);
+
+      smm->vpp_event_queues[thread_index] =
+       unix_shared_memory_queue_init (2048 /* nels $$$$ config */ ,
+                                      sizeof (session_fifo_event_t),
+                                      0 /* consumer pid */ ,
+                                      0
+                                      /* (do not) send signal when queue non-empty */
+       );
+
+      svm_pop_heap (oldheap);
+    }
+}
+
+void
+session_manager_get_segment_info (u32 index, u8 ** name, u32 * size)
+{
+  svm_fifo_segment_private_t *s;
+  s = svm_fifo_get_segment (index);
+  *name = s->h->segment_name;
+  *size = s->ssvm.ssvm_size;
+}
+
+always_inline int
+session_manager_add_segment_i (session_manager_main_t * smm,
+                              session_manager_t * sm,
+                              u32 segment_size, u8 * segment_name)
+{
+  svm_fifo_segment_create_args_t _ca, *ca = &_ca;
+  int rv;
+
+  memset (ca, 0, sizeof (*ca));
+
+  ca->segment_name = (char *) segment_name;
+  ca->segment_size = segment_size;
+
+  rv = svm_fifo_segment_create (ca);
+  if (rv)
+    {
+      clib_warning ("svm_fifo_segment_create ('%s', %d) failed",
+                   ca->segment_name, ca->segment_size);
+      vec_free (segment_name);
+      return -1;
+    }
+
+  vec_add1 (sm->segment_indices, ca->new_segment_index);
+
+  return 0;
+}
+
+static int
+session_manager_add_segment (session_manager_main_t * smm,
+                            session_manager_t * sm)
+{
+  u8 *segment_name;
+  svm_fifo_segment_create_args_t _ca, *ca = &_ca;
+  u32 add_segment_size;
+  u32 default_segment_size = 128 << 10;
+
+  memset (ca, 0, sizeof (*ca));
+  segment_name = format (0, "%d-%d%c", getpid (),
+                        smm->unique_segment_name_counter++, 0);
+  add_segment_size =
+    sm->add_segment_size ? sm->add_segment_size : default_segment_size;
+
+  return session_manager_add_segment_i (smm, sm, add_segment_size,
+                                       segment_name);
+}
+
+int
+session_manager_add_first_segment (session_manager_main_t * smm,
+                                  session_manager_t * sm, u32 segment_size,
+                                  u8 ** segment_name)
+{
+  svm_fifo_segment_create_args_t _ca, *ca = &_ca;
+  memset (ca, 0, sizeof (*ca));
+  *segment_name = format (0, "%d-%d%c", getpid (),
+                         smm->unique_segment_name_counter++, 0);
+  return session_manager_add_segment_i (smm, sm, segment_size, *segment_name);
+}
+
+void
+session_manager_del (session_manager_main_t * smm, session_manager_t * sm)
+{
+  u32 *deleted_sessions = 0;
+  u32 *deleted_thread_indices = 0;
+  int i, j;
+
+  /* Across all fifo segments used by the server */
+  for (j = 0; j < vec_len (sm->segment_indices); j++)
+    {
+      svm_fifo_segment_private_t *fifo_segment;
+      svm_fifo_t **fifos;
+      /* Vector of fifos allocated in the segment */
+      fifo_segment = svm_fifo_get_segment (sm->segment_indices[j]);
+      fifos = (svm_fifo_t **) fifo_segment->h->fifos;
+
+      /*
+       * Remove any residual sessions from the session lookup table
+       * Don't bother deleting the individual fifos, we're going to
+       * throw away the fifo segment in a minute.
+       */
+      for (i = 0; i < vec_len (fifos); i++)
+       {
+         svm_fifo_t *fifo;
+         u32 session_index, thread_index;
+         stream_session_t *session;
+
+         fifo = fifos[i];
+         session_index = fifo->server_session_index;
+         thread_index = fifo->server_thread_index;
+
+         session = pool_elt_at_index (smm->sessions[thread_index],
+                                      session_index);
+
+         /* Add to the deleted_sessions vector (once!) */
+         if (!session->is_deleted)
+           {
+             session->is_deleted = 1;
+             vec_add1 (deleted_sessions,
+                       session - smm->sessions[thread_index]);
+             vec_add1 (deleted_thread_indices, thread_index);
+           }
+       }
+
+      for (i = 0; i < vec_len (deleted_sessions); i++)
+       {
+         stream_session_t *session;
+
+         session =
+           pool_elt_at_index (smm->sessions[deleted_thread_indices[i]],
+                              deleted_sessions[i]);
+
+         /* Instead of directly removing the session call disconnect */
+         stream_session_disconnect (session);
+
+         /*
+            stream_session_table_del (smm, session);
+            pool_put(smm->sessions[deleted_thread_indices[i]], session);
+          */
+       }
+
+      vec_reset_length (deleted_sessions);
+      vec_reset_length (deleted_thread_indices);
+
+      /* Instead of removing the segment, test when removing the session if
+       * the segment can be removed
+       */
+      /* svm_fifo_segment_delete (fifo_segment); */
+    }
+
+  vec_free (deleted_sessions);
+  vec_free (deleted_thread_indices);
+}
+
+int
+session_manager_allocate_session_fifos (session_manager_main_t * smm,
+                                       session_manager_t * sm,
+                                       svm_fifo_t ** server_rx_fifo,
+                                       svm_fifo_t ** server_tx_fifo,
+                                       u32 * fifo_segment_index,
+                                       u8 * added_a_segment)
+{
+  svm_fifo_segment_private_t *fifo_segment;
+  u32 fifo_size, default_fifo_size = 8192 /* TODO config */ ;
+  int i;
+
+  *added_a_segment = 0;
+
+  /* Allocate svm fifos */
+  ASSERT (vec_len (sm->segment_indices));
+
+again:
+  for (i = 0; i < vec_len (sm->segment_indices); i++)
+    {
+      *fifo_segment_index = sm->segment_indices[i];
+      fifo_segment = svm_fifo_get_segment (*fifo_segment_index);
+
+      fifo_size = sm->rx_fifo_size;
+      fifo_size = (fifo_size == 0) ? default_fifo_size : fifo_size;
+      *server_rx_fifo = svm_fifo_segment_alloc_fifo (fifo_segment, fifo_size);
+
+      fifo_size = sm->tx_fifo_size;
+      fifo_size = (fifo_size == 0) ? default_fifo_size : fifo_size;
+      *server_tx_fifo = svm_fifo_segment_alloc_fifo (fifo_segment, fifo_size);
+
+      if (*server_rx_fifo == 0)
+       {
+         /* This would be very odd, but handle it... */
+         if (*server_tx_fifo != 0)
+           {
+             svm_fifo_segment_free_fifo (fifo_segment, *server_tx_fifo);
+             *server_tx_fifo = 0;
+           }
+         continue;
+       }
+      if (*server_tx_fifo == 0)
+       {
+         if (*server_rx_fifo != 0)
+           {
+             svm_fifo_segment_free_fifo (fifo_segment, *server_rx_fifo);
+             *server_rx_fifo = 0;
+           }
+         continue;
+       }
+      break;
+    }
+
+  /* See if we're supposed to create another segment */
+  if (*server_rx_fifo == 0)
+    {
+      if (sm->add_segment)
+       {
+         if (*added_a_segment)
+           {
+             clib_warning ("added a segment, still cant allocate a fifo");
+             return SESSION_ERROR_NEW_SEG_NO_SPACE;
+           }
+
+         if (session_manager_add_segment (smm, sm))
+           return VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
+
+         *added_a_segment = 1;
+         goto again;
+       }
+      else
+       return SESSION_ERROR_NO_SPACE;
+    }
+  return 0;
+}
+
+int
+stream_session_create_i (session_manager_main_t * smm, application_t * app,
+                        transport_connection_t * tc,
+                        stream_session_t ** ret_s)
+{
+  int rv;
+  svm_fifo_t *server_rx_fifo = 0, *server_tx_fifo = 0;
+  u32 fifo_segment_index;
+  u32 pool_index, seg_size;
+  stream_session_t *s;
+  u64 value;
+  u32 thread_index = tc->thread_index;
+  session_manager_t *sm;
+  u8 segment_added;
+  u8 *seg_name;
+
+  sm = session_manager_get (app->session_manager_index);
+
+  /* Check the API queue */
+  if (app->mode == APP_SERVER && application_api_queue_is_full (app))
+    return SESSION_ERROR_API_QUEUE_FULL;
+
+  if ((rv = session_manager_allocate_session_fifos (smm, sm, &server_rx_fifo,
+                                                   &server_tx_fifo,
+                                                   &fifo_segment_index,
+                                                   &segment_added)))
+    return rv;
+
+  if (segment_added && app->mode == APP_SERVER)
+    {
+      /* Send an API message to the external server, to map new segment */
+      ASSERT (app->cb_fns.add_segment_callback);
+
+      session_manager_get_segment_info (fifo_segment_index, &seg_name,
+                                       &seg_size);
+      if (app->cb_fns.add_segment_callback (app->api_client_index, seg_name,
+                                           seg_size))
+       return VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
+    }
+
+  /* Create the session */
+  pool_get (smm->sessions[thread_index], s);
+  memset (s, 0, sizeof (*s));
+
+  /* Initialize backpointers */
+  pool_index = s - smm->sessions[thread_index];
+  server_rx_fifo->server_session_index = pool_index;
+  server_rx_fifo->server_thread_index = thread_index;
+
+  server_tx_fifo->server_session_index = pool_index;
+  server_tx_fifo->server_thread_index = thread_index;
+
+  s->server_rx_fifo = server_rx_fifo;
+  s->server_tx_fifo = server_tx_fifo;
+
+  /* Initialize state machine, such as it is... */
+  s->session_type = app->session_type;
+  s->session_state = SESSION_STATE_CONNECTING;
+  s->app_index = application_get_index (app);
+  s->server_segment_index = fifo_segment_index;
+  s->thread_index = thread_index;
+  s->session_index = pool_index;
+
+  /* Attach transport to session */
+  s->connection_index = tc->c_index;
+
+  /* Attach session to transport */
+  tc->s_index = s->session_index;
+
+  /* Add to the main lookup table */
+  value = (((u64) thread_index) << 32) | (u64) s->session_index;
+  stream_session_table_add_for_tc (app->session_type, tc, value);
+
+  *ret_s = s;
+
+  return 0;
+}
+
+/*
+ * Enqueue data for delivery to session peer. Does not notify peer of enqueue
+ * event but on request can queue notification events for later delivery by
+ * calling stream_server_flush_enqueue_events().
+ *
+ * @param tc Transport connection which is to be enqueued data
+ * @param data Data to be enqueued
+ * @param len Length of data to be enqueued
+ * @param queue_event Flag to indicate if peer is to be notified or if event
+ *                    is to be queued. The former is useful when more data is
+ *                    enqueued and only one event is to be generated.
+ * @return Number of bytes enqueued or a negative value if enqueueing failed.
+ */
+int
+stream_session_enqueue_data (transport_connection_t * tc, u8 * data, u16 len,
+                            u8 queue_event)
+{
+  stream_session_t *s;
+  int enqueued;
+
+  s = stream_session_get (tc->s_index, tc->thread_index);
+
+  /* Make sure there's enough space left. We might've filled the pipes */
+  if (PREDICT_FALSE (len > svm_fifo_max_enqueue (s->server_rx_fifo)))
+    return -1;
+
+  enqueued = svm_fifo_enqueue_nowait (s->server_rx_fifo, s->pid, len, data);
+
+  if (queue_event)
+    {
+      /* Queue RX event on this fifo. Eventually these will need to be flushed
+       * by calling stream_server_flush_enqueue_events () */
+      session_manager_main_t *smm = vnet_get_session_manager_main ();
+      u32 thread_index = s->thread_index;
+      u32 my_enqueue_epoch = smm->current_enqueue_epoch[thread_index];
+
+      if (s->enqueue_epoch != my_enqueue_epoch)
+       {
+         s->enqueue_epoch = my_enqueue_epoch;
+         vec_add1 (smm->session_indices_to_enqueue_by_thread[thread_index],
+                   s - smm->sessions[thread_index]);
+       }
+    }
+
+  return enqueued;
+}
+
+/** Check if we have space in rx fifo to push more bytes */
+u8
+stream_session_no_space (transport_connection_t * tc, u32 thread_index,
+                        u16 data_len)
+{
+  stream_session_t *s = stream_session_get (tc->c_index, thread_index);
+
+  if (PREDICT_FALSE (s->session_state != SESSION_STATE_READY))
+    return 1;
+
+  if (data_len > svm_fifo_max_enqueue (s->server_rx_fifo))
+    return 1;
+
+  return 0;
+}
+
+u32
+stream_session_peek_bytes (transport_connection_t * tc, u8 * buffer,
+                          u32 offset, u32 max_bytes)
+{
+  stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
+  return svm_fifo_peek (s->server_tx_fifo, s->pid, offset, max_bytes, buffer);
+}
+
+u32
+stream_session_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
+{
+  stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
+  return svm_fifo_dequeue_drop (s->server_tx_fifo, s->pid, max_bytes);
+}
+
+/**
+ * Notify session peer that new data has been enqueued.
+ *
+ * @param s Stream session for which the event is to be generated.
+ * @param block Flag to indicate if call should block if event queue is full.
+ *
+ * @return 0 on succes or negative number if failed to send notification.
+ */
+static int
+stream_session_enqueue_notify (stream_session_t * s, u8 block)
+{
+  application_t *app;
+  session_fifo_event_t evt;
+  unix_shared_memory_queue_t *q;
+  static u32 serial_number;
+
+  if (PREDICT_FALSE (s->session_state == SESSION_STATE_CLOSED))
+    return 0;
+
+  /* Get session's server */
+  app = application_get (s->app_index);
+
+  /* Fabricate event */
+  evt.fifo = s->server_rx_fifo;
+  evt.event_type = FIFO_EVENT_SERVER_RX;
+  evt.event_id = serial_number++;
+  evt.enqueue_length = svm_fifo_max_dequeue (s->server_rx_fifo);
+
+  /* Add event to server's event queue */
+  q = app->event_queue;
+
+  /* Based on request block (or not) for lack of space */
+  if (block || PREDICT_TRUE (q->cursize < q->maxsize))
+    unix_shared_memory_queue_add (app->event_queue, (u8 *) & evt,
+                                 0 /* do wait for mutex */ );
+  else
+    return -1;
+
+  if (1)
+    {
+      ELOG_TYPE_DECLARE (e) =
+      {
+      .format = "evt-enqueue: id %d length %d",.format_args = "i4i4",};
+      struct
+      {
+       u32 data[2];
+      } *ed;
+      ed = ELOG_DATA (&vlib_global_main.elog_main, e);
+      ed->data[0] = evt.event_id;
+      ed->data[1] = evt.enqueue_length;
+    }
+
+  return 0;
+}
+
+/**
+ * Flushes queue of sessions that are to be notified of new data
+ * enqueued events.
+ *
+ * @param thread_index Thread index for which the flush is to be performed.
+ * @return 0 on success or a positive number indicating the number of
+ *         failures due to API queue being full.
+ */
+int
+session_manager_flush_enqueue_events (u32 thread_index)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  u32 *session_indices_to_enqueue;
+  int i, errors = 0;
+
+  session_indices_to_enqueue =
+    smm->session_indices_to_enqueue_by_thread[thread_index];
+
+  for (i = 0; i < vec_len (session_indices_to_enqueue); i++)
+    {
+      stream_session_t *s0;
+
+      /* Get session */
+      s0 = stream_session_get (session_indices_to_enqueue[i], thread_index);
+      if (stream_session_enqueue_notify (s0, 0 /* don't block */ ))
+       {
+         errors++;
+       }
+    }
+
+  vec_reset_length (session_indices_to_enqueue);
+
+  smm->session_indices_to_enqueue_by_thread[thread_index] =
+    session_indices_to_enqueue;
+
+  /* Increment enqueue epoch for next round */
+  smm->current_enqueue_epoch[thread_index]++;
+
+  return errors;
+}
+
+/*
+ * Start listening on server's ip/port pair for requested transport.
+ *
+ * Creates a 'dummy' stream session with state LISTENING to be used in session
+ * lookups, prior to establishing connection. Requests transport to build
+ * it's own specific listening connection.
+ */
+int
+stream_session_start_listen (u32 server_index, ip46_address_t * ip, u16 port)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  stream_session_t *s;
+  transport_connection_t *tc;
+  application_t *srv;
+  u32 tci;
+
+  srv = application_get (server_index);
+
+  pool_get (smm->listen_sessions[srv->session_type], s);
+  memset (s, 0, sizeof (*s));
+
+  s->session_type = srv->session_type;
+  s->session_state = SESSION_STATE_LISTENING;
+  s->session_index = s - smm->listen_sessions[srv->session_type];
+  s->app_index = srv->index;
+
+  /* Transport bind/listen  */
+  tci = tp_vfts[srv->session_type].bind (smm->vlib_main, s->session_index, ip,
+                                        port);
+
+  /* Attach transport to session */
+  s->connection_index = tci;
+  tc = tp_vfts[srv->session_type].get_listener (tci);
+
+  srv->session_index = s->session_index;
+
+  /* Add to the main lookup table */
+  stream_session_table_add_for_tc (s->session_type, tc, s->session_index);
+
+  return 0;
+}
+
+void
+stream_session_stop_listen (u32 server_index)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  stream_session_t *listener;
+  transport_connection_t *tc;
+  application_t *srv;
+
+  srv = application_get (server_index);
+  listener = pool_elt_at_index (smm->listen_sessions[srv->session_type],
+                               srv->session_index);
+
+  tc = tp_vfts[srv->session_type].get_listener (listener->connection_index);
+  stream_session_table_del_for_tc (smm, listener->session_type, tc);
+
+  tp_vfts[srv->session_type].unbind (smm->vlib_main,
+                                    listener->connection_index);
+  pool_put (smm->listen_sessions[srv->session_type], listener);
+}
+
+int
+connect_server_add_segment_cb (application_t * ss, char *segment_name,
+                              u32 segment_size)
+{
+  /* Does exactly nothing, but die */
+  ASSERT (0);
+  return 0;
+}
+
+void
+connects_session_manager_init (session_manager_main_t * smm, u8 session_type)
+{
+  session_manager_t *sm;
+  u32 connect_fifo_size = 8 << 10;     /* Config? */
+  u32 default_segment_size = 1 << 20;
+
+  pool_get (smm->session_managers, sm);
+  memset (sm, 0, sizeof (*sm));
+
+  sm->add_segment_size = default_segment_size;
+  sm->rx_fifo_size = connect_fifo_size;
+  sm->tx_fifo_size = connect_fifo_size;
+  sm->add_segment = 1;
+
+  session_manager_add_segment (smm, sm);
+  smm->connect_manager_index[session_type] = sm - smm->session_managers;
+}
+
+void
+stream_session_connect_notify (transport_connection_t * tc, u8 sst,
+                              u8 is_fail)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  application_t *app;
+  stream_session_t *new_s = 0;
+  u64 value;
+
+  value = stream_session_half_open_lookup (smm, &tc->lcl_ip, &tc->rmt_ip,
+                                          tc->lcl_port, tc->rmt_port,
+                                          tc->proto);
+  if (value == HALF_OPEN_LOOKUP_INVALID_VALUE)
+    {
+      clib_warning ("This can't be good!");
+      return;
+    }
+
+  app = application_get (value >> 32);
+
+  if (!is_fail)
+    {
+      /* Create new session (server segments are allocated if needed) */
+      if (stream_session_create_i (smm, app, tc, &new_s))
+       return;
+
+      app->session_index = stream_session_get_index (new_s);
+      app->thread_index = new_s->thread_index;
+
+      /* Allocate vpp event queue for this thread if needed */
+      vpp_session_event_queue_allocate (smm, tc->thread_index);
+    }
+
+  /* Notify client */
+  app->cb_fns.session_connected_callback (app->api_client_index, new_s,
+                                         is_fail);
+
+  /* Cleanup session lookup */
+  stream_session_half_open_table_del (smm, sst, tc);
+}
+
+void
+stream_session_accept_notify (transport_connection_t * tc)
+{
+  application_t *server;
+  stream_session_t *s;
+
+  s = stream_session_get (tc->s_index, tc->thread_index);
+  server = application_get (s->app_index);
+  server->cb_fns.session_accept_callback (s);
+}
+
+/**
+ * Notification from transport that connection is being closed.
+ *
+ * A disconnect is sent to application but state is not removed. Once
+ * disconnect is acknowledged by application, session disconnect is called.
+ * Ultimately this leads to close being called on transport (passive close).
+ */
+void
+stream_session_disconnect_notify (transport_connection_t * tc)
+{
+  application_t *server;
+  stream_session_t *s;
+
+  s = stream_session_get (tc->s_index, tc->thread_index);
+  server = application_get (s->app_index);
+  server->cb_fns.session_disconnect_callback (s);
+}
+
+/**
+ * Cleans up session and associated app if needed.
+ */
+void
+stream_session_delete (stream_session_t * s)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  svm_fifo_segment_private_t *fifo_segment;
+  application_t *app;
+  int rv;
+
+  /* delete from the main lookup table */
+  rv = stream_session_table_del (smm, s);
+
+  if (rv)
+    clib_warning ("hash delete error, rv %d", rv);
+
+  /* Cleanup fifo segments */
+  fifo_segment = svm_fifo_get_segment (s->server_segment_index);
+  svm_fifo_segment_free_fifo (fifo_segment, s->server_rx_fifo);
+  svm_fifo_segment_free_fifo (fifo_segment, s->server_tx_fifo);
+
+  /* Cleanup app if client */
+  app = application_get (s->app_index);
+  if (app->mode == APP_CLIENT)
+    {
+      application_del (app);
+    }
+  else if (app->mode == APP_SERVER)
+    {
+      session_manager_t *sm;
+      svm_fifo_segment_private_t *fifo_segment;
+      svm_fifo_t **fifos;
+      u32 fifo_index;
+
+      sm = session_manager_get (app->session_manager_index);
+
+      /* Delete fifo */
+      fifo_segment = svm_fifo_get_segment (s->server_segment_index);
+      fifos = (svm_fifo_t **) fifo_segment->h->fifos;
+
+      fifo_index = svm_fifo_segment_index (fifo_segment);
+
+      /* Remove segment only if it holds no fifos and not the first */
+      if (sm->segment_indices[0] != fifo_index && vec_len (fifos) == 0)
+       svm_fifo_segment_delete (fifo_segment);
+    }
+
+  pool_put (smm->sessions[s->thread_index], s);
+}
+
+/**
+ * Notification from transport that connection is being deleted
+ *
+ * This should be called only on previously fully established sessions. For
+ * instance failed connects should call stream_session_connect_notify and
+ * indicate that the connect has failed.
+ */
+void
+stream_session_delete_notify (transport_connection_t * tc)
+{
+  stream_session_t *s;
+
+  s = stream_session_get_if_valid (tc->s_index, tc->thread_index);
+  if (!s)
+    {
+      clib_warning ("Surprised!");
+      return;
+    }
+  stream_session_delete (s);
+}
+
+/**
+ * Notify application that connection has been reset.
+ */
+void
+stream_session_reset_notify (transport_connection_t * tc)
+{
+  stream_session_t *s;
+  application_t *app;
+  s = stream_session_get (tc->s_index, tc->thread_index);
+
+  app = application_get (s->app_index);
+  app->cb_fns.session_reset_callback (s);
+}
+
+/**
+ * Accept a stream session. Optionally ping the server by callback.
+ */
+int
+stream_session_accept (transport_connection_t * tc, u32 listener_index,
+                      u8 sst, u8 notify)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  application_t *server;
+  stream_session_t *s, *listener;
+
+  int rv;
+
+  /* Find the server */
+  listener = pool_elt_at_index (smm->listen_sessions[sst], listener_index);
+  server = application_get (listener->app_index);
+
+  if ((rv = stream_session_create_i (smm, server, tc, &s)))
+    return rv;
+
+  /* Allocate vpp event queue for this thread if needed */
+  vpp_session_event_queue_allocate (smm, tc->thread_index);
+
+  /* Shoulder-tap the server */
+  if (notify)
+    {
+      server->cb_fns.session_accept_callback (s);
+    }
+
+  return 0;
+}
+
+void
+stream_session_open (u8 sst, ip46_address_t * addr, u16 port_host_byte_order,
+                    u32 app_index)
+{
+  transport_connection_t *tc;
+  u32 tci;
+  u64 value;
+
+  /* Ask transport to open connection */
+  tci = tp_vfts[sst].open (addr, port_host_byte_order);
+
+  /* Get transport connection */
+  tc = tp_vfts[sst].get_half_open (tci);
+
+  /* Store api_client_index and transport connection index */
+  value = (((u64) app_index) << 32) | (u64) tc->c_index;
+
+  /* Add to the half-open lookup table */
+  stream_session_half_open_table_add (sst, tc, value);
+}
+
+/**
+ * Disconnect session and propagate to transport. This should eventually
+ * result in a delete notification that allows us to cleanup session state.
+ * Called for both active/passive disconnects.
+ */
+void
+stream_session_disconnect (stream_session_t * s)
+{
+  tp_vfts[s->session_type].close (s->connection_index, s->thread_index);
+  s->session_state = SESSION_STATE_CLOSED;
+}
+
+/**
+ * Cleanup transport and session state.
+ */
+void
+stream_session_cleanup (stream_session_t * s)
+{
+  tp_vfts[s->session_type].cleanup (s->connection_index, s->thread_index);
+  stream_session_delete (s);
+}
+
+void
+session_register_transport (u8 type, const transport_proto_vft_t * vft)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+
+  vec_validate (tp_vfts, type);
+  tp_vfts[type] = *vft;
+
+  /* If an offset function is provided, then peek instead of dequeue */
+  smm->session_rx_fns[type] =
+    (vft->rx_fifo_offset) ? session_fifo_rx_peek : session_fifo_rx_dequeue;
+}
+
+transport_proto_vft_t *
+session_get_transport_vft (u8 type)
+{
+  if (type >= vec_len (tp_vfts))
+    return 0;
+  return &tp_vfts[type];
+}
+
+static clib_error_t *
+session_manager_main_init (vlib_main_t * vm)
+{
+  u32 num_threads;
+  vlib_thread_main_t *vtm = vlib_get_thread_main ();
+  session_manager_main_t *smm = &session_manager_main;
+  int i;
+
+  smm->vlib_main = vm;
+  smm->vnet_main = vnet_get_main ();
+
+  num_threads = 1 /* main thread */  + vtm->n_threads;
+
+  if (num_threads < 1)
+    return clib_error_return (0, "n_thread_stacks not set");
+
+  /* $$$ config parameters */
+  svm_fifo_segment_init (0x200000000ULL /* first segment base VA */ ,
+                        20 /* timeout in seconds */ );
+
+  /* configure per-thread ** vectors */
+  vec_validate (smm->sessions, num_threads - 1);
+  vec_validate (smm->session_indices_to_enqueue_by_thread, num_threads - 1);
+  vec_validate (smm->tx_buffers, num_threads - 1);
+  vec_validate (smm->fifo_events, num_threads - 1);
+  vec_validate (smm->evts_partially_read, num_threads - 1);
+  vec_validate (smm->current_enqueue_epoch, num_threads - 1);
+  vec_validate (smm->vpp_event_queues, num_threads - 1);
+
+  /* $$$$ preallocate hack config parameter */
+  for (i = 0; i < 200000; i++)
+    {
+      stream_session_t *ss;
+      pool_get (smm->sessions[0], ss);
+      memset (ss, 0, sizeof (*ss));
+    }
+
+  for (i = 0; i < 200000; i++)
+    pool_put_index (smm->sessions[0], i);
+
+  clib_bihash_init_16_8 (&smm->v4_session_hash, "v4 session table",
+                        200000 /* $$$$ config parameter nbuckets */ ,
+                        (64 << 20) /*$$$ config parameter table size */ );
+  clib_bihash_init_48_8 (&smm->v6_session_hash, "v6 session table",
+                        200000 /* $$$$ config parameter nbuckets */ ,
+                        (64 << 20) /*$$$ config parameter table size */ );
+
+  clib_bihash_init_16_8 (&smm->v4_half_open_hash, "v4 half-open table",
+                        200000 /* $$$$ config parameter nbuckets */ ,
+                        (64 << 20) /*$$$ config parameter table size */ );
+  clib_bihash_init_48_8 (&smm->v6_half_open_hash, "v6 half-open table",
+                        200000 /* $$$$ config parameter nbuckets */ ,
+                        (64 << 20) /*$$$ config parameter table size */ );
+
+  for (i = 0; i < SESSION_N_TYPES; i++)
+    smm->connect_manager_index[i] = INVALID_INDEX;
+
+  return 0;
+}
+
+VLIB_INIT_FUNCTION (session_manager_main_init);
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/session.h b/src/vnet/session/session.h
new file mode 100644 (file)
index 0000000..cf14cca
--- /dev/null
@@ -0,0 +1,380 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __included_session_h__
+#define __included_session_h__
+
+#include <vnet/session/transport.h>
+#include <vlibmemory/unix_shared_memory_queue.h>
+#include <vlibmemory/api.h>
+#include <vppinfra/sparse_vec.h>
+#include <svm/svm_fifo_segment.h>
+
+#define HALF_OPEN_LOOKUP_INVALID_VALUE ((u64)~0)
+#define INVALID_INDEX ((u32)~0)
+
+/* TODO decide how much since we have pre-data as well */
+#define MAX_HDRS_LEN    100    /* Max number of bytes for headers */
+
+typedef enum
+{
+  FIFO_EVENT_SERVER_RX,
+  FIFO_EVENT_SERVER_TX,
+  FIFO_EVENT_TIMEOUT,
+  FIFO_EVENT_SERVER_EXIT,
+} fifo_event_type_t;
+
+#define foreach_session_input_error                                         \
+_(NO_SESSION, "No session drops")                                       \
+_(NO_LISTENER, "No listener for dst port drops")                        \
+_(ENQUEUED, "Packets pushed into rx fifo")                              \
+_(NOT_READY, "Session not ready packets")                               \
+_(FIFO_FULL, "Packets dropped for lack of rx fifo space")               \
+_(EVENT_FIFO_FULL, "Events not sent for lack of event fifo space")      \
+_(API_QUEUE_FULL, "Sessions not created for lack of API queue space")   \
+_(NEW_SEG_NO_SPACE, "Created segment, couldn't allocate a fifo pair")   \
+_(NO_SPACE, "Couldn't allocate a fifo pair")
+
+typedef enum
+{
+#define _(sym,str) SESSION_ERROR_##sym,
+  foreach_session_input_error
+#undef _
+    SESSION_N_ERROR,
+} session_error_t;
+
+/* Event queue input node static next indices */
+typedef enum
+{
+  SESSION_QUEUE_NEXT_DROP,
+  SESSION_QUEUE_NEXT_TCP_IP4_OUTPUT,
+  SESSION_QUEUE_NEXT_IP4_LOOKUP,
+  SESSION_QUEUE_NEXT_TCP_IP6_OUTPUT,
+  SESSION_QUEUE_NEXT_IP6_LOOKUP,
+  SESSION_QUEUE_N_NEXT,
+} session_queue_next_t;
+
+#define foreach_session_type                    \
+  _(IP4_TCP, ip4_tcp)                           \
+  _(IP4_UDP, ip4_udp)                           \
+  _(IP6_TCP, ip6_tcp)                           \
+  _(IP6_UDP, ip6_udp)
+
+typedef enum
+{
+#define _(A, a) SESSION_TYPE_##A,
+  foreach_session_type
+#undef _
+    SESSION_N_TYPES,
+} session_type_t;
+
+/*
+ * Application session state
+ */
+typedef enum
+{
+  SESSION_STATE_LISTENING,
+  SESSION_STATE_CONNECTING,
+  SESSION_STATE_READY,
+  SESSION_STATE_CLOSED,
+  SESSION_STATE_N_STATES,
+} stream_session_state_t;
+
+typedef CLIB_PACKED (struct
+                    {
+                    svm_fifo_t * fifo;
+                    u8 event_type;
+                    /* $$$$ for event logging */
+                    u16 event_id;
+                    u32 enqueue_length;
+                    }) session_fifo_event_t;
+
+typedef struct _stream_session_t
+{
+  /** Type */
+  u8 session_type;
+
+  /** State */
+  u8 session_state;
+
+  /** Session index in per_thread pool */
+  u32 session_index;
+
+  /** Transport specific */
+  u32 connection_index;
+
+  u8 thread_index;
+
+  /** Application specific */
+  u32 pid;
+
+  /** fifo pointers. Once allocated, these do not move */
+  svm_fifo_t *server_rx_fifo;
+  svm_fifo_t *server_tx_fifo;
+
+  /** To avoid n**2 "one event per frame" check */
+  u8 enqueue_epoch;
+
+  /** used during unbind processing */
+  u8 is_deleted;
+
+  /** stream server pool index */
+  u32 app_index;
+
+  /** svm segment index */
+  u32 server_segment_index;
+} stream_session_t;
+
+typedef struct _session_manager
+{
+  /** segments mapped by this server */
+  u32 *segment_indices;
+
+  /** Session fifo sizes. They are provided for binds and take default
+   * values for connects */
+  u32 rx_fifo_size;
+  u32 tx_fifo_size;
+
+  /** Configured additional segment size */
+  u32 add_segment_size;
+
+  /** Flag that indicates if additional segments should be created */
+  u8 add_segment;
+} session_manager_t;
+
+/* Forward definition */
+typedef struct _session_manager_main session_manager_main_t;
+
+typedef int
+  (session_fifo_rx_fn) (vlib_main_t * vm, vlib_node_runtime_t * node,
+                       session_manager_main_t * smm,
+                       session_fifo_event_t * e0, stream_session_t * s0,
+                       u32 thread_index, int *n_tx_pkts);
+
+extern session_fifo_rx_fn session_fifo_rx_peek;
+extern session_fifo_rx_fn session_fifo_rx_dequeue;
+
+struct _session_manager_main
+{
+  /** Lookup tables for established sessions and listeners */
+  clib_bihash_16_8_t v4_session_hash;
+  clib_bihash_48_8_t v6_session_hash;
+
+  /** Lookup tables for half-open sessions */
+  clib_bihash_16_8_t v4_half_open_hash;
+  clib_bihash_48_8_t v6_half_open_hash;
+
+  /** Per worker thread session pools */
+  stream_session_t **sessions;
+
+  /** Pool of listen sessions. Same type as stream sessions to ease lookups */
+  stream_session_t *listen_sessions[SESSION_N_TYPES];
+
+  /** Sparse vector to map dst port to stream server  */
+  u16 *stream_server_by_dst_port[SESSION_N_TYPES];
+
+  /** per-worker enqueue epoch counters */
+  u8 *current_enqueue_epoch;
+
+  /** Per-worker thread vector of sessions to enqueue */
+  u32 **session_indices_to_enqueue_by_thread;
+
+  /** per-worker tx buffer free lists */
+  u32 **tx_buffers;
+
+  /** Per worker-thread vector of partially read events */
+  session_fifo_event_t **evts_partially_read;
+
+  /** per-worker active event vectors */
+  session_fifo_event_t **fifo_events;
+
+  /** vpp fifo event queue */
+  unix_shared_memory_queue_t **vpp_event_queues;
+
+  /** Unique segment name counter */
+  u32 unique_segment_name_counter;
+
+  /* Connection manager used by incoming connects */
+  u32 connect_manager_index[SESSION_N_TYPES];
+
+  session_manager_t *session_managers;
+
+  /** Per transport rx function that can either dequeue or peek */
+  session_fifo_rx_fn *session_rx_fns[SESSION_N_TYPES];
+
+  /* Convenience */
+  vlib_main_t *vlib_main;
+  vnet_main_t *vnet_main;
+};
+
+extern session_manager_main_t session_manager_main;
+
+/*
+ * Session manager function
+ */
+always_inline session_manager_main_t *
+vnet_get_session_manager_main ()
+{
+  return &session_manager_main;
+}
+
+always_inline session_manager_t *
+session_manager_get (u32 index)
+{
+  return pool_elt_at_index (session_manager_main.session_managers, index);
+}
+
+always_inline unix_shared_memory_queue_t *
+session_manager_get_vpp_event_queue (u32 thread_index)
+{
+  return session_manager_main.vpp_event_queues[thread_index];
+}
+
+always_inline session_manager_t *
+connects_session_manager_get (session_manager_main_t * smm,
+                             session_type_t session_type)
+{
+  return pool_elt_at_index (smm->session_managers,
+                           smm->connect_manager_index[session_type]);
+}
+
+void session_manager_get_segment_info (u32 index, u8 ** name, u32 * size);
+int session_manager_flush_enqueue_events (u32 thread_index);
+int
+session_manager_add_first_segment (session_manager_main_t * smm,
+                                  session_manager_t * sm, u32 segment_size,
+                                  u8 ** segment_name);
+void
+session_manager_del (session_manager_main_t * smm, session_manager_t * sm);
+void
+connects_session_manager_init (session_manager_main_t * smm, u8 session_type);
+
+/*
+ * Stream session functions
+ */
+
+stream_session_t *stream_session_lookup_listener4 (ip4_address_t * lcl,
+                                                  u16 lcl_port, u8 proto);
+stream_session_t *stream_session_lookup4 (ip4_address_t * lcl,
+                                         ip4_address_t * rmt, u16 lcl_port,
+                                         u16 rmt_port, u8 proto,
+                                         u32 thread_index);
+stream_session_t *stream_session_lookup_listener6 (ip6_address_t * lcl,
+                                                  u16 lcl_port, u8 proto);
+stream_session_t *stream_session_lookup6 (ip6_address_t * lcl,
+                                         ip6_address_t * rmt, u16 lcl_port,
+                                         u16 rmt_port, u8, u32 thread_index);
+transport_connection_t
+  * stream_session_lookup_transport4 (session_manager_main_t * smm,
+                                     ip4_address_t * lcl,
+                                     ip4_address_t * rmt, u16 lcl_port,
+                                     u16 rmt_port, u8 proto,
+                                     u32 thread_index);
+transport_connection_t
+  * stream_session_lookup_transport6 (session_manager_main_t * smm,
+                                     ip6_address_t * lcl,
+                                     ip6_address_t * rmt, u16 lcl_port,
+                                     u16 rmt_port, u8 proto,
+                                     u32 thread_index);
+stream_session_t *stream_session_lookup_listener (ip46_address_t * lcl,
+                                                 u16 lcl_port, u8 proto);
+
+always_inline stream_session_t *
+stream_session_get_tsi (u64 ti_and_si, u32 thread_index)
+{
+  ASSERT ((u32) (ti_and_si >> 32) == thread_index);
+  return pool_elt_at_index (session_manager_main.sessions[thread_index],
+                           ti_and_si & 0xFFFFFFFFULL);
+}
+
+always_inline stream_session_t *
+stream_session_get (u64 si, u32 thread_index)
+{
+  return pool_elt_at_index (session_manager_main.sessions[thread_index], si);
+}
+
+always_inline stream_session_t *
+stream_session_get_if_valid (u64 si, u32 thread_index)
+{
+  if (thread_index >= vec_len (session_manager_main.sessions))
+    return 0;
+
+  if (pool_is_free_index (session_manager_main.sessions[thread_index], si))
+    return 0;
+
+  return pool_elt_at_index (session_manager_main.sessions[thread_index], si);
+}
+
+always_inline stream_session_t *
+stream_session_listener_get (u8 sst, u64 si)
+{
+  return pool_elt_at_index (session_manager_main.listen_sessions[sst], si);
+}
+
+always_inline u32
+stream_session_get_index (stream_session_t * s)
+{
+  if (s->session_state == SESSION_STATE_LISTENING)
+    return s - session_manager_main.listen_sessions[s->session_type];
+
+  return s - session_manager_main.sessions[s->thread_index];
+}
+
+always_inline u32
+stream_session_max_enqueue (transport_connection_t * tc)
+{
+  stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
+  return svm_fifo_max_enqueue (s->server_rx_fifo);
+}
+
+int
+stream_session_enqueue_data (transport_connection_t * tc, u8 * data, u16 len,
+                            u8 queue_event);
+u32
+stream_session_peek_bytes (transport_connection_t * tc, u8 * buffer,
+                          u32 offset, u32 max_bytes);
+u32 stream_session_dequeue_drop (transport_connection_t * tc, u32 max_bytes);
+
+void
+stream_session_connect_notify (transport_connection_t * tc, u8 sst,
+                              u8 is_fail);
+void stream_session_accept_notify (transport_connection_t * tc);
+void stream_session_disconnect_notify (transport_connection_t * tc);
+void stream_session_delete_notify (transport_connection_t * tc);
+void stream_session_reset_notify (transport_connection_t * tc);
+int
+stream_session_accept (transport_connection_t * tc, u32 listener_index,
+                      u8 sst, u8 notify);
+void stream_session_open (u8 sst, ip46_address_t * addr,
+                         u16 port_host_byte_order, u32 api_client_index);
+void stream_session_disconnect (stream_session_t * s);
+void stream_session_cleanup (stream_session_t * s);
+int
+stream_session_start_listen (u32 server_index, ip46_address_t * ip, u16 port);
+void stream_session_stop_listen (u32 server_index);
+
+u8 *format_stream_session (u8 * s, va_list * args);
+
+void session_register_transport (u8 type, const transport_proto_vft_t * vft);
+transport_proto_vft_t *session_get_transport_vft (u8 type);
+
+#endif /* __included_session_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/session_api.c b/src/vnet/session/session_api.c
new file mode 100644 (file)
index 0000000..9d06868
--- /dev/null
@@ -0,0 +1,821 @@
+/*
+ * Copyright (c) 2015-2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vnet/vnet.h>
+#include <vlibmemory/api.h>
+#include <vnet/session/application.h>
+
+#include <vnet/vnet_msg_enum.h>
+#include "application_interface.h"
+
+#define vl_typedefs            /* define message structures */
+#include <vnet/vnet_all_api_h.h>
+#undef vl_typedefs
+
+#define vl_endianfun           /* define message structures */
+#include <vnet/vnet_all_api_h.h>
+#undef vl_endianfun
+
+/* instantiate all the print functions we know about */
+#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
+#define vl_printfun
+#include <vnet/vnet_all_api_h.h>
+#undef vl_printfun
+
+#include <vlibapi/api_helper_macros.h>
+
+#define foreach_session_api_msg                                         \
+_(MAP_ANOTHER_SEGMENT_REPLY, map_another_segment_reply)                 \
+_(BIND_URI, bind_uri)                                                   \
+_(UNBIND_URI, unbind_uri)                                               \
+_(CONNECT_URI, connect_uri)                                             \
+_(DISCONNECT_SESSION, disconnect_session)                               \
+_(DISCONNECT_SESSION_REPLY, disconnect_session_reply)                   \
+_(ACCEPT_SESSION_REPLY, accept_session_reply)                           \
+_(RESET_SESSION_REPLY, reset_session_reply)                            \
+_(BIND_SOCK, bind_sock)                                                \
+_(UNBIND_SOCK, unbind_sock)                                             \
+_(CONNECT_SOCK, connect_sock)                                                  \
+_(DISCONNECT_SOCK, disconnect_sock)                                    \
+_(DISCONNECT_SOCK_REPLY, disconnect_sock_reply)                                \
+_(ACCEPT_SOCK_REPLY, accept_sock_reply)                                \
+_(RESET_SOCK_REPLY, reset_sock_reply)                                  \
+
+static int
+send_add_segment_callback (u32 api_client_index, const u8 * segment_name,
+                          u32 segment_size)
+{
+  vl_api_map_another_segment_t *mp;
+  unix_shared_memory_queue_t *q;
+
+  q = vl_api_client_index_to_input_queue (api_client_index);
+
+  if (!q)
+    return -1;
+
+  mp = vl_msg_api_alloc (sizeof (*mp));
+  memset (mp, 0, sizeof (*mp));
+  mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_MAP_ANOTHER_SEGMENT);
+  mp->segment_size = segment_size;
+  strncpy ((char *) mp->segment_name, (char *) segment_name,
+          sizeof (mp->segment_name) - 1);
+
+  vl_msg_api_send_shmem (q, (u8 *) & mp);
+
+  return 0;
+}
+
+static int
+send_session_accept_uri_callback (stream_session_t * s)
+{
+  vl_api_accept_session_t *mp;
+  unix_shared_memory_queue_t *q, *vpp_queue;
+  application_t *server = application_get (s->app_index);
+
+  q = vl_api_client_index_to_input_queue (server->api_client_index);
+  vpp_queue = session_manager_get_vpp_event_queue (s->thread_index);
+
+  if (!q)
+    return -1;
+
+  mp = vl_msg_api_alloc (sizeof (*mp));
+  mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_ACCEPT_SESSION);
+
+  /* Note: session_type is the first octet in all types of sessions */
+
+  mp->accept_cookie = server->accept_cookie;
+  mp->server_rx_fifo = (u64) s->server_rx_fifo;
+  mp->server_tx_fifo = (u64) s->server_tx_fifo;
+  mp->session_thread_index = s->thread_index;
+  mp->session_index = s->session_index;
+  mp->session_type = s->session_type;
+  mp->vpp_event_queue_address = (u64) vpp_queue;
+  vl_msg_api_send_shmem (q, (u8 *) & mp);
+
+  return 0;
+}
+
+static void
+send_session_disconnect_uri_callback (stream_session_t * s)
+{
+  vl_api_disconnect_session_t *mp;
+  unix_shared_memory_queue_t *q;
+  application_t *app = application_get (s->app_index);
+
+  q = vl_api_client_index_to_input_queue (app->api_client_index);
+
+  if (!q)
+    return;
+
+  mp = vl_msg_api_alloc (sizeof (*mp));
+  memset (mp, 0, sizeof (*mp));
+  mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_DISCONNECT_SESSION);
+
+  mp->session_thread_index = s->thread_index;
+  mp->session_index = s->session_index;
+  vl_msg_api_send_shmem (q, (u8 *) & mp);
+}
+
+static int
+send_session_connected_uri_callback (u32 api_client_index,
+                                    stream_session_t * s, u8 is_fail)
+{
+  vl_api_connect_uri_reply_t *mp;
+  unix_shared_memory_queue_t *q;
+  application_t *app = application_lookup (api_client_index);
+  u8 *seg_name;
+  unix_shared_memory_queue_t *vpp_queue;
+
+  q = vl_api_client_index_to_input_queue (app->api_client_index);
+
+  if (!q)
+    return -1;
+
+  mp = vl_msg_api_alloc (sizeof (*mp));
+  mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_CONNECT_URI_REPLY);
+  mp->context = app->api_context;
+  mp->retval = is_fail;
+  if (!is_fail)
+    {
+      vpp_queue = session_manager_get_vpp_event_queue (s->thread_index);
+      mp->server_rx_fifo = (u64) s->server_rx_fifo;
+      mp->server_tx_fifo = (u64) s->server_tx_fifo;
+      mp->session_thread_index = s->thread_index;
+      mp->session_index = s->session_index;
+      mp->session_type = s->session_type;
+      mp->vpp_event_queue_address = (u64) vpp_queue;
+      mp->client_event_queue_address = (u64) app->event_queue;
+
+      session_manager_get_segment_info (s->server_segment_index, &seg_name,
+                                       &mp->segment_size);
+      mp->segment_name_length = vec_len (seg_name);
+      if (mp->segment_name_length)
+       clib_memcpy (mp->segment_name, seg_name, mp->segment_name_length);
+    }
+
+  vl_msg_api_send_shmem (q, (u8 *) & mp);
+
+  /* Remove client if connect failed */
+  if (is_fail)
+    application_del (app);
+
+  return 0;
+}
+
+/**
+ * Redirect a connect_uri message to the indicated server.
+ * Only sent if the server has bound the related port with
+ * URI_OPTIONS_FLAGS_USE_FIFO
+ */
+static int
+redirect_connect_uri_callback (u32 server_api_client_index, void *mp_arg)
+{
+  vl_api_connect_uri_t *mp = mp_arg;
+  unix_shared_memory_queue_t *server_q, *client_q;
+  vlib_main_t *vm = vlib_get_main ();
+  f64 timeout = vlib_time_now (vm) + 0.5;
+  int rv = 0;
+
+  server_q = vl_api_client_index_to_input_queue (server_api_client_index);
+
+  if (!server_q)
+    {
+      rv = VNET_API_ERROR_INVALID_VALUE;
+      goto out;
+    }
+
+  client_q = vl_api_client_index_to_input_queue (mp->client_index);
+  if (!client_q)
+    {
+      rv = VNET_API_ERROR_INVALID_VALUE_2;
+      goto out;
+    }
+
+  /* Tell the server the client's API queue address, so it can reply */
+  mp->client_queue_address = (u64) client_q;
+
+  /*
+   * Bounce message handlers MUST NOT block the data-plane.
+   * Spin waiting for the queue lock, but
+   */
+
+  while (vlib_time_now (vm) < timeout)
+    {
+      rv =
+       unix_shared_memory_queue_add (server_q, (u8 *) & mp, 1 /*nowait */ );
+      switch (rv)
+       {
+         /* correctly enqueued */
+       case 0:
+         return VNET_CONNECT_REDIRECTED;
+
+         /* continue spinning, wait for pthread_mutex_trylock to work */
+       case -1:
+         continue;
+
+         /* queue stuffed, drop the msg */
+       case -2:
+         rv = VNET_API_ERROR_QUEUE_FULL;
+         goto out;
+       }
+    }
+out:
+  /* Dispose of the message */
+  vl_msg_api_free (mp);
+  return rv;
+}
+
+static u64
+make_session_handle (stream_session_t * s)
+{
+  return (u64) s->session_index << 32 | (u64) s->thread_index;
+}
+
+static int
+send_session_accept_callback (stream_session_t * s)
+{
+  vl_api_accept_sock_t *mp;
+  unix_shared_memory_queue_t *q, *vpp_queue;
+  application_t *server = application_get (s->app_index);
+
+  q = vl_api_client_index_to_input_queue (server->api_client_index);
+  vpp_queue = session_manager_get_vpp_event_queue (s->thread_index);
+
+  if (!q)
+    return -1;
+
+  mp = vl_msg_api_alloc (sizeof (*mp));
+  mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_ACCEPT_SOCK);
+
+  /* Note: session_type is the first octet in all types of sessions */
+
+  mp->accept_cookie = server->accept_cookie;
+  mp->server_rx_fifo = (u64) s->server_rx_fifo;
+  mp->server_tx_fifo = (u64) s->server_tx_fifo;
+  mp->handle = make_session_handle (s);
+  mp->vpp_event_queue_address = (u64) vpp_queue;
+  vl_msg_api_send_shmem (q, (u8 *) & mp);
+
+  return 0;
+}
+
+static int
+send_session_connected_callback (u32 api_client_index, stream_session_t * s,
+                                u8 is_fail)
+{
+  vl_api_connect_sock_reply_t *mp;
+  unix_shared_memory_queue_t *q;
+  application_t *app = application_lookup (api_client_index);
+  u8 *seg_name;
+  unix_shared_memory_queue_t *vpp_queue;
+
+  q = vl_api_client_index_to_input_queue (app->api_client_index);
+
+  if (!q)
+    return -1;
+
+  mp = vl_msg_api_alloc (sizeof (*mp));
+  mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_CONNECT_SOCK_REPLY);
+  mp->context = app->api_context;
+  mp->retval = is_fail;
+  if (!is_fail)
+    {
+      vpp_queue = session_manager_get_vpp_event_queue (s->thread_index);
+      mp->server_rx_fifo = (u64) s->server_rx_fifo;
+      mp->server_tx_fifo = (u64) s->server_tx_fifo;
+      mp->handle = make_session_handle (s);
+      mp->vpp_event_queue_address = (u64) vpp_queue;
+      mp->client_event_queue_address = (u64) app->event_queue;
+
+      session_manager_get_segment_info (s->server_segment_index, &seg_name,
+                                       &mp->segment_size);
+      mp->segment_name_length = vec_len (seg_name);
+      if (mp->segment_name_length)
+       clib_memcpy (mp->segment_name, seg_name, mp->segment_name_length);
+    }
+
+  vl_msg_api_send_shmem (q, (u8 *) & mp);
+
+  /* Remove client if connect failed */
+  if (is_fail)
+    application_del (app);
+
+  return 0;
+}
+
+static void
+send_session_disconnect_callback (stream_session_t * s)
+{
+  vl_api_disconnect_sock_t *mp;
+  unix_shared_memory_queue_t *q;
+  application_t *app = application_get (s->app_index);
+
+  q = vl_api_client_index_to_input_queue (app->api_client_index);
+
+  if (!q)
+    return;
+
+  mp = vl_msg_api_alloc (sizeof (*mp));
+  memset (mp, 0, sizeof (*mp));
+  mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_DISCONNECT_SOCK);
+
+  mp->handle = make_session_handle (s);
+  vl_msg_api_send_shmem (q, (u8 *) & mp);
+}
+
+/**
+ * Redirect a connect_uri message to the indicated server.
+ * Only sent if the server has bound the related port with
+ * URI_OPTIONS_FLAGS_USE_FIFO
+ */
+static int
+redirect_connect_callback (u32 server_api_client_index, void *mp_arg)
+{
+  vl_api_connect_sock_t *mp = mp_arg;
+  unix_shared_memory_queue_t *server_q, *client_q;
+  vlib_main_t *vm = vlib_get_main ();
+  f64 timeout = vlib_time_now (vm) + 0.5;
+  int rv = 0;
+
+  server_q = vl_api_client_index_to_input_queue (server_api_client_index);
+
+  if (!server_q)
+    {
+      rv = VNET_API_ERROR_INVALID_VALUE;
+      goto out;
+    }
+
+  client_q = vl_api_client_index_to_input_queue (mp->client_index);
+  if (!client_q)
+    {
+      rv = VNET_API_ERROR_INVALID_VALUE_2;
+      goto out;
+    }
+
+  /* Tell the server the client's API queue address, so it can reply */
+  mp->client_queue_address = (u64) client_q;
+
+  /*
+   * Bounce message handlers MUST NOT block the data-plane.
+   * Spin waiting for the queue lock, but
+   */
+
+  while (vlib_time_now (vm) < timeout)
+    {
+      rv =
+       unix_shared_memory_queue_add (server_q, (u8 *) & mp, 1 /*nowait */ );
+      switch (rv)
+       {
+         /* correctly enqueued */
+       case 0:
+         return VNET_CONNECT_REDIRECTED;
+
+         /* continue spinning, wait for pthread_mutex_trylock to work */
+       case -1:
+         continue;
+
+         /* queue stuffed, drop the msg */
+       case -2:
+         rv = VNET_API_ERROR_QUEUE_FULL;
+         goto out;
+       }
+    }
+out:
+  /* Dispose of the message */
+  vl_msg_api_free (mp);
+  return rv;
+}
+
+static session_cb_vft_t uri_session_cb_vft = {
+  .session_accept_callback = send_session_accept_uri_callback,
+  .session_disconnect_callback = send_session_disconnect_uri_callback,
+  .session_connected_callback = send_session_connected_uri_callback,
+  .add_segment_callback = send_add_segment_callback,
+  .redirect_connect_callback = redirect_connect_uri_callback
+};
+
+static session_cb_vft_t session_cb_vft = {
+  .session_accept_callback = send_session_accept_callback,
+  .session_disconnect_callback = send_session_disconnect_callback,
+  .session_connected_callback = send_session_connected_callback,
+  .add_segment_callback = send_add_segment_callback,
+  .redirect_connect_callback = redirect_connect_callback
+};
+
+static int
+api_session_not_valid (u32 session_index, u32 thread_index)
+{
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  stream_session_t *pool;
+
+  if (thread_index >= vec_len (smm->sessions))
+    return VNET_API_ERROR_INVALID_VALUE;
+
+  pool = smm->sessions[thread_index];
+
+  if (pool_is_free_index (pool, session_index))
+    return VNET_API_ERROR_INVALID_VALUE_2;
+
+  return 0;
+}
+
+static void
+vl_api_bind_uri_t_handler (vl_api_bind_uri_t * mp)
+{
+  vl_api_bind_uri_reply_t *rmp;
+  vnet_bind_args_t _a, *a = &_a;
+  char segment_name[128];
+  u32 segment_name_length;
+  int rv;
+
+  _Static_assert (sizeof (u64) * SESSION_OPTIONS_N_OPTIONS <=
+                 sizeof (mp->options),
+                 "Out of options, fix api message definition");
+
+  segment_name_length = ARRAY_LEN (segment_name);
+
+  memset (a, 0, sizeof (*a));
+
+  a->uri = (char *) mp->uri;
+  a->api_client_index = mp->client_index;
+  a->options = mp->options;
+  a->segment_name = segment_name;
+  a->segment_name_length = segment_name_length;
+  a->session_cb_vft = &uri_session_cb_vft;
+
+  a->options[SESSION_OPTIONS_SEGMENT_SIZE] = mp->initial_segment_size;
+  a->options[SESSION_OPTIONS_ACCEPT_COOKIE] = mp->accept_cookie;
+  rv = vnet_bind_uri (a);
+
+  /* *INDENT-OFF* */
+  REPLY_MACRO2 (VL_API_BIND_URI_REPLY, ({
+    rmp->retval = rv;
+    if (!rv)
+      {
+       rmp->segment_name_length = 0;
+       /* $$$$ policy? */
+       rmp->segment_size = mp->initial_segment_size;
+       if (segment_name_length)
+         {
+           memcpy (rmp->segment_name, segment_name, segment_name_length);
+           rmp->segment_name_length = segment_name_length;
+         }
+       rmp->server_event_queue_address = a->server_event_queue_address;
+      }
+  }));
+  /* *INDENT-ON* */
+
+}
+
+static void
+vl_api_unbind_uri_t_handler (vl_api_unbind_uri_t * mp)
+{
+  vl_api_unbind_uri_reply_t *rmp;
+  int rv;
+
+  rv = vnet_unbind_uri ((char *) mp->uri, mp->client_index);
+
+  REPLY_MACRO (VL_API_UNBIND_URI_REPLY);
+}
+
+static void
+vl_api_connect_uri_t_handler (vl_api_connect_uri_t * mp)
+{
+  vnet_connect_args_t _a, *a = &_a;
+
+  a->uri = (char *) mp->uri;
+  a->api_client_index = mp->client_index;
+  a->api_context = mp->context;
+  a->options = mp->options;
+  a->session_cb_vft = &uri_session_cb_vft;
+  a->mp = mp;
+  vnet_connect_uri (a);
+}
+
+static void
+vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
+{
+  vl_api_disconnect_session_reply_t *rmp;
+  int rv;
+
+  rv = api_session_not_valid (mp->session_index, mp->session_thread_index);
+  if (!rv)
+    rv = vnet_disconnect_session (mp->client_index, mp->session_index,
+                                 mp->session_thread_index);
+
+  REPLY_MACRO (VL_API_DISCONNECT_SESSION_REPLY);
+}
+
+static void
+vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
+                                          mp)
+{
+  if (api_session_not_valid (mp->session_index, mp->session_thread_index))
+    {
+      clib_warning ("Invalid session!");
+      return;
+    }
+
+  /* Client objected to disconnecting the session, log and continue */
+  if (mp->retval)
+    {
+      clib_warning ("client retval %d", mp->retval);
+      return;
+    }
+
+  /* Disconnect has been confirmed. Confirm close to transport */
+  vnet_disconnect_session (mp->client_index, mp->session_index,
+                          mp->session_thread_index);
+}
+
+static void
+vl_api_reset_session_reply_t_handler (vl_api_reset_session_reply_t * mp)
+{
+  stream_session_t *s;
+
+  if (api_session_not_valid (mp->session_index, mp->session_thread_index))
+    {
+      clib_warning ("Invalid session!");
+      return;
+    }
+
+  /* Client objected to resetting the session, log and continue */
+  if (mp->retval)
+    {
+      clib_warning ("client retval %d", mp->retval);
+      return;
+    }
+
+  s = stream_session_get (mp->session_index, mp->session_thread_index);
+
+  /* This comes as a response to a reset, transport only waiting for
+   * confirmation to remove connection state, no need to disconnect */
+  stream_session_cleanup (s);
+}
+
+static void
+vl_api_accept_session_reply_t_handler (vl_api_accept_session_reply_t * mp)
+{
+  stream_session_t *s;
+  int rv;
+
+  if (api_session_not_valid (mp->session_index, mp->session_thread_index))
+    return;
+
+  s = stream_session_get (mp->session_index, mp->session_thread_index);
+  rv = mp->retval;
+
+  if (rv)
+    {
+      /* Server isn't interested, kill the session */
+      stream_session_disconnect (s);
+      return;
+    }
+
+  s->session_state = SESSION_STATE_READY;
+}
+
+static void
+vl_api_map_another_segment_reply_t_handler (vl_api_map_another_segment_reply_t
+                                           * mp)
+{
+  clib_warning ("not implemented");
+}
+
+static void
+vl_api_bind_sock_t_handler (vl_api_bind_sock_t * mp)
+{
+  vl_api_bind_sock_reply_t *rmp;
+  vnet_bind_args_t _a, *a = &_a;
+  char segment_name[128];
+  u32 segment_name_length;
+  int rv;
+
+  STATIC_ASSERT (sizeof (u64) * SESSION_OPTIONS_N_OPTIONS <=
+                sizeof (mp->options),
+                "Out of options, fix api message definition");
+
+  segment_name_length = ARRAY_LEN (segment_name);
+
+  memset (a, 0, sizeof (*a));
+
+  clib_memcpy (&a->tep.ip, mp->ip,
+              (mp->is_ip4 ? sizeof (ip4_address_t) :
+               sizeof (ip6_address_t)));
+  a->tep.is_ip4 = mp->is_ip4;
+  a->tep.port = mp->port;
+  a->tep.vrf = mp->vrf;
+
+  a->api_client_index = mp->client_index;
+  a->options = mp->options;
+  a->segment_name = segment_name;
+  a->segment_name_length = segment_name_length;
+  a->session_cb_vft = &session_cb_vft;
+
+  rv = vnet_bind_uri (a);
+
+  /* *INDENT-OFF* */
+  REPLY_MACRO2 (VL_API_BIND_SOCK_REPLY, ({
+    rmp->retval = rv;
+    if (!rv)
+      {
+       rmp->segment_name_length = 0;
+       rmp->segment_size = mp->options[SESSION_OPTIONS_SEGMENT_SIZE];
+       if (segment_name_length)
+         {
+           memcpy(rmp->segment_name, segment_name, segment_name_length);
+           rmp->segment_name_length = segment_name_length;
+         }
+       rmp->server_event_queue_address = a->server_event_queue_address;
+      }
+  }));
+  /* *INDENT-ON* */
+}
+
+static void
+vl_api_unbind_sock_t_handler (vl_api_unbind_sock_t * mp)
+{
+  vl_api_unbind_sock_reply_t *rmp;
+  vnet_unbind_args_t _a, *a = &_a;
+  int rv;
+
+  a->api_client_index = mp->client_index;
+  a->handle = mp->handle;
+
+  rv = vnet_unbind (a);
+
+  REPLY_MACRO (VL_API_UNBIND_SOCK_REPLY);
+}
+
+static void
+vl_api_connect_sock_t_handler (vl_api_connect_sock_t * mp)
+{
+  vnet_connect_args_t _a, *a = &_a;
+
+  clib_memcpy (&a->tep.ip, mp->ip,
+              (mp->is_ip4 ? sizeof (ip4_address_t) :
+               sizeof (ip6_address_t)));
+  a->tep.is_ip4 = mp->is_ip4;
+  a->tep.port = mp->port;
+  a->tep.vrf = mp->vrf;
+  a->options = mp->options;
+  a->session_cb_vft = &session_cb_vft;
+  a->api_context = mp->context;
+  a->mp = mp;
+
+  vnet_connect (a);
+}
+
+static void
+vl_api_disconnect_sock_t_handler (vl_api_disconnect_sock_t * mp)
+{
+  vnet_disconnect_args_t _a, *a = &_a;
+  vl_api_disconnect_sock_reply_t *rmp;
+  int rv;
+
+  a->api_client_index = mp->client_index;
+  a->handle = mp->handle;
+  rv = vnet_disconnect (a);
+
+  REPLY_MACRO (VL_API_DISCONNECT_SOCK_REPLY);
+}
+
+static void
+vl_api_disconnect_sock_reply_t_handler (vl_api_disconnect_sock_reply_t * mp)
+{
+  vnet_disconnect_args_t _a, *a = &_a;
+
+  /* Client objected to disconnecting the session, log and continue */
+  if (mp->retval)
+    {
+      clib_warning ("client retval %d", mp->retval);
+      return;
+    }
+
+  a->api_client_index = mp->client_index;
+  a->handle = mp->handle;
+
+  vnet_disconnect (a);
+}
+
+static void
+vl_api_reset_sock_reply_t_handler (vl_api_reset_sock_reply_t * mp)
+{
+  stream_session_t *s;
+  u32 session_index, thread_index;
+
+  /* Client objected to resetting the session, log and continue */
+  if (mp->retval)
+    {
+      clib_warning ("client retval %d", mp->retval);
+      return;
+    }
+
+  if (api_parse_session_handle (mp->handle, &session_index, &thread_index))
+    {
+      clib_warning ("Invalid handle");
+      return;
+    }
+
+  s = stream_session_get (session_index, thread_index);
+
+  /* This comes as a response to a reset, transport only waiting for
+   * confirmation to remove connection state, no need to disconnect */
+  stream_session_cleanup (s);
+}
+
+static void
+vl_api_accept_sock_reply_t_handler (vl_api_accept_sock_reply_t * mp)
+{
+  stream_session_t *s;
+  u32 session_index, thread_index;
+
+  if (api_parse_session_handle (mp->handle, &session_index, &thread_index))
+    {
+      clib_warning ("Invalid handle");
+      return;
+    }
+  s = stream_session_get (session_index, thread_index);
+
+  if (mp->retval)
+    {
+      /* Server isn't interested, kill the session */
+      stream_session_disconnect (s);
+      return;
+    }
+
+  s->session_state = SESSION_STATE_READY;
+}
+
+#define vl_msg_name_crc_list
+#include <vnet/vnet_all_api_h.h>
+#undef vl_msg_name_crc_list
+
+static void
+setup_message_id_table (api_main_t * am)
+{
+#define _(id,n,crc) vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id);
+  foreach_vl_msg_name_crc_session;
+#undef _
+}
+
+/*
+ * session_api_hookup
+ * Add uri's API message handlers to the table.
+ * vlib has alread mapped shared memory and
+ * added the client registration handlers.
+ * See .../open-repo/vlib/memclnt_vlib.c:memclnt_process()
+ */
+static clib_error_t *
+session_api_hookup (vlib_main_t * vm)
+{
+  api_main_t *am = &api_main;
+
+#define _(N,n)                                                  \
+    vl_msg_api_set_handlers(VL_API_##N, #n,                     \
+                           vl_api_##n##_t_handler,              \
+                           vl_noop_handler,                     \
+                           vl_api_##n##_t_endian,               \
+                           vl_api_##n##_t_print,                \
+                           sizeof(vl_api_##n##_t), 1);
+  foreach_session_api_msg;
+#undef _
+
+  /*
+   * Messages which bounce off the data-plane to
+   * an API client. Simply tells the message handling infra not
+   * to free the message.
+   *
+   * Bounced message handlers MUST NOT block the data plane
+   */
+  am->message_bounce[VL_API_CONNECT_URI] = 1;
+  am->message_bounce[VL_API_CONNECT_SOCK] = 1;
+
+  /*
+   * Set up the (msg_name, crc, message-id) table
+   */
+  setup_message_id_table (am);
+
+  return 0;
+}
+
+VLIB_API_INIT_FUNCTION (session_api_hookup);
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/session_cli.c b/src/vnet/session/session_cli.c
new file mode 100644 (file)
index 0000000..b2943a1
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <vnet/session/application.h>
+#include <vnet/session/session.h>
+
+/**
+ * Format stream session as per the following format
+ *
+ * verbose:
+ *   "Connection", "Rx fifo", "Tx fifo", "Session Index"
+ * non-verbose:
+ *   "Connection"
+ */
+u8 *
+format_stream_session (u8 * s, va_list * args)
+{
+  stream_session_t *ss = va_arg (*args, stream_session_t *);
+  int verbose = va_arg (*args, int);
+  transport_proto_vft_t *tp_vft;
+  u8 *str = 0;
+
+  tp_vft = session_get_transport_vft (ss->session_type);
+
+  if (verbose)
+    str = format (0, "%-20llp%-20llp%-15lld", ss->server_rx_fifo,
+                 ss->server_tx_fifo, stream_session_get_index (ss));
+
+  if (ss->session_state == SESSION_STATE_READY)
+    {
+      s = format (s, "%-40U%v", tp_vft->format_connection,
+                 ss->connection_index, ss->thread_index, str);
+    }
+  else if (ss->session_state == SESSION_STATE_LISTENING)
+    {
+      s = format (s, "%-40U%v", tp_vft->format_listener, ss->connection_index,
+                 str);
+    }
+  else if (ss->session_state == SESSION_STATE_READY)
+    {
+      s =
+       format (s, "%-40U%v", tp_vft->format_half_open, ss->connection_index,
+               str);
+    }
+  else if (ss->session_state == SESSION_STATE_CLOSED)
+    {
+      s = format (s, "[CL] %-40U%v", tp_vft->format_connection,
+                 ss->connection_index, ss->thread_index, str);
+    }
+  else
+    {
+      clib_warning ("Session in unknown state!");
+    }
+
+  vec_free (str);
+
+  return s;
+}
+
+static clib_error_t *
+show_session_command_fn (vlib_main_t * vm, unformat_input_t * input,
+                        vlib_cli_command_t * cmd)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  int verbose = 0, i;
+  stream_session_t *pool;
+  stream_session_t *s;
+  u8 *str = 0;
+
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "verbose"))
+       verbose = 1;
+      else
+       break;
+    }
+
+  for (i = 0; i < vec_len (smm->sessions); i++)
+    {
+      u32 once_per_pool;
+      pool = smm->sessions[i];
+
+      once_per_pool = 1;
+
+      if (pool_elts (pool))
+       {
+
+         vlib_cli_output (vm, "Thread %d: %d active sessions",
+                          i, pool_elts (pool));
+         if (verbose)
+           {
+             if (once_per_pool)
+               {
+                 str = format (str, "%-40s%-20s%-20s%-15s",
+                               "Connection", "Rx fifo", "Tx fifo",
+                               "Session Index");
+                 vlib_cli_output (vm, "%v", str);
+                 vec_reset_length (str);
+                 once_per_pool = 0;
+               }
+
+              /* *INDENT-OFF* */
+              pool_foreach (s, pool,
+              ({
+                vlib_cli_output (vm, "%U", format_stream_session, s, verbose);
+              }));
+              /* *INDENT-ON* */
+           }
+       }
+      else
+       vlib_cli_output (vm, "Thread %d: no active sessions", i);
+    }
+  vec_free (str);
+
+  return 0;
+}
+
+VLIB_CLI_COMMAND (show_uri_command, static) =
+{
+.path = "show session",.short_help = "show session [verbose]",.function =
+    show_session_command_fn,};
+
+
+static clib_error_t *
+clear_session_command_fn (vlib_main_t * vm, unformat_input_t * input,
+                         vlib_cli_command_t * cmd)
+{
+  session_manager_main_t *smm = &session_manager_main;
+  u32 thread_index = 0;
+  u32 session_index = ~0;
+  stream_session_t *pool, *session;
+  application_t *server;
+
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "thread %d", &thread_index))
+       ;
+      else if (unformat (input, "session %d", &session_index))
+       ;
+      else
+       return clib_error_return (0, "unknown input `%U'",
+                                 format_unformat_error, input);
+    }
+
+  if (session_index == ~0)
+    return clib_error_return (0, "session <nn> required, but not set.");
+
+  if (thread_index > vec_len (smm->sessions))
+    return clib_error_return (0, "thread %d out of range [0-%d]",
+                             thread_index, vec_len (smm->sessions));
+
+  pool = smm->sessions[thread_index];
+
+  if (pool_is_free_index (pool, session_index))
+    return clib_error_return (0, "session %d not active", session_index);
+
+  session = pool_elt_at_index (pool, session_index);
+  server = application_get (session->app_index);
+
+  /* Disconnect both app and transport */
+  server->cb_fns.session_disconnect_callback (session);
+
+  return 0;
+}
+
+VLIB_CLI_COMMAND (clear_uri_session_command, static) =
+{
+.path = "clear session",.short_help =
+    "clear session thread <thread> session <index>",.function =
+    clear_session_command_fn,};
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/session/transport.c b/src/vnet/session/transport.c
new file mode 100644 (file)
index 0000000..abd94ba
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vnet/session/transport.h>
+
+u32
+transport_endpoint_lookup (transport_endpoint_table_t *ht, ip46_address_t *ip,
+                           u16 port)
+{
+  clib_bihash_kv_24_8_t kv;
+  int rv;
+
+  kv.key[0] = ip->as_u64[0];
+  kv.key[1] = ip->as_u64[1];
+  kv.key[2] = port;
+
+  rv = clib_bihash_search_inline_24_8 (ht, &kv);
+  if (rv == 0)
+    return kv.value;
+
+  return TRANSPORT_ENDPOINT_INVALID_INDEX;
+}
+
+void
+transport_endpoint_table_add (transport_endpoint_table_t *ht,
+                              transport_endpoint_t *te, u32 value)
+{
+  clib_bihash_kv_24_8_t kv;
+
+  kv.key[0] = te->ip.as_u64[0];
+  kv.key[1] = te->ip.as_u64[1];
+  kv.key[2] = te->port;
+  kv.value = value;
+
+  clib_bihash_add_del_24_8 (ht, &kv, 1);
+}
+
+void
+transport_endpoint_table_del (transport_endpoint_table_t *ht,
+                              transport_endpoint_t *te)
+{
+  clib_bihash_kv_24_8_t kv;
+
+  kv.key[0] = te->ip.as_u64[0];
+  kv.key[1] = te->ip.as_u64[1];
+  kv.key[2] = te->port;
+
+  clib_bihash_add_del_24_8 (ht, &kv, 0);
+}
+
+
+
diff --git a/src/vnet/session/transport.h b/src/vnet/session/transport.h
new file mode 100644 (file)
index 0000000..2d4415b
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef VNET_VNET_URI_TRANSPORT_H_
+#define VNET_VNET_URI_TRANSPORT_H_
+
+#include <vnet/vnet.h>
+#include <vnet/ip/ip.h>
+#include <vppinfra/bihash_16_8.h>
+#include <vppinfra/bihash_48_8.h>
+
+/*
+ * Protocol independent transport properties associated to a session
+ */
+typedef struct _transport_connection
+{
+  ip46_address_t rmt_ip;       /**< Remote IP */
+  ip46_address_t lcl_ip;       /**< Local IP */
+  u16 lcl_port;                        /**< Local port */
+  u16 rmt_port;                        /**< Remote port */
+  u8 proto;                    /**< Transport protocol id */
+
+  u32 s_index;                 /**< Parent session index */
+  u32 c_index;                 /**< Connection index in transport pool */
+  u8 is_ip4;                   /**< Flag if IP4 connection */
+  u32 thread_index;            /**< Worker-thread index */
+
+  /** Macros for 'derived classes' where base is named "connection" */
+#define c_lcl_ip connection.lcl_ip
+#define c_rmt_ip connection.rmt_ip
+#define c_lcl_ip4 connection.lcl_ip.ip4
+#define c_rmt_ip4 connection.rmt_ip.ip4
+#define c_lcl_ip6 connection.lcl_ip.ip6
+#define c_rmt_ip6 connection.rmt_ip.ip6
+#define c_lcl_port connection.lcl_port
+#define c_rmt_port connection.rmt_port
+#define c_proto connection.proto
+#define c_state connection.state
+#define c_s_index connection.s_index
+#define c_c_index connection.c_index
+#define c_is_ip4 connection.is_ip4
+#define c_thread_index connection.thread_index
+} transport_connection_t;
+
+/*
+ * Transport protocol virtual function table
+ */
+typedef struct _transport_proto_vft
+{
+  /*
+   * Setup
+   */
+  u32 (*bind) (vlib_main_t *, u32, ip46_address_t *, u16);
+  u32 (*unbind) (vlib_main_t *, u32);
+  int (*open) (ip46_address_t * addr, u16 port_host_byte_order);
+  void (*close) (u32 conn_index, u32 thread_index);
+  void (*cleanup) (u32 conn_index, u32 thread_index);
+
+  /*
+   * Transmission
+   */
+    u32 (*push_header) (transport_connection_t * tconn, vlib_buffer_t * b);
+    u16 (*send_mss) (transport_connection_t * tc);
+    u32 (*send_space) (transport_connection_t * tc);
+    u32 (*rx_fifo_offset) (transport_connection_t * tc);
+
+  /*
+   * Connection retrieval
+   */
+  transport_connection_t *(*get_connection) (u32 conn_idx, u32 thread_idx);
+  transport_connection_t *(*get_listener) (u32 conn_index);
+  transport_connection_t *(*get_half_open) (u32 conn_index);
+
+  /*
+   * Format
+   */
+  u8 *(*format_connection) (u8 * s, va_list * args);
+  u8 *(*format_listener) (u8 * s, va_list * args);
+  u8 *(*format_half_open) (u8 * s, va_list * args);
+
+} transport_proto_vft_t;
+
+/* 16 octets */
+typedef CLIB_PACKED (struct
+                    {
+                    union
+                    {
+                    struct
+                    {
+                    ip4_address_t src; ip4_address_t dst;
+                    u16 src_port;
+                    u16 dst_port;
+                    /* align by making this 4 octets even though its a 1-bit field
+                     * NOTE: avoid key overlap with other transports that use 5 tuples for
+                     * session identification.
+                     */
+                    u32 proto;
+                    };
+                    u64 as_u64[2];
+                    };
+                    }) v4_connection_key_t;
+
+typedef CLIB_PACKED (struct
+                    {
+                    union
+                    {
+                    struct
+                    {
+                    /* 48 octets */
+                    ip6_address_t src; ip6_address_t dst;
+                    u16 src_port;
+                    u16 dst_port; u32 proto; u8 unused_for_now[8];
+                    }; u64 as_u64[6];
+                    };
+                    }) v6_connection_key_t;
+
+typedef clib_bihash_kv_16_8_t session_kv4_t;
+typedef clib_bihash_kv_48_8_t session_kv6_t;
+
+always_inline void
+make_v4_ss_kv (session_kv4_t * kv, ip4_address_t * lcl, ip4_address_t * rmt,
+              u16 lcl_port, u16 rmt_port, u8 proto)
+{
+  v4_connection_key_t key;
+  memset (&key, 0, sizeof (v4_connection_key_t));
+
+  key.src.as_u32 = lcl->as_u32;
+  key.dst.as_u32 = rmt->as_u32;
+  key.src_port = lcl_port;
+  key.dst_port = rmt_port;
+  key.proto = proto;
+
+  kv->key[0] = key.as_u64[0];
+  kv->key[1] = key.as_u64[1];
+  kv->value = ~0ULL;
+}
+
+always_inline void
+make_v4_listener_kv (session_kv4_t * kv, ip4_address_t * lcl, u16 lcl_port,
+                    u8 proto)
+{
+  v4_connection_key_t key;
+  memset (&key, 0, sizeof (v4_connection_key_t));
+
+  key.src.as_u32 = lcl->as_u32;
+  key.dst.as_u32 = 0;
+  key.src_port = lcl_port;
+  key.dst_port = 0;
+  key.proto = proto;
+
+  kv->key[0] = key.as_u64[0];
+  kv->key[1] = key.as_u64[1];
+  kv->value = ~0ULL;
+}
+
+always_inline void
+make_v4_ss_kv_from_tc (session_kv4_t * kv, transport_connection_t * t)
+{
+  return make_v4_ss_kv (kv, &t->lcl_ip.ip4, &t->rmt_ip.ip4, t->lcl_port,
+                       t->rmt_port, t->proto);
+}
+
+always_inline void
+make_v6_ss_kv (session_kv6_t * kv, ip6_address_t * lcl, ip6_address_t * rmt,
+              u16 lcl_port, u16 rmt_port, u8 proto)
+{
+  v6_connection_key_t key;
+  memset (&key, 0, sizeof (v6_connection_key_t));
+
+  key.src.as_u64[0] = lcl->as_u64[0];
+  key.src.as_u64[1] = lcl->as_u64[1];
+  key.dst.as_u64[0] = rmt->as_u64[0];
+  key.dst.as_u64[1] = rmt->as_u64[1];
+  key.src_port = lcl_port;
+  key.dst_port = rmt_port;
+  key.proto = proto;
+
+  kv->key[0] = key.as_u64[0];
+  kv->key[1] = key.as_u64[1];
+  kv->value = ~0ULL;
+}
+
+always_inline void
+make_v6_listener_kv (session_kv6_t * kv, ip6_address_t * lcl, u16 lcl_port,
+                    u8 proto)
+{
+  v6_connection_key_t key;
+  memset (&key, 0, sizeof (v6_connection_key_t));
+
+  key.src.as_u64[0] = lcl->as_u64[0];
+  key.src.as_u64[1] = lcl->as_u64[1];
+  key.dst.as_u64[0] = 0;
+  key.dst.as_u64[1] = 0;
+  key.src_port = lcl_port;
+  key.dst_port = 0;
+  key.proto = proto;
+
+  kv->key[0] = key.as_u64[0];
+  kv->key[1] = key.as_u64[1];
+  kv->value = ~0ULL;
+}
+
+always_inline void
+make_v6_ss_kv_from_tc (session_kv6_t * kv, transport_connection_t * t)
+{
+  make_v6_ss_kv (kv, &t->lcl_ip.ip6, &t->rmt_ip.ip6, t->lcl_port,
+                t->rmt_port, t->proto);
+}
+
+typedef struct _transport_endpoint
+{
+  ip46_address_t ip;
+  u16 port;
+  u8 is_ip4;
+  u32 vrf;
+} transport_endpoint_t;
+
+typedef clib_bihash_24_8_t transport_endpoint_table_t;
+
+#define TRANSPORT_ENDPOINT_INVALID_INDEX ((u32)~0)
+
+u32
+transport_endpoint_lookup (transport_endpoint_table_t * ht,
+                          ip46_address_t * ip, u16 port);
+void transport_endpoint_table_add (transport_endpoint_table_t * ht,
+                                  transport_endpoint_t * te, u32 value);
+void transport_endpoint_table_del (transport_endpoint_table_t * ht,
+                                  transport_endpoint_t * te);
+
+#endif /* VNET_VNET_URI_TRANSPORT_H_ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp.c b/src/vnet/tcp/tcp.c
new file mode 100644 (file)
index 0000000..0f9b709
--- /dev/null
@@ -0,0 +1,708 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vnet/tcp/tcp.h>
+#include <vnet/session/session.h>
+#include <vnet/fib/fib.h>
+#include <math.h>
+
+tcp_main_t tcp_main;
+
+static u32
+tcp_connection_bind (vlib_main_t * vm, u32 session_index, ip46_address_t * ip,
+                    u16 port_host_byte_order, u8 is_ip4)
+{
+  tcp_main_t *tm = &tcp_main;
+  tcp_connection_t *listener;
+
+  pool_get (tm->listener_pool, listener);
+  memset (listener, 0, sizeof (*listener));
+
+  listener->c_c_index = listener - tm->listener_pool;
+  listener->c_lcl_port = clib_host_to_net_u16 (port_host_byte_order);
+
+  if (is_ip4)
+    listener->c_lcl_ip4.as_u32 = ip->ip4.as_u32;
+  else
+    clib_memcpy (&listener->c_lcl_ip6, &ip->ip6, sizeof (ip6_address_t));
+
+  listener->c_s_index = session_index;
+  listener->c_proto = SESSION_TYPE_IP4_TCP;
+  listener->state = TCP_STATE_LISTEN;
+  listener->c_is_ip4 = 1;
+
+  return listener->c_c_index;
+}
+
+u32
+tcp_session_bind_ip4 (vlib_main_t * vm, u32 session_index,
+                     ip46_address_t * ip, u16 port_host_byte_order)
+{
+  return tcp_connection_bind (vm, session_index, ip, port_host_byte_order, 1);
+}
+
+u32
+tcp_session_bind_ip6 (vlib_main_t * vm, u32 session_index,
+                     ip46_address_t * ip, u16 port_host_byte_order)
+{
+  return tcp_connection_bind (vm, session_index, ip, port_host_byte_order, 0);
+
+}
+
+static void
+tcp_session_unbind (u32 listener_index)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  pool_put_index (tm->listener_pool, listener_index);
+}
+
+u32
+tcp_session_unbind_ip4 (vlib_main_t * vm, u32 listener_index)
+{
+  tcp_session_unbind (listener_index);
+  return 0;
+}
+
+u32
+tcp_session_unbind_ip6 (vlib_main_t * vm, u32 listener_index)
+{
+  tcp_session_unbind (listener_index);
+  return 0;
+}
+
+transport_connection_t *
+tcp_session_get_listener (u32 listener_index)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  tcp_connection_t *tc;
+  tc = pool_elt_at_index (tm->listener_pool, listener_index);
+  return &tc->connection;
+}
+
+/**
+ * Cleans up connection state.
+ *
+ * No notifications.
+ */
+void
+tcp_connection_cleanup (tcp_connection_t * tc)
+{
+  tcp_main_t *tm = &tcp_main;
+  u32 tepi;
+  transport_endpoint_t *tep;
+
+  /* Cleanup local endpoint if this was an active connect */
+  tepi = transport_endpoint_lookup (&tm->local_endpoints_table, &tc->c_lcl_ip,
+                                   tc->c_lcl_port);
+
+  /*XXX lock */
+  if (tepi != TRANSPORT_ENDPOINT_INVALID_INDEX)
+    {
+      tep = pool_elt_at_index (tm->local_endpoints, tepi);
+      transport_endpoint_table_del (&tm->local_endpoints_table, tep);
+      pool_put (tm->local_endpoints, tep);
+    }
+
+  /* Make sure all timers are cleared */
+  tcp_connection_timers_reset (tc);
+
+  /* Check if half-open */
+  if (tc->state == TCP_STATE_SYN_SENT)
+    pool_put (tm->half_open_connections, tc);
+  else
+    pool_put (tm->connections[tc->c_thread_index], tc);
+}
+
+/**
+ * Connection removal.
+ *
+ * This should be called only once connection enters CLOSED state. Note
+ * that it notifies the session of the removal event, so if the goal is to
+ * just remove the connection, call tcp_connection_cleanup instead.
+ */
+void
+tcp_connection_del (tcp_connection_t * tc)
+{
+  stream_session_delete_notify (&tc->connection);
+  tcp_connection_cleanup (tc);
+}
+
+/**
+ * Begin connection closing procedure.
+ *
+ * If at the end the connection is not in CLOSED state, it is not removed.
+ * Instead, we rely on on TCP to advance through state machine to either
+ * 1) LAST_ACK (passive close) whereby when the last ACK is received
+ * tcp_connection_del is called. This notifies session of the delete and
+ * calls cleanup.
+ * 2) TIME_WAIT (active close) whereby after 2MSL the 2MSL timer triggers
+ * and cleanup is called.
+ */
+void
+tcp_connection_close (tcp_connection_t * tc)
+{
+  /* Send FIN if needed */
+  if (tc->state == TCP_STATE_ESTABLISHED || tc->state == TCP_STATE_SYN_RCVD
+      || tc->state == TCP_STATE_CLOSE_WAIT)
+    tcp_send_fin (tc);
+
+  /* Switch state */
+  if (tc->state == TCP_STATE_ESTABLISHED || tc->state == TCP_STATE_SYN_RCVD)
+    tc->state = TCP_STATE_FIN_WAIT_1;
+  else if (tc->state == TCP_STATE_SYN_SENT)
+    tc->state = TCP_STATE_CLOSED;
+  else if (tc->state == TCP_STATE_CLOSE_WAIT)
+    tc->state = TCP_STATE_LAST_ACK;
+
+  /* Half-close connections are not supported XXX */
+
+  if (tc->state == TCP_STATE_CLOSED)
+    tcp_connection_del (tc);
+}
+
+void
+tcp_session_close (u32 conn_index, u32 thread_index)
+{
+  tcp_connection_t *tc;
+  tc = tcp_connection_get (conn_index, thread_index);
+  tcp_connection_close (tc);
+}
+
+void
+tcp_session_cleanup (u32 conn_index, u32 thread_index)
+{
+  tcp_connection_t *tc;
+  tc = tcp_connection_get (conn_index, thread_index);
+  tcp_connection_cleanup (tc);
+}
+
+void *
+ip_interface_get_first_ip (u32 sw_if_index, u8 is_ip4)
+{
+  ip_lookup_main_t *lm4 = &ip4_main.lookup_main;
+  ip_lookup_main_t *lm6 = &ip6_main.lookup_main;
+  ip_interface_address_t *ia = 0;
+
+  if (is_ip4)
+    {
+      /* *INDENT-OFF* */
+      foreach_ip_interface_address (lm4, ia, sw_if_index, 1 /* unnumbered */ ,
+      ({
+        return ip_interface_address_get_address (lm4, ia);
+      }));
+      /* *INDENT-ON* */
+    }
+  else
+    {
+      /* *INDENT-OFF* */
+      foreach_ip_interface_address (lm6, ia, sw_if_index, 1 /* unnumbered */ ,
+      ({
+        return ip_interface_address_get_address (lm6, ia);
+      }));
+      /* *INDENT-ON* */
+    }
+
+  return 0;
+}
+
+/**
+ * Allocate local port and add if successful add entry to local endpoint
+ * table to mark the pair as used.
+ */
+u16
+tcp_allocate_local_port (tcp_main_t * tm, ip46_address_t * ip)
+{
+  u8 unique = 0;
+  transport_endpoint_t *tep;
+  u32 time_now, tei;
+  u16 min = 1024, max = 65535, tries;  /* XXX configurable ? */
+
+  tries = max - min;
+  time_now = tcp_time_now ();
+
+  /* Start at random point or max */
+  pool_get (tm->local_endpoints, tep);
+  clib_memcpy (&tep->ip, ip, sizeof (*ip));
+  tep->port = random_u32 (&time_now) << 16;
+  tep->port = tep->port < min ? max : tep->port;
+
+  /* Search for first free slot */
+  while (tries)
+    {
+      tei = transport_endpoint_lookup (&tm->local_endpoints_table, &tep->ip,
+                                      tep->port);
+      if (tei == TRANSPORT_ENDPOINT_INVALID_INDEX)
+       {
+         unique = 1;
+         break;
+       }
+
+      tep->port--;
+
+      if (tep->port < min)
+       tep->port = max;
+
+      tries--;
+    }
+
+  if (unique)
+    {
+      transport_endpoint_table_add (&tm->local_endpoints_table, tep,
+                                   tep - tm->local_endpoints);
+
+      return tep->port;
+    }
+
+  /* Failed */
+  pool_put (tm->local_endpoints, tep);
+  return -1;
+}
+
+/**
+ * Initialize all connection timers as invalid
+ */
+void
+tcp_connection_timers_init (tcp_connection_t * tc)
+{
+  int i;
+
+  /* Set all to invalid */
+  for (i = 0; i < TCP_N_TIMERS; i++)
+    {
+      tc->timers[i] = TCP_TIMER_HANDLE_INVALID;
+    }
+
+  tc->rto = TCP_RTO_INIT;
+}
+
+/**
+ * Stop all connection timers
+ */
+void
+tcp_connection_timers_reset (tcp_connection_t * tc)
+{
+  int i;
+  for (i = 0; i < TCP_N_TIMERS; i++)
+    {
+      tcp_timer_reset (tc, i);
+    }
+}
+
+/** Initialize tcp connection variables
+ *
+ * Should be called after having received a msg from the peer, i.e., a SYN or
+ * a SYNACK, such that connection options have already been exchanged. */
+void
+tcp_connection_init_vars (tcp_connection_t * tc)
+{
+  tcp_connection_timers_init (tc);
+  tcp_set_snd_mss (tc);
+  tc->sack_sb.head = TCP_INVALID_SACK_HOLE_INDEX;
+  tcp_cc_init (tc);
+}
+
+int
+tcp_connection_open (ip46_address_t * rmt_addr, u16 rmt_port, u8 is_ip4)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  tcp_connection_t *tc;
+  fib_prefix_t prefix;
+  u32 fei, sw_if_index;
+  ip46_address_t lcl_addr;
+  u16 lcl_port;
+
+  /*
+   * Find the local address and allocate port
+   */
+  memset (&lcl_addr, 0, sizeof (lcl_addr));
+
+  /* Find a FIB path to the destination */
+  clib_memcpy (&prefix.fp_addr, rmt_addr, sizeof (*rmt_addr));
+  prefix.fp_proto = is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
+  prefix.fp_len = is_ip4 ? 32 : 128;
+
+  fei = fib_table_lookup (0, &prefix);
+
+  /* Couldn't find route to destination. Bail out. */
+  if (fei == FIB_NODE_INDEX_INVALID)
+    return -1;
+
+  sw_if_index = fib_entry_get_resolving_interface (fei);
+
+  if (sw_if_index == (u32) ~ 0)
+    return -1;
+
+  if (is_ip4)
+    {
+      ip4_address_t *ip4;
+      ip4 = ip_interface_get_first_ip (sw_if_index, 1);
+      lcl_addr.ip4.as_u32 = ip4->as_u32;
+    }
+  else
+    {
+      ip6_address_t *ip6;
+      ip6 = ip_interface_get_first_ip (sw_if_index, 0);
+      clib_memcpy (&lcl_addr.ip6, ip6, sizeof (*ip6));
+    }
+
+  /* Allocate source port */
+  lcl_port = tcp_allocate_local_port (tm, &lcl_addr);
+  if (lcl_port < 1)
+    return -1;
+
+  /*
+   * Create connection and send SYN
+   */
+
+  pool_get (tm->half_open_connections, tc);
+  memset (tc, 0, sizeof (*tc));
+
+  clib_memcpy (&tc->c_rmt_ip, rmt_addr, sizeof (ip46_address_t));
+  clib_memcpy (&tc->c_lcl_ip, &lcl_addr, sizeof (ip46_address_t));
+  tc->c_rmt_port = clib_host_to_net_u16 (rmt_port);
+  tc->c_lcl_port = clib_host_to_net_u16 (lcl_port);
+  tc->c_c_index = tc - tm->half_open_connections;
+  tc->c_is_ip4 = is_ip4;
+
+  /* The other connection vars will be initialized after SYN ACK */
+  tcp_connection_timers_init (tc);
+
+  tcp_send_syn (tc);
+
+  tc->state = TCP_STATE_SYN_SENT;
+
+  return tc->c_c_index;
+}
+
+int
+tcp_session_open_ip4 (ip46_address_t * addr, u16 port)
+{
+  return tcp_connection_open (addr, port, 1);
+}
+
+int
+tcp_session_open_ip6 (ip46_address_t * addr, u16 port)
+{
+  return tcp_connection_open (addr, port, 0);
+}
+
+u8 *
+format_tcp_session_ip4 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  u32 thread_index = va_arg (*args, u32);
+  tcp_connection_t *tc;
+
+  tc = tcp_connection_get (tci, thread_index);
+
+  s = format (s, "[%s] %U:%d->%U:%d", "tcp", format_ip4_address,
+             &tc->c_lcl_ip4, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip4_address, &tc->c_rmt_ip4,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+
+  return s;
+}
+
+u8 *
+format_tcp_session_ip6 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  u32 thread_index = va_arg (*args, u32);
+  tcp_connection_t *tc = tcp_connection_get (tci, thread_index);
+  s = format (s, "[%s] %U:%d->%U:%d", "tcp", format_ip6_address,
+             &tc->c_lcl_ip6, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip6_address, &tc->c_rmt_ip6,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+u8 *
+format_tcp_listener_session_ip4 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  tcp_connection_t *tc = tcp_listener_get (tci);
+  s = format (s, "[%s] %U:%d->%U:%d", "tcp", format_ip4_address,
+             &tc->c_lcl_ip4, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip4_address, &tc->c_rmt_ip4,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+u8 *
+format_tcp_listener_session_ip6 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  tcp_connection_t *tc = tcp_listener_get (tci);
+  s = format (s, "[%s] %U:%d->%U:%d", "tcp", format_ip6_address,
+             &tc->c_lcl_ip6, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip6_address, &tc->c_rmt_ip6,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+u8 *
+format_tcp_half_open_session_ip4 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  tcp_connection_t *tc = tcp_half_open_connection_get (tci);
+  s = format (s, "[%s] %U:%d->%U:%d", "tcp", format_ip4_address,
+             &tc->c_lcl_ip4, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip4_address, &tc->c_rmt_ip4,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+u8 *
+format_tcp_half_open_session_ip6 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  tcp_connection_t *tc = tcp_half_open_connection_get (tci);
+  s = format (s, "[%s] %U:%d->%U:%d", "tcp", format_ip6_address,
+             &tc->c_lcl_ip6, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip6_address, &tc->c_rmt_ip6,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+transport_connection_t *
+tcp_session_get_transport (u32 conn_index, u32 thread_index)
+{
+  tcp_connection_t *tc = tcp_connection_get (conn_index, thread_index);
+  return &tc->connection;
+}
+
+transport_connection_t *
+tcp_half_open_session_get_transport (u32 conn_index)
+{
+  tcp_connection_t *tc = tcp_half_open_connection_get (conn_index);
+  return &tc->connection;
+}
+
+u16
+tcp_session_send_mss (transport_connection_t * trans_conn)
+{
+  tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
+  return tc->snd_mss;
+}
+
+u32
+tcp_session_send_space (transport_connection_t * trans_conn)
+{
+  tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
+  return tcp_available_snd_space (tc);
+}
+
+u32
+tcp_session_rx_fifo_offset (transport_connection_t * trans_conn)
+{
+  tcp_connection_t *tc = (tcp_connection_t *) trans_conn;
+  return (tc->snd_una_max - tc->snd_una);
+}
+
+/* *INDENT-OFF* */
+const static transport_proto_vft_t tcp4_proto = {
+  .bind = tcp_session_bind_ip4,
+  .unbind = tcp_session_unbind_ip4,
+  .push_header = tcp_push_header,
+  .get_connection = tcp_session_get_transport,
+  .get_listener = tcp_session_get_listener,
+  .get_half_open = tcp_half_open_session_get_transport,
+  .open = tcp_session_open_ip4,
+  .close = tcp_session_close,
+  .cleanup = tcp_session_cleanup,
+  .send_mss = tcp_session_send_mss,
+  .send_space = tcp_session_send_space,
+  .rx_fifo_offset = tcp_session_rx_fifo_offset,
+  .format_connection = format_tcp_session_ip4,
+  .format_listener = format_tcp_listener_session_ip4,
+  .format_half_open = format_tcp_half_open_session_ip4
+};
+
+const static transport_proto_vft_t tcp6_proto = {
+  .bind = tcp_session_bind_ip6,
+  .unbind = tcp_session_unbind_ip6,
+  .push_header = tcp_push_header,
+  .get_connection = tcp_session_get_transport,
+  .get_listener = tcp_session_get_listener,
+  .get_half_open = tcp_half_open_session_get_transport,
+  .open = tcp_session_open_ip6,
+  .close = tcp_session_close,
+  .cleanup = tcp_session_cleanup,
+  .send_mss = tcp_session_send_mss,
+  .send_space = tcp_session_send_space,
+  .rx_fifo_offset = tcp_session_rx_fifo_offset,
+  .format_connection = format_tcp_session_ip6,
+  .format_listener = format_tcp_listener_session_ip6,
+  .format_half_open = format_tcp_half_open_session_ip6
+};
+/* *INDENT-ON* */
+
+void
+tcp_timer_keep_handler (u32 conn_index)
+{
+  u32 cpu_index = os_get_cpu_number ();
+  tcp_connection_t *tc;
+
+  tc = tcp_connection_get (conn_index, cpu_index);
+  tc->timers[TCP_TIMER_KEEP] = TCP_TIMER_HANDLE_INVALID;
+
+  tcp_connection_close (tc);
+}
+
+void
+tcp_timer_establish_handler (u32 conn_index)
+{
+  tcp_connection_t *tc;
+  u8 sst;
+
+  tc = tcp_half_open_connection_get (conn_index);
+  tc->timers[TCP_TIMER_ESTABLISH] = TCP_TIMER_HANDLE_INVALID;
+
+  ASSERT (tc->state == TCP_STATE_SYN_SENT);
+
+  sst = tc->c_is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
+  stream_session_connect_notify (&tc->connection, sst, 1 /* fail */ );
+
+  tcp_connection_cleanup (tc);
+}
+
+void
+tcp_timer_2msl_handler (u32 conn_index)
+{
+  u32 cpu_index = os_get_cpu_number ();
+  tcp_connection_t *tc;
+
+  tc = tcp_connection_get (conn_index, cpu_index);
+  tc->timers[TCP_TIMER_2MSL] = TCP_TIMER_HANDLE_INVALID;
+
+  tcp_connection_del (tc);
+}
+
+/* *INDENT-OFF* */
+static timer_expiration_handler *timer_expiration_handlers[TCP_N_TIMERS] =
+{
+    tcp_timer_retransmit_handler,
+    tcp_timer_delack_handler,
+    0,
+    tcp_timer_keep_handler,
+    tcp_timer_2msl_handler,
+    tcp_timer_retransmit_syn_handler,
+    tcp_timer_establish_handler
+};
+/* *INDENT-ON* */
+
+static void
+tcp_expired_timers_dispatch (u32 * expired_timers)
+{
+  int i;
+  u32 connection_index, timer_id;
+
+  for (i = 0; i < vec_len (expired_timers); i++)
+    {
+      /* Get session index and timer id */
+      connection_index = expired_timers[i] & 0x0FFFFFFF;
+      timer_id = expired_timers[i] >> 28;
+
+      /* Handle expiration */
+      (*timer_expiration_handlers[timer_id]) (connection_index);
+    }
+}
+
+void
+tcp_initialize_timer_wheels (tcp_main_t * tm)
+{
+  tw_timer_wheel_16t_2w_512sl_t *tw;
+  vec_foreach (tw, tm->timer_wheels)
+  {
+    tw_timer_wheel_init_16t_2w_512sl (tw, tcp_expired_timers_dispatch,
+                                     100e-3 /* timer period 100ms */ , ~0);
+    tw->last_run_time = vlib_time_now (tm->vlib_main);
+  }
+}
+
+clib_error_t *
+tcp_init (vlib_main_t * vm)
+{
+  ip_main_t *im = &ip_main;
+  ip_protocol_info_t *pi;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_thread_main_t *vtm = vlib_get_thread_main ();
+  clib_error_t *error = 0;
+  u32 num_threads;
+
+  tm->vlib_main = vm;
+  tm->vnet_main = vnet_get_main ();
+
+  if ((error = vlib_call_init_function (vm, ip_main_init)))
+    return error;
+  if ((error = vlib_call_init_function (vm, ip4_lookup_init)))
+    return error;
+  if ((error = vlib_call_init_function (vm, ip6_lookup_init)))
+    return error;
+
+  /*
+   * Registrations
+   */
+
+  /* Register with IP */
+  pi = ip_get_protocol_info (im, IP_PROTOCOL_TCP);
+  if (pi == 0)
+    return clib_error_return (0, "TCP protocol info AWOL");
+  pi->format_header = format_tcp_header;
+  pi->unformat_pg_edit = unformat_pg_tcp_header;
+
+  ip4_register_protocol (IP_PROTOCOL_TCP, tcp4_input_node.index);
+
+  /* Register as transport with URI */
+  session_register_transport (SESSION_TYPE_IP4_TCP, &tcp4_proto);
+  session_register_transport (SESSION_TYPE_IP6_TCP, &tcp6_proto);
+
+  /*
+   * Initialize data structures
+   */
+
+  num_threads = 1 /* main thread */  + vtm->n_threads;
+  vec_validate (tm->connections, num_threads - 1);
+
+  /* Initialize per worker thread tx buffers (used for control messages) */
+  vec_validate (tm->tx_buffers, num_threads - 1);
+
+  /* Initialize timer wheels */
+  vec_validate (tm->timer_wheels, num_threads - 1);
+  tcp_initialize_timer_wheels (tm);
+
+  vec_validate (tm->delack_connections, num_threads - 1);
+
+  /* Initialize clocks per tick for TCP timestamp. Used to compute
+   * monotonically increasing timestamps. */
+  tm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
+    / TCP_TSTAMP_RESOLUTION;
+
+  clib_bihash_init_24_8 (&tm->local_endpoints_table, "local endpoint table",
+                        200000 /* $$$$ config parameter nbuckets */ ,
+                        (64 << 20) /*$$$ config parameter table size */ );
+
+  return error;
+}
+
+VLIB_INIT_FUNCTION (tcp_init);
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp.h b/src/vnet/tcp/tcp.h
new file mode 100644 (file)
index 0000000..22f00a6
--- /dev/null
@@ -0,0 +1,624 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _vnet_tcp_h_
+#define _vnet_tcp_h_
+
+#include <vnet/vnet.h>
+#include <vnet/ip/ip.h>
+#include <vnet/tcp/tcp_packet.h>
+#include <vnet/tcp/tcp_timer.h>
+#include <vnet/session/transport.h>
+#include <vnet/session/session.h>
+
+#define TCP_TICK 10e-3                 /**< TCP tick period (s) */
+#define THZ 1/TCP_TICK                 /**< TCP tick frequency */
+#define TCP_TSTAMP_RESOLUTION TCP_TICK /**< Time stamp resolution */
+#define TCP_PAWS_IDLE 24 * 24 * 60 * 60 * THZ /**< 24 days */
+#define TCP_MAX_OPTION_SPACE 40
+
+#define TCP_DUPACK_THRESHOLD 3
+#define TCP_DEFAULT_RX_FIFO_SIZE 64 << 10
+
+/** TCP FSM state definitions as per RFC793. */
+#define foreach_tcp_fsm_state   \
+  _(CLOSED, "CLOSED")           \
+  _(LISTEN, "LISTEN")           \
+  _(SYN_SENT, "SYN_SENT")       \
+  _(SYN_RCVD, "SYN_RCVD")       \
+  _(ESTABLISHED, "ESTABLISHED") \
+  _(CLOSE_WAIT, "CLOSE_WAIT")   \
+  _(FIN_WAIT_1, "FIN_WAIT_1")   \
+  _(LAST_ACK, "LAST_ACK")       \
+  _(CLOSING, "CLOSING")         \
+  _(FIN_WAIT_2, "FIN_WAIT_2")   \
+  _(TIME_WAIT, "TIME_WAIT")
+
+typedef enum _tcp_state
+{
+#define _(sym, str) TCP_STATE_##sym,
+  foreach_tcp_fsm_state
+#undef _
+  TCP_N_STATES
+} tcp_state_t;
+
+format_function_t format_tcp_state;
+
+/** TCP timers */
+#define foreach_tcp_timer               \
+  _(RETRANSMIT, "RETRANSMIT")           \
+  _(DELACK, "DELAYED ACK")              \
+  _(PERSIST, "PERSIST")                 \
+  _(KEEP, "KEEP")                       \
+  _(2MSL, "2MSL")                       \
+  _(RETRANSMIT_SYN, "RETRANSMIT_SYN")   \
+  _(ESTABLISH, "ESTABLISH")
+
+typedef enum _tcp_timers
+{
+#define _(sym, str) TCP_TIMER_##sym,
+  foreach_tcp_timer
+#undef _
+  TCP_N_TIMERS
+} tcp_timers_e;
+
+typedef void (timer_expiration_handler) (u32 index);
+
+extern timer_expiration_handler tcp_timer_delack_handler;
+extern timer_expiration_handler tcp_timer_retransmit_handler;
+extern timer_expiration_handler tcp_timer_retransmit_syn_handler;
+
+#define TCP_TIMER_HANDLE_INVALID ((u32) ~0)
+
+/* Timer delays as multiples of 100ms */
+#define TCP_TO_TIMER_TICK       TCP_TICK*10    /* Period for converting from TCP
+                                                * ticks to timer units */
+#define TCP_DELACK_TIME         1      /* 0.1s */
+#define TCP_ESTABLISH_TIME      750    /* 75s */
+#define TCP_2MSL_TIME           300    /* 30s */
+
+#define TCP_RTO_MAX 60 * THZ   /* Min max RTO (60s) as per RFC6298 */
+#define TCP_RTT_MAX 30 * THZ   /* 30s (probably too much) */
+#define TCP_RTO_SYN_RETRIES 3  /* SYN retries without doubling RTO */
+#define TCP_RTO_INIT 1 * THZ   /* Initial retransmit timer */
+
+void tcp_update_time (f64 now, u32 thread_index);
+
+/** TCP connection flags */
+#define foreach_tcp_connection_flag             \
+  _(DELACK, "Delay ACK")                        \
+  _(SNDACK, "Send ACK")                         \
+  _(BURSTACK, "Burst ACK set")                  \
+  _(SENT_RCV_WND0, "Sent 0 receive window")     \
+  _(RECOVERY, "Recovery on")                    \
+  _(FAST_RECOVERY, "Fast Recovery on")
+
+typedef enum _tcp_connection_flag_bits
+{
+#define _(sym, str) TCP_CONN_##sym##_BIT,
+  foreach_tcp_connection_flag
+#undef _
+  TCP_CONN_N_FLAG_BITS
+} tcp_connection_flag_bits_e;
+
+typedef enum _tcp_connection_flag
+{
+#define _(sym, str) TCP_CONN_##sym = 1 << TCP_CONN_##sym##_BIT,
+  foreach_tcp_connection_flag
+#undef _
+  TCP_CONN_N_FLAGS
+} tcp_connection_flags_e;
+
+/** TCP buffer flags */
+#define foreach_tcp_buf_flag                            \
+  _ (ACK)       /**< Sending ACK. */                    \
+  _ (DUPACK)    /**< Sending DUPACK. */                 \
+
+enum
+{
+#define _(f) TCP_BUF_BIT_##f,
+  foreach_tcp_buf_flag
+#undef _
+    TCP_N_BUF_BITS,
+};
+
+enum
+{
+#define _(f) TCP_BUF_FLAG_##f = 1 << TCP_BUF_BIT_##f,
+  foreach_tcp_buf_flag
+#undef _
+};
+
+#define TCP_MAX_SACK_BLOCKS 5  /**< Max number of SACK blocks stored */
+#define TCP_INVALID_SACK_HOLE_INDEX ((u32)~0)
+
+typedef struct _sack_scoreboard_hole
+{
+  u32 next;            /**< Index for next entry in linked list */
+  u32 prev;            /**< Index for previous entry in linked list */
+  u32 start;           /**< Start sequence number */
+  u32 end;             /**< End sequence number */
+} sack_scoreboard_hole_t;
+
+typedef struct _sack_scoreboard
+{
+  sack_scoreboard_hole_t *holes;       /**< Pool of holes */
+  u32 head;                            /**< Index to first entry */
+  u32 sacked_bytes;                    /**< Number of bytes sacked in sb */
+} sack_scoreboard_t;
+
+typedef enum _tcp_cc_algorithm_type
+{
+  TCP_CC_NEWRENO,
+} tcp_cc_algorithm_type_e;
+
+typedef struct _tcp_cc_algorithm tcp_cc_algorithm_t;
+
+typedef enum _tcp_cc_ack_t
+{
+  TCP_CC_ACK,
+  TCP_CC_DUPACK,
+  TCP_CC_PARTIALACK
+} tcp_cc_ack_t;
+
+typedef struct _tcp_connection
+{
+  transport_connection_t connection;  /**< Common transport data. First! */
+
+  u8 state;                    /**< TCP state as per tcp_state_t */
+  u16 flags;                   /**< Connection flags (see tcp_conn_flags_e) */
+  u32 timers[TCP_N_TIMERS];    /**< Timer handles into timer wheel */
+
+  /* TODO RFC4898 */
+
+  /** Send sequence variables RFC793 */
+  u32 snd_una;         /**< oldest unacknowledged sequence number */
+  u32 snd_una_max;     /**< newest unacknowledged sequence number + 1*/
+  u32 snd_wnd;         /**< send window */
+  u32 snd_wl1;         /**< seq number used for last snd.wnd update */
+  u32 snd_wl2;         /**< ack number used for last snd.wnd update */
+  u32 snd_nxt;         /**< next seq number to be sent */
+
+  /** Receive sequence variables RFC793 */
+  u32 rcv_nxt;         /**< next sequence number expected */
+  u32 rcv_wnd;         /**< receive window we expect */
+
+  u32 rcv_las;         /**< rcv_nxt at last ack sent/rcv_wnd update */
+  u32 iss;             /**< initial sent sequence */
+  u32 irs;             /**< initial remote sequence */
+
+  /* Options */
+  tcp_options_t opt;   /**< TCP connection options parsed */
+  u8 rcv_wscale;       /**< Window scale to advertise to peer */
+  u8 snd_wscale;       /**< Window scale to use when sending */
+  u32 tsval_recent;    /**< Last timestamp received */
+  u32 tsval_recent_age;        /**< When last updated tstamp_recent*/
+
+  sack_block_t *snd_sacks;     /**< Vector of SACKs to send. XXX Fixed size? */
+  sack_scoreboard_t sack_sb;   /**< SACK "scoreboard" that tracks holes */
+
+  u8 rcv_dupacks;      /**< Number of DUPACKs received */
+  u8 snt_dupacks;      /**< Number of DUPACKs sent in a burst */
+
+  /* Congestion control */
+  u32 cwnd;            /**< Congestion window */
+  u32 ssthresh;                /**< Slow-start threshold */
+  u32 prev_ssthresh;   /**< ssthresh before congestion */
+  u32 bytes_acked;     /**< Bytes acknowledged by current segment */
+  u32 rtx_bytes;       /**< Retransmitted bytes */
+  u32 tsecr_last_ack;  /**< Timestamp echoed to us in last health ACK */
+  tcp_cc_algorithm_t *cc_algo; /**< Congestion control algorithm */
+
+  /* RTT and RTO */
+  u32 rto;             /**< Retransmission timeout */
+  u32 rto_boff;                /**< Index for RTO backoff */
+  u32 srtt;            /**< Smoothed RTT */
+  u32 rttvar;          /**< Smoothed mean RTT difference. Approximates variance */
+  u32 rtt_ts;          /**< Timestamp for tracked ACK */
+  u32 rtt_seq;         /**< Sequence number for tracked ACK */
+
+  u16 snd_mss;         /**< Send MSS */
+} tcp_connection_t;
+
+struct _tcp_cc_algorithm
+{
+  void (*rcv_ack) (tcp_connection_t * tc);
+  void (*rcv_cong_ack) (tcp_connection_t * tc, tcp_cc_ack_t ack);
+  void (*congestion) (tcp_connection_t * tc);
+  void (*recovered) (tcp_connection_t * tc);
+  void (*init) (tcp_connection_t * tc);
+};
+
+#define tcp_fastrecovery_on(tc) (tc)->flags |= TCP_CONN_FAST_RECOVERY
+#define tcp_fastrecovery_off(tc) (tc)->flags &= ~TCP_CONN_FAST_RECOVERY
+#define tcp_in_fastrecovery(tc) ((tc)->flags & TCP_CONN_FAST_RECOVERY)
+#define tcp_in_recovery(tc) ((tc)->flags & (TCP_CONN_FAST_RECOVERY | TCP_CONN_RECOVERY))
+#define tcp_recovery_off(tc) ((tc)->flags &= ~(TCP_CONN_FAST_RECOVERY | TCP_CONN_RECOVERY))
+#define tcp_in_slowstart(tc) (tc->cwnd < tc->ssthresh)
+
+typedef enum
+{
+  TCP_IP4,
+  TCP_IP6,
+  TCP_N_AF,
+} tcp_af_t;
+
+typedef enum _tcp_error
+{
+#define tcp_error(n,s) TCP_ERROR_##n,
+#include <vnet/tcp/tcp_error.def>
+#undef tcp_error
+  TCP_N_ERROR,
+} tcp_error_t;
+
+typedef struct _tcp_lookup_dispatch
+{
+  u8 next, error;
+} tcp_lookup_dispatch_t;
+
+typedef struct _tcp_main
+{
+  /* Per-worker thread tcp connection pools */
+  tcp_connection_t **connections;
+
+  /* Pool of listeners. */
+  tcp_connection_t *listener_pool;
+
+  /** Dispatch table by state and flags */
+  tcp_lookup_dispatch_t dispatch_table[TCP_N_STATES][64];
+
+  u8 log2_tstamp_clocks_per_tick;
+  f64 tstamp_ticks_per_clock;
+
+  /** per-worker tx buffer free lists */
+  u32 **tx_buffers;
+
+  /* Per worker-thread timer wheel for connections timers */
+  tw_timer_wheel_16t_2w_512sl_t *timer_wheels;
+
+  /* Convenience per worker-thread vector of connections to DELACK */
+  u32 **delack_connections;
+
+  /* Pool of half-open connections on which we've sent a SYN */
+  tcp_connection_t *half_open_connections;
+
+  /* Pool of local TCP endpoints */
+  transport_endpoint_t *local_endpoints;
+
+  /* Local endpoints lookup table */
+  transport_endpoint_table_t local_endpoints_table;
+
+  /* Congestion control algorithms registered */
+  tcp_cc_algorithm_t *cc_algos;
+
+  /* convenience */
+  vlib_main_t *vlib_main;
+  vnet_main_t *vnet_main;
+  ip4_main_t *ip4_main;
+  ip6_main_t *ip6_main;
+} tcp_main_t;
+
+extern tcp_main_t tcp_main;
+extern vlib_node_registration_t tcp4_input_node;
+extern vlib_node_registration_t tcp6_input_node;
+extern vlib_node_registration_t tcp4_output_node;
+extern vlib_node_registration_t tcp6_output_node;
+
+always_inline tcp_main_t *
+vnet_get_tcp_main ()
+{
+  return &tcp_main;
+}
+
+always_inline tcp_connection_t *
+tcp_connection_get (u32 conn_index, u32 thread_index)
+{
+  return pool_elt_at_index (tcp_main.connections[thread_index], conn_index);
+}
+
+always_inline tcp_connection_t *
+tcp_connection_get_if_valid (u32 conn_index, u32 thread_index)
+{
+  if (tcp_main.connections[thread_index] == 0)
+    return 0;
+  if (pool_is_free_index (tcp_main.connections[thread_index], conn_index))
+    return 0;
+  return pool_elt_at_index (tcp_main.connections[thread_index], conn_index);
+}
+
+void tcp_connection_close (tcp_connection_t * tc);
+void tcp_connection_cleanup (tcp_connection_t * tc);
+void tcp_connection_del (tcp_connection_t * tc);
+
+always_inline tcp_connection_t *
+tcp_listener_get (u32 tli)
+{
+  return pool_elt_at_index (tcp_main.listener_pool, tli);
+}
+
+always_inline tcp_connection_t *
+tcp_half_open_connection_get (u32 conn_index)
+{
+  return pool_elt_at_index (tcp_main.half_open_connections, conn_index);
+}
+
+void tcp_make_ack (tcp_connection_t * ts, vlib_buffer_t * b);
+void tcp_make_finack (tcp_connection_t * tc, vlib_buffer_t * b);
+void tcp_make_synack (tcp_connection_t * ts, vlib_buffer_t * b);
+void tcp_send_reset (vlib_buffer_t * pkt, u8 is_ip4);
+void tcp_send_syn (tcp_connection_t * tc);
+void tcp_send_fin (tcp_connection_t * tc);
+void tcp_set_snd_mss (tcp_connection_t * tc);
+
+always_inline u32
+tcp_end_seq (tcp_header_t * th, u32 len)
+{
+  return th->seq_number + tcp_is_syn (th) + tcp_is_fin (th) + len;
+}
+
+/* Modulo arithmetic for TCP sequence numbers */
+#define seq_lt(_s1, _s2) ((i32)((_s1)-(_s2)) < 0)
+#define seq_leq(_s1, _s2) ((i32)((_s1)-(_s2)) <= 0)
+#define seq_gt(_s1, _s2) ((i32)((_s1)-(_s2)) > 0)
+#define seq_geq(_s1, _s2) ((i32)((_s1)-(_s2)) >= 0)
+
+/* Modulo arithmetic for timestamps */
+#define timestamp_lt(_t1, _t2) ((i32)((_t1)-(_t2)) < 0)
+#define timestamp_leq(_t1, _t2) ((i32)((_t1)-(_t2)) <= 0)
+
+always_inline u32
+tcp_flight_size (const tcp_connection_t * tc)
+{
+  return tc->snd_una_max - tc->snd_una - tc->sack_sb.sacked_bytes
+    + tc->rtx_bytes;
+}
+
+/**
+ * Initial cwnd as per RFC5681
+ */
+always_inline u32
+tcp_initial_cwnd (const tcp_connection_t * tc)
+{
+  if (tc->snd_mss > 2190)
+    return 2 * tc->snd_mss;
+  else if (tc->snd_mss > 1095)
+    return 3 * tc->snd_mss;
+  else
+    return 4 * tc->snd_mss;
+}
+
+always_inline u32
+tcp_loss_wnd (const tcp_connection_t * tc)
+{
+  return tc->snd_mss;
+}
+
+always_inline u32
+tcp_available_wnd (const tcp_connection_t * tc)
+{
+  return clib_min (tc->cwnd, tc->snd_wnd);
+}
+
+always_inline u32
+tcp_available_snd_space (const tcp_connection_t * tc)
+{
+  u32 available_wnd = tcp_available_wnd (tc);
+  u32 flight_size = tcp_flight_size (tc);
+
+  if (available_wnd <= flight_size)
+    return 0;
+
+  return available_wnd - flight_size;
+}
+
+void tcp_retransmit_first_unacked (tcp_connection_t * tc);
+
+void tcp_fast_retransmit (tcp_connection_t * tc);
+
+always_inline u32
+tcp_time_now (void)
+{
+  return clib_cpu_time_now () * tcp_main.tstamp_ticks_per_clock;
+}
+
+u32 tcp_push_header (transport_connection_t * tconn, vlib_buffer_t * b);
+
+u32
+tcp_prepare_retransmit_segment (tcp_connection_t * tc, vlib_buffer_t * b,
+                               u32 max_bytes);
+
+void tcp_connection_timers_init (tcp_connection_t * tc);
+void tcp_connection_timers_reset (tcp_connection_t * tc);
+
+void tcp_connection_init_vars (tcp_connection_t * tc);
+
+always_inline void
+tcp_connection_force_ack (tcp_connection_t * tc, vlib_buffer_t * b)
+{
+  /* Reset flags, make sure ack is sent */
+  tc->flags = TCP_CONN_SNDACK;
+  vnet_buffer (b)->tcp.flags &= ~TCP_BUF_FLAG_DUPACK;
+}
+
+always_inline void
+tcp_timer_set (tcp_connection_t * tc, u8 timer_id, u32 interval)
+{
+  tc->timers[timer_id]
+    = tw_timer_start_16t_2w_512sl (&tcp_main.timer_wheels[tc->c_thread_index],
+                                  tc->c_c_index, timer_id, interval);
+}
+
+always_inline void
+tcp_retransmit_timer_set (tcp_main_t * tm, tcp_connection_t * tc)
+{
+  /* XXX Switch to faster TW */
+  tcp_timer_set (tc, TCP_TIMER_RETRANSMIT,
+                clib_max (tc->rto * TCP_TO_TIMER_TICK, 1));
+}
+
+always_inline void
+tcp_timer_reset (tcp_connection_t * tc, u8 timer_id)
+{
+  if (tc->timers[timer_id] == TCP_TIMER_HANDLE_INVALID)
+    return;
+
+  tw_timer_stop_16t_2w_512sl (&tcp_main.timer_wheels[tc->c_thread_index],
+                             tc->timers[timer_id]);
+  tc->timers[timer_id] = TCP_TIMER_HANDLE_INVALID;
+}
+
+always_inline void
+tcp_timer_update (tcp_connection_t * tc, u8 timer_id, u32 interval)
+{
+  if (tc->timers[timer_id] != TCP_TIMER_HANDLE_INVALID)
+    tw_timer_stop_16t_2w_512sl (&tcp_main.timer_wheels[tc->c_thread_index],
+                               tc->timers[timer_id]);
+  tc->timers[timer_id] =
+    tw_timer_start_16t_2w_512sl (&tcp_main.timer_wheels[tc->c_thread_index],
+                                tc->c_c_index, timer_id, interval);
+}
+
+always_inline u8
+tcp_timer_is_active (tcp_connection_t * tc, tcp_timers_e timer)
+{
+  return tc->timers[timer] != TCP_TIMER_HANDLE_INVALID;
+}
+
+void
+scoreboard_remove_hole (sack_scoreboard_t * sb,
+                       sack_scoreboard_hole_t * hole);
+
+always_inline sack_scoreboard_hole_t *
+scoreboard_next_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * hole)
+{
+  if (hole->next != TCP_INVALID_SACK_HOLE_INDEX)
+    return pool_elt_at_index (sb->holes, hole->next);
+  return 0;
+}
+
+always_inline sack_scoreboard_hole_t *
+scoreboard_first_hole (sack_scoreboard_t * sb)
+{
+  if (sb->head != TCP_INVALID_SACK_HOLE_INDEX)
+    return pool_elt_at_index (sb->holes, sb->head);
+  return 0;
+}
+
+always_inline void
+scoreboard_clear (sack_scoreboard_t * sb)
+{
+  sack_scoreboard_hole_t *hole = scoreboard_first_hole (sb);
+  while ((hole = scoreboard_first_hole (sb)))
+    {
+      scoreboard_remove_hole (sb, hole);
+    }
+}
+
+always_inline u32
+scoreboard_hole_bytes (sack_scoreboard_hole_t * hole)
+{
+  return hole->end - hole->start;
+}
+
+always_inline void
+tcp_cc_algo_register (tcp_cc_algorithm_type_e type,
+                     const tcp_cc_algorithm_t * vft)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vec_validate (tm->cc_algos, type);
+
+  tm->cc_algos[type] = *vft;
+}
+
+always_inline tcp_cc_algorithm_t *
+tcp_cc_algo_get (tcp_cc_algorithm_type_e type)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  return &tm->cc_algos[type];
+}
+
+void tcp_cc_init (tcp_connection_t * tc);
+
+/**
+ * Push TCP header to buffer
+ *
+ * @param vm - vlib_main
+ * @param b - buffer to write the header to
+ * @param sp_net - source port net order
+ * @param dp_net - destination port net order
+ * @param seq - sequence number net order
+ * @param ack - ack number net order
+ * @param tcp_hdr_opts_len - header and options length in bytes
+ * @param flags - header flags
+ * @param wnd - window size
+ *
+ * @return - pointer to start of TCP header
+ */
+always_inline void *
+vlib_buffer_push_tcp_net_order (vlib_buffer_t * b, u16 sp, u16 dp, u32 seq,
+                               u32 ack, u8 tcp_hdr_opts_len, u8 flags,
+                               u16 wnd)
+{
+  tcp_header_t *th;
+
+  th = vlib_buffer_push_uninit (b, tcp_hdr_opts_len);
+
+  th->src_port = sp;
+  th->dst_port = dp;
+  th->seq_number = seq;
+  th->ack_number = ack;
+  th->data_offset_and_reserved = (tcp_hdr_opts_len >> 2) << 4;
+  th->flags = flags;
+  th->window = wnd;
+  th->checksum = 0;
+  th->urgent_pointer = 0;
+  return th;
+}
+
+/**
+ * Push TCP header to buffer
+ *
+ * @param vm - vlib_main
+ * @param b - buffer to write the header to
+ * @param sp_net - source port net order
+ * @param dp_net - destination port net order
+ * @param seq - sequence number host order
+ * @param ack - ack number host order
+ * @param tcp_hdr_opts_len - header and options length in bytes
+ * @param flags - header flags
+ * @param wnd - window size
+ *
+ * @return - pointer to start of TCP header
+ */
+always_inline void *
+vlib_buffer_push_tcp (vlib_buffer_t * b, u16 sp_net, u16 dp_net, u32 seq,
+                     u32 ack, u8 tcp_hdr_opts_len, u8 flags, u16 wnd)
+{
+  return vlib_buffer_push_tcp_net_order (b, sp_net, dp_net,
+                                        clib_host_to_net_u32 (seq),
+                                        clib_host_to_net_u32 (ack),
+                                        tcp_hdr_opts_len, flags,
+                                        clib_host_to_net_u16 (wnd));
+}
+
+#endif /* _vnet_tcp_h_ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp_error.def b/src/vnet/tcp/tcp_error.def
new file mode 100644 (file)
index 0000000..cff5ec1
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+tcp_error (NONE, "no error")
+tcp_error (NO_LISTENER, "no listener for dst port")
+tcp_error (LOOKUP_DROPS, "lookup drops")
+tcp_error (DISPATCH, "Dispatch error")
+tcp_error (ENQUEUED, "Packets pushed into rx fifo")                              
+tcp_error (PURE_ACK, "Pure acks")
+tcp_error (SYNS_RCVD, "SYNs received")
+tcp_error (SYN_ACKS_RCVD, "SYN-ACKs received")
+tcp_error (NOT_READY, "Session not ready for packets")                               
+tcp_error (FIFO_FULL, "Packets dropped for lack of rx fifo space")               
+tcp_error (EVENT_FIFO_FULL, "Events not sent for lack of event fifo space")      
+tcp_error (API_QUEUE_FULL, "Sessions not created for lack of API queue space")
+tcp_error (CREATE_SESSION_FAIL, "Sessions couldn't be allocated")
+tcp_error (SEGMENT_INVALID, "Invalid segment")
+tcp_error (ACK_INVALID, "Invalid ACK")
+tcp_error (ACK_DUP, "Duplicate ACK")
+tcp_error (ACK_OLD, "Old ACK")
+tcp_error (PKTS_SENT, "Packets sent")
+tcp_error (FILTERED_DUPACKS, "Filtered duplicate ACKs")
+tcp_error (RST_SENT, "Resets sent")
\ No newline at end of file
diff --git a/src/vnet/tcp/tcp_format.c b/src/vnet/tcp/tcp_format.c
new file mode 100644 (file)
index 0000000..7136741
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2015 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * tcp/tcp_format.c: tcp formatting
+ *
+ * Copyright (c) 2008 Eliot Dresselhaus
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <vnet/ip/ip.h>
+#include <vnet/tcp/tcp.h>
+
+static u8 *
+format_tcp_flags (u8 * s, va_list * args)
+{
+  int flags = va_arg (*args, int);
+
+#define _(f) if (flags & TCP_FLAG_##f) s = format (s, "%s, ", #f);
+  foreach_tcp_flag
+#undef _
+    return s;
+}
+
+/* Format TCP header. */
+u8 *
+format_tcp_header (u8 * s, va_list * args)
+{
+  tcp_header_t *tcp = va_arg (*args, tcp_header_t *);
+  u32 max_header_bytes = va_arg (*args, u32);
+  u32 header_bytes;
+  uword indent;
+
+  /* Nothing to do. */
+  if (max_header_bytes < sizeof (tcp[0]))
+    return format (s, "TCP header truncated");
+
+  indent = format_get_indent (s);
+  indent += 2;
+  header_bytes = tcp_header_bytes (tcp);
+
+  s = format (s, "TCP: %d -> %d", clib_net_to_host_u16 (tcp->src),
+             clib_net_to_host_u16 (tcp->dst));
+
+  s = format (s, "\n%Useq. 0x%08x ack 0x%08x", format_white_space, indent,
+             clib_net_to_host_u32 (tcp->seq_number),
+             clib_net_to_host_u32 (tcp->ack_number));
+
+  s = format (s, "\n%Uflags %U, tcp header: %d bytes", format_white_space,
+             indent, format_tcp_flags, tcp->flags, header_bytes);
+
+  s = format (s, "\n%Uwindow %d, checksum 0x%04x", format_white_space, indent,
+             clib_net_to_host_u16 (tcp->window),
+             clib_net_to_host_u16 (tcp->checksum));
+
+
+#if 0
+  /* Format TCP options. */
+  {
+    u8 *o;
+    u8 *option_start = (void *) (tcp + 1);
+    u8 *option_end = (void *) tcp + header_bytes;
+
+    for (o = option_start; o < option_end;)
+      {
+       u32 length = o[1];
+       switch (o[0])
+         {
+         case TCP_OPTION_END:
+           length = 1;
+           o = option_end;
+           break;
+
+         case TCP_OPTION_NOOP:
+           length = 1;
+           break;
+
+         }
+      }
+  }
+#endif
+
+  /* Recurse into next protocol layer. */
+  if (max_header_bytes != 0 && header_bytes < max_header_bytes)
+    {
+      ip_main_t *im = &ip_main;
+      tcp_udp_port_info_t *pi;
+
+      pi = ip_get_tcp_udp_port_info (im, tcp->dst);
+
+      if (pi && pi->format_header)
+       s = format (s, "\n%U%U", format_white_space, indent - 2,
+                   pi->format_header,
+                   /* next protocol header */ (void *) tcp + header_bytes,
+                   max_header_bytes - header_bytes);
+    }
+
+  return s;
+}
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp_input.c b/src/vnet/tcp/tcp_input.c
new file mode 100644 (file)
index 0000000..daa0683
--- /dev/null
@@ -0,0 +1,2316 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vppinfra/sparse_vec.h>
+#include <vnet/tcp/tcp_packet.h>
+#include <vnet/tcp/tcp.h>
+#include <vnet/session/session.h>
+#include <math.h>
+
+static char *tcp_error_strings[] = {
+#define tcp_error(n,s) s,
+#include <vnet/tcp/tcp_error.def>
+#undef tcp_error
+};
+
+/* All TCP nodes have the same outgoing arcs */
+#define foreach_tcp_state_next                  \
+  _ (DROP, "error-drop")                        \
+  _ (TCP4_OUTPUT, "tcp4-output")                \
+  _ (TCP6_OUTPUT, "tcp6-output")
+
+typedef enum _tcp_established_next
+{
+#define _(s,n) TCP_ESTABLISHED_NEXT_##s,
+  foreach_tcp_state_next
+#undef _
+    TCP_ESTABLISHED_N_NEXT,
+} tcp_established_next_t;
+
+typedef enum _tcp_rcv_process_next
+{
+#define _(s,n) TCP_RCV_PROCESS_NEXT_##s,
+  foreach_tcp_state_next
+#undef _
+    TCP_RCV_PROCESS_N_NEXT,
+} tcp_rcv_process_next_t;
+
+typedef enum _tcp_syn_sent_next
+{
+#define _(s,n) TCP_SYN_SENT_NEXT_##s,
+  foreach_tcp_state_next
+#undef _
+    TCP_SYN_SENT_N_NEXT,
+} tcp_syn_sent_next_t;
+
+typedef enum _tcp_listen_next
+{
+#define _(s,n) TCP_LISTEN_NEXT_##s,
+  foreach_tcp_state_next
+#undef _
+    TCP_LISTEN_N_NEXT,
+} tcp_listen_next_t;
+
+/* Generic, state independent indices */
+typedef enum _tcp_state_next
+{
+#define _(s,n) TCP_NEXT_##s,
+  foreach_tcp_state_next
+#undef _
+    TCP_STATE_N_NEXT,
+} tcp_state_next_t;
+
+#define tcp_next_output(is_ip4) (is_ip4 ? TCP_NEXT_TCP4_OUTPUT          \
+                                        : TCP_NEXT_TCP6_OUTPUT)
+
+vlib_node_registration_t tcp4_established_node;
+vlib_node_registration_t tcp6_established_node;
+
+/**
+ * Validate segment sequence number. As per RFC793:
+ *
+ * Segment Receive Test
+ *      Length  Window
+ *      ------- -------  -------------------------------------------
+ *      0       0       SEG.SEQ = RCV.NXT
+ *      0       >0      RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
+ *      >0      0       not acceptable
+ *      >0      >0      RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
+ *                      or RCV.NXT =< SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND
+ *
+ * This ultimately consists in checking if segment falls within the window.
+ * The one important difference compared to RFC793 is that we use rcv_las,
+ * or the rcv_nxt at last ack sent instead of rcv_nxt since that's the
+ * peer's reference when computing our receive window.
+ *
+ * This accepts only segments within the window.
+ */
+always_inline u8
+tcp_segment_in_rcv_wnd (tcp_connection_t * tc, u32 seq, u32 end_seq)
+{
+  return seq_leq (end_seq, tc->rcv_las + tc->rcv_wnd)
+    && seq_geq (seq, tc->rcv_nxt);
+}
+
+void
+tcp_options_parse (tcp_header_t * th, tcp_options_t * to)
+{
+  const u8 *data;
+  u8 opt_len, opts_len, kind;
+  int j;
+  sack_block_t b;
+
+  opts_len = (tcp_doff (th) << 2) - sizeof (tcp_header_t);
+  data = (const u8 *) (th + 1);
+
+  /* Zero out all flags but those set in SYN */
+  to->flags &= (TCP_OPTS_FLAG_SACK_PERMITTED | TCP_OPTS_FLAG_WSCALE);
+
+  for (; opts_len > 0; opts_len -= opt_len, data += opt_len)
+    {
+      kind = data[0];
+
+      /* Get options length */
+      if (kind == TCP_OPTION_EOL)
+       break;
+      else if (kind == TCP_OPTION_NOOP)
+       opt_len = 1;
+      else
+       {
+         /* broken options */
+         if (opts_len < 2)
+           break;
+         opt_len = data[1];
+
+         /* weird option length */
+         if (opt_len < 2 || opt_len > opts_len)
+           break;
+       }
+
+      /* Parse options */
+      switch (kind)
+       {
+       case TCP_OPTION_MSS:
+         if ((opt_len == TCP_OPTION_LEN_MSS) && tcp_syn (th))
+           {
+             to->flags |= TCP_OPTS_FLAG_MSS;
+             to->mss = clib_net_to_host_u16 (*(u16 *) (data + 2));
+           }
+         break;
+       case TCP_OPTION_WINDOW_SCALE:
+         if ((opt_len == TCP_OPTION_LEN_WINDOW_SCALE) && tcp_syn (th))
+           {
+             to->flags |= TCP_OPTS_FLAG_WSCALE;
+             to->wscale = data[2];
+             if (to->wscale > TCP_MAX_WND_SCALE)
+               {
+                 clib_warning ("Illegal window scaling value: %d",
+                               to->wscale);
+                 to->wscale = TCP_MAX_WND_SCALE;
+               }
+           }
+         break;
+       case TCP_OPTION_TIMESTAMP:
+         if (opt_len == TCP_OPTION_LEN_TIMESTAMP)
+           {
+             to->flags |= TCP_OPTS_FLAG_TSTAMP;
+             to->tsval = clib_net_to_host_u32 (*(u32 *) (data + 2));
+             to->tsecr = clib_net_to_host_u32 (*(u32 *) (data + 6));
+           }
+         break;
+       case TCP_OPTION_SACK_PERMITTED:
+         if (opt_len == TCP_OPTION_LEN_SACK_PERMITTED && tcp_syn (th))
+           to->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
+         break;
+       case TCP_OPTION_SACK_BLOCK:
+         /* If SACK permitted was not advertised or a SYN, break */
+         if ((to->flags & TCP_OPTS_FLAG_SACK_PERMITTED) == 0 || tcp_syn (th))
+           break;
+
+         /* If too short or not correctly formatted, break */
+         if (opt_len < 10 || ((opt_len - 2) % TCP_OPTION_LEN_SACK_BLOCK))
+           break;
+
+         to->flags |= TCP_OPTS_FLAG_SACK;
+         to->n_sack_blocks = (opt_len - 2) / TCP_OPTION_LEN_SACK_BLOCK;
+         vec_reset_length (to->sacks);
+         for (j = 0; j < to->n_sack_blocks; j++)
+           {
+             b.start = clib_net_to_host_u32 (*(u32 *) (data + 2 + 4 * j));
+             b.end = clib_net_to_host_u32 (*(u32 *) (data + 6 + 4 * j));
+             vec_add1 (to->sacks, b);
+           }
+         break;
+       default:
+         /* Nothing to see here */
+         continue;
+       }
+    }
+}
+
+always_inline int
+tcp_segment_check_paws (tcp_connection_t * tc)
+{
+  /* XXX normally test for timestamp should be lt instead of leq, but for
+   * local testing this is not enough */
+  return tcp_opts_tstamp (&tc->opt) && tc->tsval_recent
+    && timestamp_lt (tc->opt.tsval, tc->tsval_recent);
+}
+
+/**
+ * Validate incoming segment as per RFC793 p. 69 and RFC1323 p. 19
+ *
+ * It first verifies if segment has a wrapped sequence number (PAWS) and then
+ * does the processing associated to the first four steps (ignoring security
+ * and precedence): sequence number, rst bit and syn bit checks.
+ *
+ * @return 0 if segments passes validation.
+ */
+static int
+tcp_segment_validate (vlib_main_t * vm, tcp_connection_t * tc0,
+                     vlib_buffer_t * b0, tcp_header_t * th0, u32 * next0)
+{
+  u8 paws_failed;
+
+  if (PREDICT_FALSE (!tcp_ack (th0) && !tcp_rst (th0) && !tcp_syn (th0)))
+    return -1;
+
+  tcp_options_parse (th0, &tc0->opt);
+
+  /* RFC1323: Check against wrapped sequence numbers (PAWS). If we have
+   * timestamp to echo and it's less than tsval_recent, drop segment
+   * but still send an ACK in order to retain TCP's mechanism for detecting
+   * and recovering from half-open connections */
+  paws_failed = tcp_segment_check_paws (tc0);
+  if (paws_failed)
+    {
+      clib_warning ("paws failed");
+
+      /* If it just so happens that a segment updates tsval_recent for a
+       * segment over 24 days old, invalidate tsval_recent. */
+      if (timestamp_lt (tc0->tsval_recent_age + TCP_PAWS_IDLE,
+                       tcp_time_now ()))
+       {
+         /* Age isn't reset until we get a valid tsval (bsd inspired) */
+         tc0->tsval_recent = 0;
+       }
+      else
+       {
+         /* Drop after ack if not rst */
+         if (!tcp_rst (th0))
+           {
+             tcp_make_ack (tc0, b0);
+             *next0 = tcp_next_output (tc0->c_is_ip4);
+             return -1;
+           }
+       }
+    }
+
+  /* 1st: check sequence number */
+  if (!tcp_segment_in_rcv_wnd (tc0, vnet_buffer (b0)->tcp.seq_number,
+                              vnet_buffer (b0)->tcp.seq_end))
+    {
+      if (!tcp_rst (th0))
+       {
+         /* Send dup ack */
+         tcp_make_ack (tc0, b0);
+         *next0 = tcp_next_output (tc0->c_is_ip4);
+       }
+      return -1;
+    }
+
+  /* 2nd: check the RST bit */
+  if (tcp_rst (th0))
+    {
+      /* Notify session that connection has been reset. Switch
+       * state to closed and await for session to do the cleanup. */
+      stream_session_reset_notify (&tc0->connection);
+      tc0->state = TCP_STATE_CLOSED;
+      return -1;
+    }
+
+  /* 3rd: check security and precedence (skip) */
+
+  /* 4th: check the SYN bit */
+  if (tcp_syn (th0))
+    {
+      tcp_send_reset (b0, tc0->c_is_ip4);
+      return -1;
+    }
+
+  /* If PAWS passed and segment in window, save timestamp */
+  if (!paws_failed)
+    {
+      tc0->tsval_recent = tc0->opt.tsval;
+      tc0->tsval_recent_age = tcp_time_now ();
+    }
+
+  return 0;
+}
+
+always_inline int
+tcp_rcv_ack_is_acceptable (tcp_connection_t * tc0, vlib_buffer_t * tb0)
+{
+  /* SND.UNA =< SEG.ACK =< SND.NXT */
+  return (seq_leq (tc0->snd_una, vnet_buffer (tb0)->tcp.ack_number)
+         && seq_leq (vnet_buffer (tb0)->tcp.ack_number, tc0->snd_nxt));
+}
+
+/**
+ * Compute smoothed RTT as per VJ's '88 SIGCOMM and RFC6298
+ *
+ * Note that although the original article, srtt and rttvar are scaled
+ * to minimize round-off errors, here we don't. Instead, we rely on
+ * better precision time measurements.
+ *
+ * TODO support us rtt resolution
+ */
+static void
+tcp_estimate_rtt (tcp_connection_t * tc, u32 mrtt)
+{
+  int err;
+
+  if (tc->srtt != 0)
+    {
+      err = mrtt - tc->srtt;
+      tc->srtt += err >> 3;
+
+      /* XXX Drop in RTT results in RTTVAR increase and bigger RTO.
+       * The increase should be bound */
+      tc->rttvar += (clib_abs (err) - tc->rttvar) >> 2;
+    }
+  else
+    {
+      /* First measurement. */
+      tc->srtt = mrtt;
+      tc->rttvar = mrtt << 1;
+    }
+}
+
+/** Update RTT estimate and RTO timer
+ *
+ * Measure RTT: We have two sources of RTT measurements: TSOPT and ACK
+ * timing. Middle boxes are known to fiddle with TCP options so we
+ * should give higher priority to ACK timing.
+ *
+ * return 1 if valid rtt 0 otherwise
+ */
+static int
+tcp_update_rtt (tcp_connection_t * tc, u32 ack)
+{
+  u32 mrtt = 0;
+
+  /* Karn's rule, part 1. Don't use retransmitted segments to estimate
+   * RTT because they're ambiguous. */
+  if (tc->rtt_seq && seq_gt (ack, tc->rtt_seq) && !tc->rto_boff)
+    {
+      mrtt = tcp_time_now () - tc->rtt_ts;
+      tc->rtt_seq = 0;
+    }
+
+  /* As per RFC7323 TSecr can be used for RTTM only if the segment advances
+   * snd_una, i.e., the left side of the send window:
+   * seq_lt (tc->snd_una, ack). Note: last condition could be dropped, we don't
+   * try to update rtt for dupacks */
+  else if (tcp_opts_tstamp (&tc->opt) && tc->opt.tsecr && tc->bytes_acked)
+    {
+      mrtt = tcp_time_now () - tc->opt.tsecr;
+    }
+
+  /* Ignore dubious measurements */
+  if (mrtt == 0 || mrtt > TCP_RTT_MAX)
+    return 0;
+
+  tcp_estimate_rtt (tc, mrtt);
+
+  tc->rto = clib_min (tc->srtt + (tc->rttvar << 2), TCP_RTO_MAX);
+
+  return 1;
+}
+
+/**
+ * Dequeue bytes that have been acked and while at it update RTT estimates.
+ */
+static void
+tcp_dequeue_acked (tcp_connection_t * tc, u32 ack)
+{
+  /* Dequeue the newly ACKed bytes */
+  stream_session_dequeue_drop (&tc->connection, tc->bytes_acked);
+
+  /* Update rtt and rto */
+  if (tcp_update_rtt (tc, ack))
+    {
+      /* Good ACK received and valid RTT, make sure retransmit backoff is 0 */
+      tc->rto_boff = 0;
+    }
+}
+
+/** Check if dupack as per RFC5681 Sec. 2 */
+always_inline u8
+tcp_ack_is_dupack (tcp_connection_t * tc, vlib_buffer_t * b, u32 new_snd_wnd)
+{
+  return ((vnet_buffer (b)->tcp.ack_number == tc->snd_una)
+         && seq_gt (tc->snd_una_max, tc->snd_una)
+         && (vnet_buffer (b)->tcp.seq_end == vnet_buffer (b)->tcp.seq_number)
+         && (new_snd_wnd == tc->snd_wnd));
+}
+
+void
+scoreboard_remove_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * hole)
+{
+  sack_scoreboard_hole_t *next, *prev;
+
+  if (hole->next != TCP_INVALID_SACK_HOLE_INDEX)
+    {
+      next = pool_elt_at_index (sb->holes, hole->next);
+      next->prev = hole->prev;
+    }
+
+  if (hole->prev != TCP_INVALID_SACK_HOLE_INDEX)
+    {
+      prev = pool_elt_at_index (sb->holes, hole->prev);
+      prev->next = hole->next;
+    }
+  else
+    {
+      sb->head = hole->next;
+    }
+
+  pool_put (sb->holes, hole);
+}
+
+sack_scoreboard_hole_t *
+scoreboard_insert_hole (sack_scoreboard_t * sb, sack_scoreboard_hole_t * prev,
+                       u32 start, u32 end)
+{
+  sack_scoreboard_hole_t *hole, *next;
+  u32 hole_index;
+
+  pool_get (sb->holes, hole);
+  memset (hole, 0, sizeof (*hole));
+
+  hole->start = start;
+  hole->end = end;
+  hole_index = hole - sb->holes;
+
+  if (prev)
+    {
+      hole->prev = prev - sb->holes;
+      hole->next = prev->next;
+
+      if ((next = scoreboard_next_hole (sb, hole)))
+       next->prev = hole_index;
+
+      prev->next = hole_index;
+    }
+  else
+    {
+      sb->head = hole_index;
+      hole->prev = TCP_INVALID_SACK_HOLE_INDEX;
+      hole->next = TCP_INVALID_SACK_HOLE_INDEX;
+    }
+
+  return hole;
+}
+
+static void
+tcp_rcv_sacks (tcp_connection_t * tc, u32 ack)
+{
+  sack_scoreboard_t *sb = &tc->sack_sb;
+  sack_block_t *blk, tmp;
+  sack_scoreboard_hole_t *hole, *next_hole;
+  u32 blk_index = 0;
+  int i, j;
+
+  if (!tcp_opts_sack (tc) && sb->head == TCP_INVALID_SACK_HOLE_INDEX)
+    return;
+
+  /* Remove invalid blocks */
+  vec_foreach (blk, tc->opt.sacks)
+  {
+    if (seq_lt (blk->start, blk->end)
+       && seq_gt (blk->start, tc->snd_una)
+       && seq_gt (blk->start, ack) && seq_lt (blk->end, tc->snd_nxt))
+      continue;
+
+    vec_del1 (tc->opt.sacks, blk - tc->opt.sacks);
+  }
+
+  /* Add block for cumulative ack */
+  if (seq_gt (ack, tc->snd_una))
+    {
+      tmp.start = tc->snd_una;
+      tmp.end = ack;
+      vec_add1 (tc->opt.sacks, tmp);
+    }
+
+  if (vec_len (tc->opt.sacks) == 0)
+    return;
+
+  /* Make sure blocks are ordered */
+  for (i = 0; i < vec_len (tc->opt.sacks); i++)
+    for (j = i; j < vec_len (tc->opt.sacks); j++)
+      if (seq_lt (tc->opt.sacks[j].start, tc->opt.sacks[i].start))
+       {
+         tmp = tc->opt.sacks[i];
+         tc->opt.sacks[i] = tc->opt.sacks[j];
+         tc->opt.sacks[j] = tmp;
+       }
+
+  /* If no holes, insert the first that covers all outstanding bytes */
+  if (sb->head == TCP_INVALID_SACK_HOLE_INDEX)
+    {
+      scoreboard_insert_hole (sb, 0, tc->snd_una, tc->snd_una_max);
+    }
+
+  /* Walk the holes with the SACK blocks */
+  hole = pool_elt_at_index (sb->holes, sb->head);
+  while (hole && blk_index < vec_len (tc->opt.sacks))
+    {
+      blk = &tc->opt.sacks[blk_index];
+
+      if (seq_leq (blk->start, hole->start))
+       {
+         /* Block covers hole. Remove hole */
+         if (seq_geq (blk->end, hole->end))
+           {
+             next_hole = scoreboard_next_hole (sb, hole);
+
+             /* Byte accounting */
+             if (seq_lt (hole->end, ack))
+               {
+                 /* Bytes lost because snd wnd left edge advances */
+                 if (seq_lt (next_hole->start, ack))
+                   sb->sacked_bytes -= next_hole->start - hole->end;
+                 else
+                   sb->sacked_bytes -= ack - hole->end;
+               }
+             else
+               {
+                 sb->sacked_bytes += scoreboard_hole_bytes (hole);
+               }
+
+             scoreboard_remove_hole (sb, hole);
+             hole = next_hole;
+           }
+         /* Partial overlap */
+         else
+           {
+             sb->sacked_bytes += blk->end - hole->start;
+             hole->start = blk->end;
+             blk_index++;
+           }
+       }
+      else
+       {
+         /* Hole must be split */
+         if (seq_leq (blk->end, hole->end))
+           {
+             sb->sacked_bytes += blk->end - blk->start;
+             scoreboard_insert_hole (sb, hole, blk->end, hole->end);
+             hole->end = blk->start - 1;
+             blk_index++;
+           }
+         else
+           {
+             sb->sacked_bytes += hole->end - blk->start + 1;
+             hole->end = blk->start - 1;
+             hole = scoreboard_next_hole (sb, hole);
+           }
+       }
+    }
+}
+
+/** Update snd_wnd
+ *
+ * If (SND.WL1 < SEG.SEQ or (SND.WL1 = SEG.SEQ and SND.WL2 =< SEG.ACK)), set
+ * SND.WND <- SEG.WND, set SND.WL1 <- SEG.SEQ, and set SND.WL2 <- SEG.ACK */
+static void
+tcp_update_snd_wnd (tcp_connection_t * tc, u32 seq, u32 ack, u32 snd_wnd)
+{
+  if (tc->snd_wl1 < seq || (tc->snd_wl1 == seq && tc->snd_wl2 <= ack))
+    {
+      tc->snd_wnd = snd_wnd;
+      tc->snd_wl1 = seq;
+      tc->snd_wl2 = ack;
+    }
+}
+
+static void
+tcp_cc_congestion (tcp_connection_t * tc)
+{
+  tc->cc_algo->congestion (tc);
+}
+
+static void
+tcp_cc_recover (tcp_connection_t * tc)
+{
+  if (tcp_in_fastrecovery (tc))
+    {
+      tc->cc_algo->recovered (tc);
+      tcp_recovery_off (tc);
+    }
+  else if (tcp_in_recovery (tc))
+    {
+      tcp_recovery_off (tc);
+      tc->cwnd = tcp_loss_wnd (tc);
+    }
+}
+
+static void
+tcp_cc_rcv_ack (tcp_connection_t * tc)
+{
+  u8 partial_ack;
+
+  if (tcp_in_recovery (tc))
+    {
+      partial_ack = seq_lt (tc->snd_una, tc->snd_una_max);
+      if (!partial_ack)
+       {
+         /* Clear retransmitted bytes. */
+         tc->rtx_bytes = 0;
+         tcp_cc_recover (tc);
+       }
+      else
+       {
+         /* Clear retransmitted bytes. XXX should we clear all? */
+         tc->rtx_bytes = 0;
+         tc->cc_algo->rcv_cong_ack (tc, TCP_CC_PARTIALACK);
+
+         /* Retransmit first unacked segment */
+         tcp_retransmit_first_unacked (tc);
+       }
+    }
+  else
+    {
+      tc->cc_algo->rcv_ack (tc);
+    }
+
+  tc->rcv_dupacks = 0;
+  tc->tsecr_last_ack = tc->opt.tsecr;
+}
+
+static void
+tcp_cc_rcv_dupack (tcp_connection_t * tc, u32 ack)
+{
+  ASSERT (tc->snd_una == ack);
+
+  tc->rcv_dupacks++;
+  if (tc->rcv_dupacks == TCP_DUPACK_THRESHOLD)
+    {
+      /* RFC6582 NewReno heuristic to avoid multiple fast retransmits */
+      if (tc->opt.tsecr != tc->tsecr_last_ack)
+       {
+         tc->rcv_dupacks = 0;
+         return;
+       }
+
+      tcp_fastrecovery_on (tc);
+
+      /* Handle congestion and dupack */
+      tcp_cc_congestion (tc);
+      tc->cc_algo->rcv_cong_ack (tc, TCP_CC_DUPACK);
+
+      tcp_fast_retransmit (tc);
+
+      /* Post retransmit update cwnd to ssthresh and account for the
+       * three segments that have left the network and should've been
+       * buffered at the receiver */
+      tc->cwnd = tc->ssthresh + TCP_DUPACK_THRESHOLD * tc->snd_mss;
+    }
+  else if (tc->rcv_dupacks > TCP_DUPACK_THRESHOLD)
+    {
+      ASSERT (tcp_in_fastrecovery (tc));
+
+      tc->cc_algo->rcv_cong_ack (tc, TCP_CC_DUPACK);
+    }
+}
+
+void
+tcp_cc_init (tcp_connection_t * tc)
+{
+  tc->cc_algo = tcp_cc_algo_get (TCP_CC_NEWRENO);
+  tc->cc_algo->init (tc);
+}
+
+static int
+tcp_rcv_ack (tcp_connection_t * tc, vlib_buffer_t * b,
+            tcp_header_t * th, u32 * next, u32 * error)
+{
+  u32 new_snd_wnd;
+
+  /* If the ACK acks something not yet sent (SEG.ACK > SND.NXT) then send an
+   * ACK, drop the segment, and return  */
+  if (seq_gt (vnet_buffer (b)->tcp.ack_number, tc->snd_nxt))
+    {
+      tcp_make_ack (tc, b);
+      *next = tcp_next_output (tc->c_is_ip4);
+      *error = TCP_ERROR_ACK_INVALID;
+      return -1;
+    }
+
+  /* If old ACK, discard */
+  if (seq_lt (vnet_buffer (b)->tcp.ack_number, tc->snd_una))
+    {
+      *error = TCP_ERROR_ACK_OLD;
+      return -1;
+    }
+
+  if (tcp_opts_sack_permitted (&tc->opt))
+    tcp_rcv_sacks (tc, vnet_buffer (b)->tcp.ack_number);
+
+  new_snd_wnd = clib_net_to_host_u32 (th->window) << tc->snd_wscale;
+
+  if (tcp_ack_is_dupack (tc, b, new_snd_wnd))
+    {
+      tcp_cc_rcv_dupack (tc, vnet_buffer (b)->tcp.ack_number);
+      *error = TCP_ERROR_ACK_DUP;
+      return -1;
+    }
+
+  /* Valid ACK */
+  tc->bytes_acked = vnet_buffer (b)->tcp.ack_number - tc->snd_una;
+  tc->snd_una = vnet_buffer (b)->tcp.ack_number;
+
+  /* Dequeue ACKed packet and update RTT */
+  tcp_dequeue_acked (tc, vnet_buffer (b)->tcp.ack_number);
+
+  tcp_update_snd_wnd (tc, vnet_buffer (b)->tcp.seq_number,
+                     vnet_buffer (b)->tcp.ack_number, new_snd_wnd);
+
+  /* Updates congestion control (slow start/congestion avoidance) */
+  tcp_cc_rcv_ack (tc);
+
+  /* If everything has been acked, stop retransmit timer
+   * otherwise update */
+  if (tc->snd_una == tc->snd_una_max)
+    tcp_timer_reset (tc, TCP_TIMER_RETRANSMIT);
+  else
+    tcp_timer_update (tc, TCP_TIMER_RETRANSMIT, tc->rto);
+
+  return 0;
+}
+
+/**
+ * Build SACK list as per RFC2018.
+ *
+ * Makes sure the first block contains the segment that generated the current
+ * ACK and the following ones are the ones most recently reported in SACK
+ * blocks.
+ *
+ * @param tc TCP connection for which the SACK list is updated
+ * @param start Start sequence number of the newest SACK block
+ * @param end End sequence of the newest SACK block
+ */
+static void
+tcp_update_sack_list (tcp_connection_t * tc, u32 start, u32 end)
+{
+  sack_block_t *new_list = 0, block;
+  u32 n_elts;
+  int i;
+  u8 new_head = 0;
+
+  /* If the first segment is ooo add it to the list. Last write might've moved
+   * rcv_nxt over the first segment. */
+  if (seq_lt (tc->rcv_nxt, start))
+    {
+      block.start = start;
+      block.end = end;
+      vec_add1 (new_list, block);
+      new_head = 1;
+    }
+
+  /* Find the blocks still worth keeping. */
+  for (i = 0; i < vec_len (tc->snd_sacks); i++)
+    {
+      /* Discard if:
+       * 1) rcv_nxt advanced beyond current block OR
+       * 2) Segment overlapped by the first segment, i.e., it has been merged
+       *    into it.*/
+      if (seq_leq (tc->snd_sacks[i].start, tc->rcv_nxt)
+         || seq_leq (tc->snd_sacks[i].start, end))
+       continue;
+
+      /* Save subsequent segments to new SACK list. */
+      n_elts = clib_min (vec_len (tc->snd_sacks) - i,
+                        TCP_MAX_SACK_BLOCKS - new_head);
+      vec_insert_elts (new_list, &tc->snd_sacks[i], n_elts, new_head);
+      break;
+    }
+
+  /* Replace old vector with new one */
+  vec_free (tc->snd_sacks);
+  tc->snd_sacks = new_list;
+}
+
+/** Enqueue data for delivery to application */
+always_inline u32
+tcp_session_enqueue_data (tcp_connection_t * tc, vlib_buffer_t * b,
+                         u16 data_len)
+{
+  int written;
+
+  /* Pure ACK. Update rcv_nxt and be done. */
+  if (PREDICT_FALSE (data_len == 0))
+    {
+      tc->rcv_nxt = vnet_buffer (b)->tcp.seq_end;
+      return TCP_ERROR_PURE_ACK;
+    }
+
+  written = stream_session_enqueue_data (&tc->connection,
+                                        vlib_buffer_get_current (b),
+                                        data_len, 1 /* queue event */ );
+
+  /* Update rcv_nxt */
+  if (PREDICT_TRUE (written == data_len))
+    {
+      tc->rcv_nxt = vnet_buffer (b)->tcp.seq_end;
+    }
+  /* If more data written than expected, account for out-of-order bytes. */
+  else if (written > data_len)
+    {
+      tc->rcv_nxt = vnet_buffer (b)->tcp.seq_end + written - data_len;
+
+      /* Send ACK confirming the update */
+      tc->flags |= TCP_CONN_SNDACK;
+
+      /* Update SACK list if need be */
+      if (tcp_opts_sack_permitted (&tc->opt))
+       {
+         /* Remove SACK blocks that have been delivered */
+         tcp_update_sack_list (tc, tc->rcv_nxt, tc->rcv_nxt);
+       }
+    }
+  else
+    {
+      ASSERT (0);
+      return TCP_ERROR_FIFO_FULL;
+    }
+
+  return TCP_ERROR_ENQUEUED;
+}
+
+/** Enqueue out-of-order data */
+always_inline u32
+tcp_session_enqueue_ooo (tcp_connection_t * tc, vlib_buffer_t * b,
+                        u16 data_len)
+{
+  stream_session_t *s0;
+  u32 offset, seq;
+
+  s0 = stream_session_get (tc->c_s_index, tc->c_thread_index);
+  seq = vnet_buffer (b)->tcp.seq_number;
+  offset = seq - tc->rcv_nxt;
+
+  if (svm_fifo_enqueue_with_offset (s0->server_rx_fifo, s0->pid, offset,
+                                   data_len, vlib_buffer_get_current (b)))
+    return TCP_ERROR_FIFO_FULL;
+
+  /* Update SACK list if in use */
+  if (tcp_opts_sack_permitted (&tc->opt))
+    {
+      ooo_segment_t *newest;
+      u32 start, end;
+
+      /* Get the newest segment from the fifo */
+      newest = svm_fifo_newest_ooo_segment (s0->server_rx_fifo);
+      start = tc->rcv_nxt + ooo_segment_offset (s0->server_rx_fifo, newest);
+      end = tc->rcv_nxt + ooo_segment_end_offset (s0->server_rx_fifo, newest);
+
+      tcp_update_sack_list (tc, start, end);
+    }
+
+  return TCP_ERROR_ENQUEUED;
+}
+
+/**
+ * Check if ACK could be delayed. DELACK timer is set only after frame is
+ * processed so this can return true for a full bursts of packets.
+ */
+always_inline int
+tcp_can_delack (tcp_connection_t * tc)
+{
+  /* If there's no DELACK timer set and the last window sent wasn't 0 we
+   * can safely delay. */
+  if (!tcp_timer_is_active (tc, TCP_TIMER_DELACK)
+      && (tc->flags & TCP_CONN_SENT_RCV_WND0) == 0
+      && (tc->flags & TCP_CONN_SNDACK) == 0)
+    return 1;
+
+  return 0;
+}
+
+static int
+tcp_segment_rcv (tcp_main_t * tm, tcp_connection_t * tc, vlib_buffer_t * b,
+                u16 n_data_bytes, u32 * next0)
+{
+  u32 error = 0;
+
+  /* Handle out-of-order data */
+  if (PREDICT_FALSE (vnet_buffer (b)->tcp.seq_number != tc->rcv_nxt))
+    {
+      error = tcp_session_enqueue_ooo (tc, b, n_data_bytes);
+
+      /* Don't send more than 3 dupacks per burst
+       * XXX decide if this is good */
+      if (tc->snt_dupacks < 3)
+       {
+         /* RFC2581: Send DUPACK for fast retransmit */
+         tcp_make_ack (tc, b);
+         *next0 = tcp_next_output (tc->c_is_ip4);
+
+         /* Mark as DUPACK. We may filter these in output if
+          * the burst fills the holes. */
+         vnet_buffer (b)->tcp.flags = TCP_BUF_FLAG_DUPACK;
+
+         tc->snt_dupacks++;
+       }
+
+      goto done;
+    }
+
+  /* In order data, enqueue. Fifo figures out by itself if any out-of-order
+   * segments can be enqueued after fifo tail offset changes. */
+  error = tcp_session_enqueue_data (tc, b, n_data_bytes);
+
+  /* Check if ACK can be delayed */
+  if (tcp_can_delack (tc))
+    {
+      /* Nothing to do for pure ACKs */
+      if (n_data_bytes == 0)
+       goto done;
+
+      /* If connection has not been previously marked for delay ack
+       * add it to the list and flag it */
+      if (!tc->flags & TCP_CONN_DELACK)
+       {
+         vec_add1 (tm->delack_connections[tc->c_thread_index],
+                   tc->c_c_index);
+         tc->flags |= TCP_CONN_DELACK;
+       }
+    }
+  else
+    {
+      /* Check if a packet has already been enqueued to output for burst.
+       * If yes, then drop this one, otherwise, let it pass through to
+       * output */
+      if ((tc->flags & TCP_CONN_BURSTACK) == 0)
+       {
+         *next0 = tcp_next_output (tc->c_is_ip4);
+         tcp_make_ack (tc, b);
+         error = TCP_ERROR_ENQUEUED;
+
+         /* TODO: maybe add counter to ensure N acks will be sent/burst */
+         tc->flags |= TCP_CONN_BURSTACK;
+       }
+    }
+
+done:
+  return error;
+}
+
+void
+delack_timers_init (tcp_main_t * tm, u32 thread_index)
+{
+  tcp_connection_t *tc;
+  u32 i, *conns;
+  tw_timer_wheel_16t_2w_512sl_t *tw;
+
+  tw = &tm->timer_wheels[thread_index];
+  conns = tm->delack_connections[thread_index];
+  for (i = 0; i < vec_len (conns); i++)
+    {
+      tc = pool_elt_at_index (tm->connections[thread_index], conns[i]);
+      ASSERT (0 != tc);
+
+      tc->timers[TCP_TIMER_DELACK]
+       = tw_timer_start_16t_2w_512sl (tw, conns[i],
+                                      TCP_TIMER_DELACK, TCP_DELACK_TIME);
+    }
+  vec_reset_length (tm->delack_connections[thread_index]);
+}
+
+always_inline uword
+tcp46_established_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
+                         vlib_frame_t * from_frame, int is_ip4)
+{
+  u32 n_left_from, next_index, *from, *to_next;
+  u32 my_thread_index = vm->cpu_index, errors = 0;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+
+  from = vlib_frame_vector_args (from_frame);
+  n_left_from = from_frame->n_vectors;
+
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         tcp_header_t *th0 = 0;
+         tcp_connection_t *tc0;
+         ip4_header_t *ip40;
+         ip6_header_t *ip60;
+         u32 n_advance_bytes0, n_data_bytes0;
+         u32 next0 = TCP_ESTABLISHED_NEXT_DROP, error0 = TCP_ERROR_ENQUEUED;
+
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+         tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
+                                   my_thread_index);
+
+         /* Checksum computed by ipx_local no need to compute again */
+
+         if (is_ip4)
+           {
+             ip40 = vlib_buffer_get_current (b0);
+             th0 = ip4_next_header (ip40);
+             n_advance_bytes0 = (ip4_header_bytes (ip40)
+                                 + tcp_header_bytes (th0));
+             n_data_bytes0 = clib_net_to_host_u16 (ip40->length)
+               - n_advance_bytes0;
+           }
+         else
+           {
+             ip60 = vlib_buffer_get_current (b0);
+             th0 = ip6_next_header (ip60);
+             n_advance_bytes0 = tcp_header_bytes (th0);
+             n_data_bytes0 = clib_net_to_host_u16 (ip60->payload_length)
+               - n_advance_bytes0;
+             n_advance_bytes0 += sizeof (ip60[0]);
+           }
+
+         /* SYNs, FINs and data consume sequence numbers */
+         vnet_buffer (b0)->tcp.seq_end = vnet_buffer (b0)->tcp.seq_number
+           + tcp_is_syn (th0) + tcp_is_fin (th0) + n_data_bytes0;
+
+         /* TODO header prediction fast path */
+
+         /* 1-4: check SEQ, RST, SYN */
+         if (PREDICT_FALSE (tcp_segment_validate (vm, tc0, b0, th0, &next0)))
+           {
+             error0 = TCP_ERROR_SEGMENT_INVALID;
+             goto drop;
+           }
+
+         /* 5: check the ACK field  */
+         if (tcp_rcv_ack (tc0, b0, th0, &next0, &error0))
+           {
+             goto drop;
+           }
+
+         /* 6: check the URG bit TODO */
+
+         /* 7: process the segment text */
+         vlib_buffer_advance (b0, n_advance_bytes0);
+         error0 = tcp_segment_rcv (tm, tc0, b0, n_data_bytes0, &next0);
+
+         /* 8: check the FIN bit */
+         if (tcp_fin (th0))
+           {
+             /* Send ACK and enter CLOSE-WAIT */
+             tcp_make_ack (tc0, b0);
+             tcp_connection_force_ack (tc0, b0);
+             next0 = tcp_next_output (tc0->c_is_ip4);
+             tc0->state = TCP_STATE_CLOSE_WAIT;
+             stream_session_disconnect_notify (&tc0->connection);
+           }
+
+       drop:
+         b0->error = node->errors[error0];
+         if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
+           {
+
+           }
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  errors = session_manager_flush_enqueue_events (my_thread_index);
+  if (errors)
+    {
+      if (is_ip4)
+       vlib_node_increment_counter (vm, tcp4_established_node.index,
+                                    TCP_ERROR_EVENT_FIFO_FULL, errors);
+      else
+       vlib_node_increment_counter (vm, tcp6_established_node.index,
+                                    TCP_ERROR_EVENT_FIFO_FULL, errors);
+    }
+
+  delack_timers_init (tm, my_thread_index);
+
+  return from_frame->n_vectors;
+}
+
+static uword
+tcp4_established (vlib_main_t * vm, vlib_node_runtime_t * node,
+                 vlib_frame_t * from_frame)
+{
+  return tcp46_established_inline (vm, node, from_frame, 1 /* is_ip4 */ );
+}
+
+static uword
+tcp6_established (vlib_main_t * vm, vlib_node_runtime_t * node,
+                 vlib_frame_t * from_frame)
+{
+  return tcp46_established_inline (vm, node, from_frame, 0 /* is_ip4 */ );
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp4_established_node) =
+{
+  .function = tcp4_established,
+  .name = "tcp4-established",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,.error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_ESTABLISHED_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_ESTABLISHED_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp4_established_node, tcp4_established);
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp6_established_node) =
+{
+  .function = tcp6_established,
+  .name = "tcp6-established",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_ESTABLISHED_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_ESTABLISHED_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp6_established_node, tcp6_established);
+
+vlib_node_registration_t tcp4_syn_sent_node;
+vlib_node_registration_t tcp6_syn_sent_node;
+
+always_inline uword
+tcp46_syn_sent_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
+                      vlib_frame_t * from_frame, int is_ip4)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  u32 n_left_from, next_index, *from, *to_next;
+  u32 my_thread_index = vm->cpu_index, errors = 0;
+  u8 sst = is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
+
+  from = vlib_frame_vector_args (from_frame);
+  n_left_from = from_frame->n_vectors;
+
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0, ack0, seq0;
+         vlib_buffer_t *b0;
+         tcp_header_t *tcp0 = 0;
+         tcp_connection_t *tc0;
+         ip4_header_t *ip40;
+         ip6_header_t *ip60;
+         u32 n_advance_bytes0, n_data_bytes0;
+         tcp_connection_t *new_tc0;
+         u32 next0 = TCP_SYN_SENT_NEXT_DROP, error0 = TCP_ERROR_ENQUEUED;
+
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+         tc0 =
+           tcp_half_open_connection_get (vnet_buffer (b0)->
+                                         tcp.connection_index);
+
+         ack0 = vnet_buffer (b0)->tcp.ack_number;
+         seq0 = vnet_buffer (b0)->tcp.seq_number;
+
+         /* Checksum computed by ipx_local no need to compute again */
+
+         if (is_ip4)
+           {
+             ip40 = vlib_buffer_get_current (b0);
+             tcp0 = ip4_next_header (ip40);
+             n_advance_bytes0 = (ip4_header_bytes (ip40)
+                                 + tcp_header_bytes (tcp0));
+             n_data_bytes0 = clib_net_to_host_u16 (ip40->length)
+               - n_advance_bytes0;
+           }
+         else
+           {
+             ip60 = vlib_buffer_get_current (b0);
+             tcp0 = ip6_next_header (ip60);
+             n_advance_bytes0 = tcp_header_bytes (tcp0);
+             n_data_bytes0 = clib_net_to_host_u16 (ip60->payload_length)
+               - n_advance_bytes0;
+             n_advance_bytes0 += sizeof (ip60[0]);
+           }
+
+         if (PREDICT_FALSE
+             (!tcp_ack (tcp0) && !tcp_rst (tcp0) && !tcp_syn (tcp0)))
+           goto drop;
+
+         /* SYNs, FINs and data consume sequence numbers */
+         vnet_buffer (b0)->tcp.seq_end = seq0 + tcp_is_syn (tcp0)
+           + tcp_is_fin (tcp0) + n_data_bytes0;
+
+         /*
+          *  1. check the ACK bit
+          */
+
+         /*
+          *   If the ACK bit is set
+          *     If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send a reset (unless
+          *     the RST bit is set, if so drop the segment and return)
+          *       <SEQ=SEG.ACK><CTL=RST>
+          *     and discard the segment.  Return.
+          *     If SND.UNA =< SEG.ACK =< SND.NXT then the ACK is acceptable.
+          */
+         if (tcp_ack (tcp0))
+           {
+             if (ack0 <= tc0->iss || ack0 > tc0->snd_nxt)
+               {
+                 if (!tcp_rst (tcp0))
+                   tcp_send_reset (b0, is_ip4);
+
+                 goto drop;
+               }
+
+             /* Make sure ACK is valid */
+             if (tc0->snd_una > ack0)
+               goto drop;
+           }
+
+         /*
+          * 2. check the RST bit
+          */
+
+         if (tcp_rst (tcp0))
+           {
+             /* If ACK is acceptable, signal client that peer is not
+              * willing to accept connection and drop connection*/
+             if (tcp_ack (tcp0))
+               {
+                 stream_session_connect_notify (&tc0->connection, sst,
+                                                1 /* fail */ );
+                 tcp_connection_cleanup (tc0);
+               }
+             goto drop;
+           }
+
+         /*
+          * 3. check the security and precedence (skipped)
+          */
+
+         /*
+          * 4. check the SYN bit
+          */
+
+         /* No SYN flag. Drop. */
+         if (!tcp_syn (tcp0))
+           goto drop;
+
+         /* Stop connection establishment and retransmit timers */
+         tcp_timer_reset (tc0, TCP_TIMER_ESTABLISH);
+         tcp_timer_reset (tc0, TCP_TIMER_RETRANSMIT_SYN);
+
+         /* Valid SYN or SYN-ACK. Move connection from half-open pool to
+          * current thread pool. */
+         pool_get (tm->connections[my_thread_index], new_tc0);
+         clib_memcpy (new_tc0, tc0, sizeof (*new_tc0));
+
+         new_tc0->c_thread_index = my_thread_index;
+
+         /* Cleanup half-open connection XXX lock */
+         pool_put (tm->half_open_connections, tc0);
+
+         new_tc0->rcv_nxt = vnet_buffer (b0)->tcp.seq_end;
+         new_tc0->irs = seq0;
+
+         /* Parse options */
+         tcp_options_parse (tcp0, &new_tc0->opt);
+         tcp_connection_init_vars (new_tc0);
+
+         if (tcp_opts_tstamp (&new_tc0->opt))
+           {
+             new_tc0->tsval_recent = new_tc0->opt.tsval;
+             new_tc0->tsval_recent_age = tcp_time_now ();
+           }
+
+         if (tcp_opts_wscale (&new_tc0->opt))
+           new_tc0->snd_wscale = new_tc0->opt.wscale;
+
+         new_tc0->snd_wnd = clib_net_to_host_u32 (tcp0->window)
+           << new_tc0->snd_wscale;
+         new_tc0->snd_wl1 = seq0;
+         new_tc0->snd_wl2 = ack0;
+
+         /* SYN-ACK: See if we can switch to ESTABLISHED state */
+         if (tcp_ack (tcp0))
+           {
+             /* Our SYN is ACKed: we have iss < ack = snd_una */
+
+             /* TODO Dequeue acknowledged segments if we support Fast Open */
+             new_tc0->snd_una = ack0;
+             new_tc0->state = TCP_STATE_ESTABLISHED;
+
+             /* Notify app that we have connection */
+             stream_session_connect_notify (&new_tc0->connection, sst, 0);
+
+             /* Make sure after data segment processing ACK is sent */
+             new_tc0->flags |= TCP_CONN_SNDACK;
+           }
+         /* SYN: Simultaneous open. Change state to SYN-RCVD and send SYN-ACK */
+         else
+           {
+             new_tc0->state = TCP_STATE_SYN_RCVD;
+
+             /* Notify app that we have connection XXX */
+             stream_session_connect_notify (&new_tc0->connection, sst, 0);
+
+             tcp_make_synack (new_tc0, b0);
+             next0 = tcp_next_output (is_ip4);
+
+             goto drop;
+           }
+
+         /* Read data, if any */
+         if (n_data_bytes0)
+           {
+             error0 =
+               tcp_segment_rcv (tm, new_tc0, b0, n_data_bytes0, &next0);
+             if (error0 == TCP_ERROR_PURE_ACK)
+               error0 = TCP_ERROR_SYN_ACKS_RCVD;
+           }
+         else
+           {
+             tcp_make_ack (new_tc0, b0);
+             next0 = tcp_next_output (new_tc0->c_is_ip4);
+           }
+
+       drop:
+
+         b0->error = error0 ? node->errors[error0] : 0;
+         if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
+           {
+
+           }
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  errors = session_manager_flush_enqueue_events (my_thread_index);
+  if (errors)
+    {
+      if (is_ip4)
+       vlib_node_increment_counter (vm, tcp4_established_node.index,
+                                    TCP_ERROR_EVENT_FIFO_FULL, errors);
+      else
+       vlib_node_increment_counter (vm, tcp6_established_node.index,
+                                    TCP_ERROR_EVENT_FIFO_FULL, errors);
+    }
+
+  return from_frame->n_vectors;
+}
+
+static uword
+tcp4_syn_sent (vlib_main_t * vm, vlib_node_runtime_t * node,
+              vlib_frame_t * from_frame)
+{
+  return tcp46_syn_sent_inline (vm, node, from_frame, 1 /* is_ip4 */ );
+}
+
+static uword
+tcp6_syn_sent_rcv (vlib_main_t * vm, vlib_node_runtime_t * node,
+                  vlib_frame_t * from_frame)
+{
+  return tcp46_syn_sent_inline (vm, node, from_frame, 0 /* is_ip4 */ );
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp4_syn_sent_node) =
+{
+  .function = tcp4_syn_sent,
+  .name = "tcp4-syn-sent",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_SYN_SENT_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_SYN_SENT_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp4_syn_sent_node, tcp4_syn_sent);
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp6_syn_sent_node) =
+{
+  .function = tcp6_syn_sent_rcv,
+  .name = "tcp6-syn-sent",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_SYN_SENT_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_SYN_SENT_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  }
+,};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp6_syn_sent_node, tcp6_syn_sent_rcv);
+/**
+ * Handles reception for all states except LISTEN, SYN-SEND and ESTABLISHED
+ * as per RFC793 p. 64
+ */
+always_inline uword
+tcp46_rcv_process_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
+                         vlib_frame_t * from_frame, int is_ip4)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  u32 n_left_from, next_index, *from, *to_next;
+  u32 my_thread_index = vm->cpu_index, errors = 0;
+
+  from = vlib_frame_vector_args (from_frame);
+  n_left_from = from_frame->n_vectors;
+
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         tcp_header_t *tcp0 = 0;
+         tcp_connection_t *tc0;
+         ip4_header_t *ip40;
+         ip6_header_t *ip60;
+         u32 n_advance_bytes0, n_data_bytes0;
+         u32 next0 = TCP_RCV_PROCESS_NEXT_DROP, error0 = TCP_ERROR_ENQUEUED;
+
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+         tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
+                                   my_thread_index);
+
+         /* Checksum computed by ipx_local no need to compute again */
+
+         if (is_ip4)
+           {
+             ip40 = vlib_buffer_get_current (b0);
+             tcp0 = ip4_next_header (ip40);
+             n_advance_bytes0 = (ip4_header_bytes (ip40)
+                                 + tcp_header_bytes (tcp0));
+             n_data_bytes0 = clib_net_to_host_u16 (ip40->length)
+               - n_advance_bytes0;
+           }
+         else
+           {
+             ip60 = vlib_buffer_get_current (b0);
+             tcp0 = ip6_next_header (ip60);
+             n_advance_bytes0 = tcp_header_bytes (tcp0);
+             n_data_bytes0 = clib_net_to_host_u16 (ip60->payload_length)
+               - n_advance_bytes0;
+             n_advance_bytes0 += sizeof (ip60[0]);
+           }
+
+         /* SYNs, FINs and data consume sequence numbers */
+         vnet_buffer (b0)->tcp.seq_end = vnet_buffer (b0)->tcp.seq_number
+           + tcp_is_syn (tcp0) + tcp_is_fin (tcp0) + n_data_bytes0;
+
+         /*
+          * Special treatment for CLOSED
+          */
+         switch (tc0->state)
+           {
+           case TCP_STATE_CLOSED:
+             goto drop;
+             break;
+           }
+
+         /*
+          * For all other states (except LISTEN)
+          */
+
+         /* 1-4: check SEQ, RST, SYN */
+         if (PREDICT_FALSE
+             (tcp_segment_validate (vm, tc0, b0, tcp0, &next0)))
+           {
+             error0 = TCP_ERROR_SEGMENT_INVALID;
+             goto drop;
+           }
+
+         /* 5: check the ACK field  */
+         switch (tc0->state)
+           {
+           case TCP_STATE_SYN_RCVD:
+             /*
+              * If the segment acknowledgment is not acceptable, form a
+              * reset segment,
+              *  <SEQ=SEG.ACK><CTL=RST>
+              * and send it.
+              */
+             if (!tcp_rcv_ack_is_acceptable (tc0, b0))
+               {
+                 tcp_send_reset (b0, is_ip4);
+                 goto drop;
+               }
+             /* Switch state to ESTABLISHED */
+             tc0->state = TCP_STATE_ESTABLISHED;
+
+             /* Initialize session variables */
+             tc0->snd_una = vnet_buffer (b0)->tcp.ack_number;
+             tc0->snd_wnd = clib_net_to_host_u32 (tcp0->window)
+               << tc0->opt.wscale;
+             tc0->snd_wl1 = vnet_buffer (b0)->tcp.seq_number;
+             tc0->snd_wl2 = vnet_buffer (b0)->tcp.ack_number;
+
+             /* Shoulder tap the server */
+             stream_session_accept_notify (&tc0->connection);
+
+             tcp_timer_reset (tc0, TCP_TIMER_RETRANSMIT_SYN);
+             break;
+           case TCP_STATE_ESTABLISHED:
+             /* We can get packets in established state here because they
+              * were enqueued before state change */
+             if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
+               goto drop;
+
+             break;
+           case TCP_STATE_FIN_WAIT_1:
+             /* In addition to the processing for the ESTABLISHED state, if
+              * our FIN is now acknowledged then enter FIN-WAIT-2 and
+              * continue processing in that state. */
+             if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
+               goto drop;
+             tc0->state = TCP_STATE_FIN_WAIT_2;
+             /* Stop all timers, 2MSL will be set lower */
+             tcp_connection_timers_reset (tc0);
+             break;
+           case TCP_STATE_FIN_WAIT_2:
+             /* In addition to the processing for the ESTABLISHED state, if
+              * the retransmission queue is empty, the user's CLOSE can be
+              * acknowledged ("ok") but do not delete the TCB. */
+             if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
+               goto drop;
+             /* check if rtx queue is empty and ack CLOSE TODO */
+             break;
+           case TCP_STATE_CLOSE_WAIT:
+             /* Do the same processing as for the ESTABLISHED state. */
+             if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
+               goto drop;
+             break;
+           case TCP_STATE_CLOSING:
+             /* In addition to the processing for the ESTABLISHED state, if
+              * the ACK acknowledges our FIN then enter the TIME-WAIT state,
+              * otherwise ignore the segment. */
+             if (tcp_rcv_ack (tc0, b0, tcp0, &next0, &error0))
+               goto drop;
+
+             /* XXX test that send queue empty */
+             tc0->state = TCP_STATE_TIME_WAIT;
+             goto drop;
+
+             break;
+           case TCP_STATE_LAST_ACK:
+             /* The only thing that can arrive in this state is an
+              * acknowledgment of our FIN. If our FIN is now acknowledged,
+              * delete the TCB, enter the CLOSED state, and return. */
+
+             if (!tcp_rcv_ack_is_acceptable (tc0, b0))
+               goto drop;
+
+             tcp_connection_del (tc0);
+             goto drop;
+
+             break;
+           case TCP_STATE_TIME_WAIT:
+             /* The only thing that can arrive in this state is a
+              * retransmission of the remote FIN. Acknowledge it, and restart
+              * the 2 MSL timeout. */
+
+             /* TODO */
+             goto drop;
+             break;
+           default:
+             ASSERT (0);
+           }
+
+         /* 6: check the URG bit TODO */
+
+         /* 7: process the segment text */
+         switch (tc0->state)
+           {
+           case TCP_STATE_ESTABLISHED:
+           case TCP_STATE_FIN_WAIT_1:
+           case TCP_STATE_FIN_WAIT_2:
+             error0 = tcp_segment_rcv (tm, tc0, b0, n_data_bytes0, &next0);
+             break;
+           case TCP_STATE_CLOSE_WAIT:
+           case TCP_STATE_CLOSING:
+           case TCP_STATE_LAST_ACK:
+           case TCP_STATE_TIME_WAIT:
+             /* This should not occur, since a FIN has been received from the
+              * remote side.  Ignore the segment text. */
+             break;
+           }
+
+         /* 8: check the FIN bit */
+         if (!tcp_fin (tcp0))
+           goto drop;
+
+         switch (tc0->state)
+           {
+           case TCP_STATE_ESTABLISHED:
+           case TCP_STATE_SYN_RCVD:
+             /* Send FIN-ACK notify app and enter CLOSE-WAIT */
+             tcp_connection_timers_reset (tc0);
+             tcp_make_finack (tc0, b0);
+             next0 = tcp_next_output (tc0->c_is_ip4);
+             stream_session_disconnect_notify (&tc0->connection);
+             tc0->state = TCP_STATE_CLOSE_WAIT;
+             break;
+           case TCP_STATE_CLOSE_WAIT:
+           case TCP_STATE_CLOSING:
+           case TCP_STATE_LAST_ACK:
+             /* move along .. */
+             break;
+           case TCP_STATE_FIN_WAIT_1:
+             tc0->state = TCP_STATE_TIME_WAIT;
+             tcp_connection_timers_reset (tc0);
+             tcp_timer_set (tc0, TCP_TIMER_2MSL, TCP_2MSL_TIME);
+             break;
+           case TCP_STATE_FIN_WAIT_2:
+             /* Got FIN, send ACK! */
+             tc0->state = TCP_STATE_TIME_WAIT;
+             tcp_timer_set (tc0, TCP_TIMER_2MSL, TCP_2MSL_TIME);
+             tcp_make_ack (tc0, b0);
+             next0 = tcp_next_output (is_ip4);
+             break;
+           case TCP_STATE_TIME_WAIT:
+             /* Remain in the TIME-WAIT state. Restart the 2 MSL time-wait
+              * timeout.
+              */
+             tcp_timer_update (tc0, TCP_TIMER_2MSL, TCP_2MSL_TIME);
+             break;
+           }
+
+         b0->error = error0 ? node->errors[error0] : 0;
+
+       drop:
+         if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
+           {
+
+           }
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  errors = session_manager_flush_enqueue_events (my_thread_index);
+  if (errors)
+    {
+      if (is_ip4)
+       vlib_node_increment_counter (vm, tcp4_established_node.index,
+                                    TCP_ERROR_EVENT_FIFO_FULL, errors);
+      else
+       vlib_node_increment_counter (vm, tcp6_established_node.index,
+                                    TCP_ERROR_EVENT_FIFO_FULL, errors);
+    }
+
+  return from_frame->n_vectors;
+}
+
+static uword
+tcp4_rcv_process (vlib_main_t * vm, vlib_node_runtime_t * node,
+                 vlib_frame_t * from_frame)
+{
+  return tcp46_rcv_process_inline (vm, node, from_frame, 1 /* is_ip4 */ );
+}
+
+static uword
+tcp6_rcv_process (vlib_main_t * vm, vlib_node_runtime_t * node,
+                 vlib_frame_t * from_frame)
+{
+  return tcp46_rcv_process_inline (vm, node, from_frame, 0 /* is_ip4 */ );
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp4_rcv_process_node) =
+{
+  .function = tcp4_rcv_process,
+  .name = "tcp4-rcv-process",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_RCV_PROCESS_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_RCV_PROCESS_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp4_rcv_process_node, tcp4_rcv_process);
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp6_rcv_process_node) =
+{
+  .function = tcp6_rcv_process,
+  .name = "tcp6-rcv-process",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_RCV_PROCESS_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_RCV_PROCESS_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp6_rcv_process_node, tcp6_rcv_process);
+
+vlib_node_registration_t tcp4_listen_node;
+vlib_node_registration_t tcp6_listen_node;
+
+/**
+ * LISTEN state processing as per RFC 793 p. 65
+ */
+always_inline uword
+tcp46_listen_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
+                    vlib_frame_t * from_frame, int is_ip4)
+{
+  u32 n_left_from, next_index, *from, *to_next;
+  u32 my_thread_index = vm->cpu_index;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  u8 sst = is_ip4 ? SESSION_TYPE_IP4_TCP : SESSION_TYPE_IP6_TCP;
+
+  from = vlib_frame_vector_args (from_frame);
+  n_left_from = from_frame->n_vectors;
+
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         tcp_header_t *th0 = 0;
+         tcp_connection_t *lc0;
+         ip4_header_t *ip40;
+         ip6_header_t *ip60;
+         tcp_connection_t *child0;
+         u32 error0 = TCP_ERROR_SYNS_RCVD, next0 = TCP_LISTEN_NEXT_DROP;
+
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+         lc0 = tcp_listener_get (vnet_buffer (b0)->tcp.connection_index);
+
+         if (is_ip4)
+           {
+             ip40 = vlib_buffer_get_current (b0);
+             th0 = ip4_next_header (ip40);
+           }
+         else
+           {
+             ip60 = vlib_buffer_get_current (b0);
+             th0 = ip6_next_header (ip60);
+           }
+
+         /* Create child session. For syn-flood protection use filter */
+
+         /* 1. first check for an RST */
+         if (tcp_rst (th0))
+           goto drop;
+
+         /* 2. second check for an ACK */
+         if (tcp_ack (th0))
+           {
+             tcp_send_reset (b0, is_ip4);
+             goto drop;
+           }
+
+         /* 3. check for a SYN (did that already) */
+
+         /* Create child session and send SYN-ACK */
+         pool_get (tm->connections[my_thread_index], child0);
+         memset (child0, 0, sizeof (*child0));
+
+         child0->c_c_index = child0 - tm->connections[my_thread_index];
+         child0->c_lcl_port = lc0->c_lcl_port;
+         child0->c_rmt_port = th0->src_port;
+         child0->c_is_ip4 = is_ip4;
+         child0->c_thread_index = my_thread_index;
+
+         if (is_ip4)
+           {
+             child0->c_lcl_ip4.as_u32 = ip40->dst_address.as_u32;
+             child0->c_rmt_ip4.as_u32 = ip40->src_address.as_u32;
+           }
+         else
+           {
+             clib_memcpy (&child0->c_lcl_ip6, &ip60->dst_address,
+                          sizeof (ip6_address_t));
+             clib_memcpy (&child0->c_rmt_ip6, &ip60->src_address,
+                          sizeof (ip6_address_t));
+           }
+
+         if (stream_session_accept (&child0->connection, lc0->c_s_index, sst,
+                                    0 /* notify */ ))
+           {
+             error0 = TCP_ERROR_CREATE_SESSION_FAIL;
+             goto drop;
+           }
+
+         tcp_options_parse (th0, &child0->opt);
+         tcp_connection_init_vars (child0);
+
+         child0->irs = vnet_buffer (b0)->tcp.seq_number;
+         child0->rcv_nxt = vnet_buffer (b0)->tcp.seq_number + 1;
+         child0->state = TCP_STATE_SYN_RCVD;
+
+         /* RFC1323: TSval timestamps sent on {SYN} and {SYN,ACK}
+          * segments are used to initialize PAWS. */
+         if (tcp_opts_tstamp (&child0->opt))
+           {
+             child0->tsval_recent = child0->opt.tsval;
+             child0->tsval_recent_age = tcp_time_now ();
+           }
+
+         /* Reuse buffer to make syn-ack and send */
+         tcp_make_synack (child0, b0);
+         next0 = tcp_next_output (is_ip4);
+
+       drop:
+         if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
+           {
+
+           }
+
+         b0->error = error0 ? node->errors[error0] : 0;
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+  return from_frame->n_vectors;
+}
+
+static uword
+tcp4_listen (vlib_main_t * vm, vlib_node_runtime_t * node,
+            vlib_frame_t * from_frame)
+{
+  return tcp46_listen_inline (vm, node, from_frame, 1 /* is_ip4 */ );
+}
+
+static uword
+tcp6_listen (vlib_main_t * vm, vlib_node_runtime_t * node,
+            vlib_frame_t * from_frame)
+{
+  return tcp46_listen_inline (vm, node, from_frame, 0 /* is_ip4 */ );
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp4_listen_node) =
+{
+  .function = tcp4_listen,
+  .name = "tcp4-listen",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_LISTEN_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_LISTEN_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp4_listen_node, tcp4_listen);
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp6_listen_node) =
+{
+  .function = tcp6_listen,
+  .name = "tcp6-listen",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_LISTEN_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_LISTEN_NEXT_##s] = n,
+    foreach_tcp_state_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp6_listen_node, tcp6_listen);
+
+vlib_node_registration_t tcp4_input_node;
+vlib_node_registration_t tcp6_input_node;
+
+typedef enum _tcp_input_next
+{
+  TCP_INPUT_NEXT_DROP,
+  TCP_INPUT_NEXT_LISTEN,
+  TCP_INPUT_NEXT_RCV_PROCESS,
+  TCP_INPUT_NEXT_SYN_SENT,
+  TCP_INPUT_NEXT_ESTABLISHED,
+  TCP_INPUT_NEXT_RESET,
+  TCP_INPUT_N_NEXT
+} tcp_input_next_t;
+
+#define foreach_tcp4_input_next                 \
+  _ (DROP, "error-drop")                        \
+  _ (LISTEN, "tcp4-listen")                     \
+  _ (RCV_PROCESS, "tcp4-rcv-process")           \
+  _ (SYN_SENT, "tcp4-syn-sent")                 \
+  _ (ESTABLISHED, "tcp4-established")          \
+  _ (RESET, "tcp4-reset")
+
+#define foreach_tcp6_input_next                 \
+  _ (DROP, "error-drop")                        \
+  _ (LISTEN, "tcp6-listen")                     \
+  _ (RCV_PROCESS, "tcp6-rcv-process")           \
+  _ (SYN_SENT, "tcp6-syn-sent")                 \
+  _ (ESTABLISHED, "tcp6-established")          \
+  _ (RESET, "tcp6-reset")
+
+typedef struct
+{
+  u16 src_port;
+  u16 dst_port;
+  u8 state;
+} tcp_rx_trace_t;
+
+const char *tcp_fsm_states[] = {
+#define _(sym, str) str,
+  foreach_tcp_fsm_state
+#undef _
+};
+
+u8 *
+format_tcp_state (u8 * s, va_list * args)
+{
+  tcp_state_t *state = va_arg (*args, tcp_state_t *);
+
+  if (state[0] < TCP_N_STATES)
+    s = format (s, "%s", tcp_fsm_states[state[0]]);
+  else
+    s = format (s, "UNKNOWN");
+
+  return s;
+}
+
+u8 *
+format_tcp_rx_trace (u8 * s, va_list * args)
+{
+  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+  tcp_rx_trace_t *t = va_arg (*args, tcp_rx_trace_t *);
+
+  s = format (s, "TCP: src-port %d dst-port %U%s\n",
+             clib_net_to_host_u16 (t->src_port),
+             clib_net_to_host_u16 (t->dst_port), format_tcp_state, t->state);
+
+  return s;
+}
+
+#define filter_flags (TCP_FLAG_SYN|TCP_FLAG_ACK|TCP_FLAG_RST|TCP_FLAG_FIN)
+
+always_inline uword
+tcp46_input_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
+                   vlib_frame_t * from_frame, int is_ip4)
+{
+  u32 n_left_from, next_index, *from, *to_next;
+  u32 my_thread_index = vm->cpu_index;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  session_manager_main_t *ssm = vnet_get_session_manager_main ();
+
+  from = vlib_frame_vector_args (from_frame);
+  n_left_from = from_frame->n_vectors;
+
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         tcp_header_t *tcp0 = 0;
+         tcp_connection_t *tc0;
+         ip4_header_t *ip40;
+         ip6_header_t *ip60;
+         u32 error0 = TCP_ERROR_NO_LISTENER, next0 = TCP_INPUT_NEXT_DROP;
+         u8 flags0;
+
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+
+         if (is_ip4)
+           {
+             ip40 = vlib_buffer_get_current (b0);
+             tcp0 = ip4_next_header (ip40);
+
+             /* lookup session */
+             tc0 =
+               (tcp_connection_t *) stream_session_lookup_transport4 (ssm,
+                                                                      &ip40->dst_address,
+                                                                      &ip40->src_address,
+                                                                      tcp0->dst_port,
+                                                                      tcp0->src_port,
+                                                                      SESSION_TYPE_IP4_TCP,
+                                                                      my_thread_index);
+           }
+         else
+           {
+             ip60 = vlib_buffer_get_current (b0);
+             tcp0 = ip6_next_header (ip60);
+             tc0 =
+               (tcp_connection_t *) stream_session_lookup_transport6 (ssm,
+                                                                      &ip60->src_address,
+                                                                      &ip60->dst_address,
+                                                                      tcp0->src_port,
+                                                                      tcp0->dst_port,
+                                                                      SESSION_TYPE_IP6_TCP,
+                                                                      my_thread_index);
+           }
+
+         /* Session exists */
+         if (PREDICT_TRUE (0 != tc0))
+           {
+             /* Save connection index */
+             vnet_buffer (b0)->tcp.connection_index = tc0->c_c_index;
+             vnet_buffer (b0)->tcp.seq_number =
+               clib_net_to_host_u32 (tcp0->seq_number);
+             vnet_buffer (b0)->tcp.ack_number =
+               clib_net_to_host_u32 (tcp0->ack_number);
+
+             flags0 = tcp0->flags & filter_flags;
+             next0 = tm->dispatch_table[tc0->state][flags0].next;
+             error0 = tm->dispatch_table[tc0->state][flags0].error;
+
+             if (PREDICT_FALSE (error0 == TCP_ERROR_DISPATCH))
+               {
+                 /* Overload tcp flags to store state */
+                 vnet_buffer (b0)->tcp.flags = tc0->state;
+               }
+           }
+         else
+           {
+             /* Send reset */
+             next0 = TCP_INPUT_NEXT_RESET;
+             error0 = TCP_ERROR_NO_LISTENER;
+             vnet_buffer (b0)->tcp.flags = 0;
+           }
+
+         b0->error = error0 ? node->errors[error0] : 0;
+
+         if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
+           {
+
+           }
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  return from_frame->n_vectors;
+}
+
+static uword
+tcp4_input (vlib_main_t * vm, vlib_node_runtime_t * node,
+           vlib_frame_t * from_frame)
+{
+  return tcp46_input_inline (vm, node, from_frame, 1 /* is_ip4 */ );
+}
+
+static uword
+tcp6_input (vlib_main_t * vm, vlib_node_runtime_t * node,
+           vlib_frame_t * from_frame)
+{
+  return tcp46_input_inline (vm, node, from_frame, 0 /* is_ip4 */ );
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp4_input_node) =
+{
+  .function = tcp4_input,
+  .name = "tcp4-input",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_INPUT_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_INPUT_NEXT_##s] = n,
+    foreach_tcp4_input_next
+#undef _
+  },
+  .format_buffer = format_tcp_header,
+  .format_trace = format_tcp_rx_trace,
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp4_input_node, tcp4_input);
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp6_input_node) =
+{
+  .function = tcp6_input,
+  .name = "tcp6-input",
+  /* Takes a vector of packets. */
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_INPUT_N_NEXT,
+  .next_nodes =
+  {
+#define _(s,n) [TCP_INPUT_NEXT_##s] = n,
+    foreach_tcp6_input_next
+#undef _
+  },
+  .format_buffer = format_tcp_header,
+  .format_trace = format_tcp_rx_trace,
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp6_input_node, tcp6_input);
+void
+tcp_update_time (f64 now, u32 thread_index)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  tw_timer_expire_timers_16t_2w_512sl (&tm->timer_wheels[thread_index], now);
+}
+
+static void
+tcp_dispatch_table_init (tcp_main_t * tm)
+{
+  int i, j;
+  for (i = 0; i < ARRAY_LEN (tm->dispatch_table); i++)
+    for (j = 0; j < ARRAY_LEN (tm->dispatch_table[i]); j++)
+      {
+       tm->dispatch_table[i][j].next = TCP_INPUT_NEXT_DROP;
+       tm->dispatch_table[i][j].error = TCP_ERROR_DISPATCH;
+      }
+
+#define _(t,f,n,e)                                             \
+do {                                                           \
+    tm->dispatch_table[TCP_STATE_##t][f].next = (n);           \
+    tm->dispatch_table[TCP_STATE_##t][f].error = (e);          \
+} while (0)
+
+  /* SYNs for new connections -> tcp-listen. */
+  _(LISTEN, TCP_FLAG_SYN, TCP_INPUT_NEXT_LISTEN, TCP_ERROR_NONE);
+  /* ACK for for a SYN-ACK -> tcp-rcv-process. */
+  _(SYN_RCVD, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
+  /* SYN-ACK for a SYN */
+  _(SYN_SENT, TCP_FLAG_SYN | TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT,
+    TCP_ERROR_NONE);
+  _(SYN_SENT, TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT, TCP_ERROR_NONE);
+  _(SYN_SENT, TCP_FLAG_RST, TCP_INPUT_NEXT_SYN_SENT, TCP_ERROR_NONE);
+  _(SYN_SENT, TCP_FLAG_RST | TCP_FLAG_ACK, TCP_INPUT_NEXT_SYN_SENT,
+    TCP_ERROR_NONE);
+  /* ACK for for established connection -> tcp-established. */
+  _(ESTABLISHED, TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
+  /* FIN for for established connection -> tcp-established. */
+  _(ESTABLISHED, TCP_FLAG_FIN, TCP_INPUT_NEXT_ESTABLISHED, TCP_ERROR_NONE);
+  _(ESTABLISHED, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_ESTABLISHED,
+    TCP_ERROR_NONE);
+  /* ACK or FIN-ACK to our FIN */
+  _(FIN_WAIT_1, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
+  _(FIN_WAIT_1, TCP_FLAG_ACK | TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS,
+    TCP_ERROR_NONE);
+  /* FIN in reply to our FIN from the other side */
+  _(FIN_WAIT_1, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
+  /* FIN confirming that the peer (app) has closed */
+  _(FIN_WAIT_2, TCP_FLAG_FIN, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
+  _(FIN_WAIT_2, TCP_FLAG_FIN | TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS,
+    TCP_ERROR_NONE);
+  _(LAST_ACK, TCP_FLAG_ACK, TCP_INPUT_NEXT_RCV_PROCESS, TCP_ERROR_NONE);
+#undef _
+}
+
+clib_error_t *
+tcp_input_init (vlib_main_t * vm)
+{
+  clib_error_t *error = 0;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+
+  if ((error = vlib_call_init_function (vm, tcp_init)))
+    return error;
+
+  /* Initialize dispatch table. */
+  tcp_dispatch_table_init (tm);
+
+  return error;
+}
+
+VLIB_INIT_FUNCTION (tcp_input_init);
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp_newreno.c b/src/vnet/tcp/tcp_newreno.c
new file mode 100644 (file)
index 0000000..856dffe
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vnet/tcp/tcp.h>
+
+void
+newreno_congestion (tcp_connection_t * tc)
+{
+  tc->prev_ssthresh = tc->ssthresh;
+  tc->ssthresh = clib_max (tcp_flight_size (tc) / 2, 2 * tc->snd_mss);
+}
+
+void
+newreno_recovered (tcp_connection_t * tc)
+{
+  tc->cwnd = tc->ssthresh;
+}
+
+void
+newreno_rcv_ack (tcp_connection_t * tc)
+{
+  if (tcp_in_slowstart (tc))
+    {
+      tc->cwnd += clib_min (tc->snd_mss, tc->bytes_acked);
+    }
+  else
+    {
+      /* Round up to 1 if needed */
+      tc->cwnd += clib_max (tc->snd_mss * tc->snd_mss / tc->cwnd, 1);
+    }
+}
+
+void
+newreno_rcv_cong_ack (tcp_connection_t * tc, tcp_cc_ack_t ack_type)
+{
+  if (ack_type == TCP_CC_DUPACK)
+    {
+      tc->cwnd += tc->snd_mss;
+    }
+  else if (ack_type == TCP_CC_PARTIALACK)
+    {
+      tc->cwnd -= tc->bytes_acked;
+      if (tc->bytes_acked > tc->snd_mss)
+       tc->bytes_acked += tc->snd_mss;
+    }
+}
+
+void
+newreno_conn_init (tcp_connection_t * tc)
+{
+  tc->ssthresh = tc->snd_wnd;
+  tc->cwnd = tcp_initial_cwnd (tc);
+}
+
+const static tcp_cc_algorithm_t tcp_newreno = {
+  .congestion = newreno_congestion,
+  .recovered = newreno_recovered,
+  .rcv_ack = newreno_rcv_ack,
+  .rcv_cong_ack = newreno_rcv_cong_ack,
+  .init = newreno_conn_init
+};
+
+clib_error_t *
+newreno_init (vlib_main_t * vm)
+{
+  clib_error_t *error = 0;
+
+  tcp_cc_algo_register (TCP_CC_NEWRENO, &tcp_newreno);
+
+  return error;
+}
+
+VLIB_INIT_FUNCTION (newreno_init);
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp_output.c b/src/vnet/tcp/tcp_output.c
new file mode 100644 (file)
index 0000000..dbcf1f7
--- /dev/null
@@ -0,0 +1,1412 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vnet/tcp/tcp.h>
+#include <vnet/lisp-cp/packets.h>
+
+vlib_node_registration_t tcp4_output_node;
+vlib_node_registration_t tcp6_output_node;
+
+typedef enum _tcp_output_nect
+{
+  TCP_OUTPUT_NEXT_DROP,
+  TCP_OUTPUT_NEXT_IP_LOOKUP,
+  TCP_OUTPUT_N_NEXT
+} tcp_output_next_t;
+
+#define foreach_tcp4_output_next               \
+  _ (DROP, "error-drop")                        \
+  _ (IP_LOOKUP, "ip4-lookup")
+
+#define foreach_tcp6_output_next               \
+  _ (DROP, "error-drop")                        \
+  _ (IP_LOOKUP, "ip6-lookup")
+
+static char *tcp_error_strings[] = {
+#define tcp_error(n,s) s,
+#include <vnet/tcp/tcp_error.def>
+#undef tcp_error
+};
+
+typedef struct
+{
+  u16 src_port;
+  u16 dst_port;
+  u8 state;
+} tcp_tx_trace_t;
+
+u16 dummy_mtu = 400;
+
+u8 *
+format_tcp_tx_trace (u8 * s, va_list * args)
+{
+  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+
+  s = format (s, "TBD\n");
+
+  return s;
+}
+
+void
+tcp_set_snd_mss (tcp_connection_t * tc)
+{
+  u16 snd_mss;
+
+  /* TODO find our iface MTU */
+  snd_mss = dummy_mtu;
+
+  /* TODO cache mss and consider PMTU discovery */
+  snd_mss = tc->opt.mss < snd_mss ? tc->opt.mss : snd_mss;
+
+  tc->snd_mss = snd_mss;
+
+  if (tc->snd_mss == 0)
+    {
+      clib_warning ("snd mss is 0");
+      tc->snd_mss = dummy_mtu;
+    }
+}
+
+static u8
+tcp_window_compute_scale (u32 available_space)
+{
+  u8 wnd_scale = 0;
+  while (wnd_scale < TCP_MAX_WND_SCALE
+        && (available_space >> wnd_scale) > TCP_WND_MAX)
+    wnd_scale++;
+  return wnd_scale;
+}
+
+/**
+ * Compute initial window and scale factor. As per RFC1323, window field in
+ * SYN and SYN-ACK segments is never scaled.
+ */
+u32
+tcp_initial_window_to_advertise (tcp_connection_t * tc)
+{
+  u32 available_space;
+
+  /* Initial wnd for SYN. Fifos are not allocated yet.
+   * Use some predefined value */
+  if (tc->state != TCP_STATE_SYN_RCVD)
+    {
+      return TCP_DEFAULT_RX_FIFO_SIZE;
+    }
+
+  available_space = stream_session_max_enqueue (&tc->connection);
+  tc->rcv_wscale = tcp_window_compute_scale (available_space);
+  tc->rcv_wnd = clib_min (available_space, TCP_WND_MAX << tc->rcv_wscale);
+
+  return clib_min (tc->rcv_wnd, TCP_WND_MAX);
+}
+
+/**
+ * Compute and return window to advertise, scaled as per RFC1323
+ */
+u32
+tcp_window_to_advertise (tcp_connection_t * tc, tcp_state_t state)
+{
+  u32 available_space, wnd, scaled_space;
+
+  if (state != TCP_STATE_ESTABLISHED)
+    return tcp_initial_window_to_advertise (tc);
+
+  available_space = stream_session_max_enqueue (&tc->connection);
+  scaled_space = available_space >> tc->rcv_wscale;
+
+  /* Need to update scale */
+  if (PREDICT_FALSE ((scaled_space == 0 && available_space != 0))
+      || (scaled_space >= TCP_WND_MAX))
+    tc->rcv_wscale = tcp_window_compute_scale (available_space);
+
+  wnd = clib_min (available_space, TCP_WND_MAX << tc->rcv_wscale);
+  tc->rcv_wnd = wnd;
+
+  return wnd >> tc->rcv_wscale;
+}
+
+/**
+ * Write TCP options to segment.
+ */
+u32
+tcp_options_write (u8 * data, tcp_options_t * opts)
+{
+  u32 opts_len = 0;
+  u32 buf, seq_len = 4;
+
+  if (tcp_opts_mss (opts))
+    {
+      *data++ = TCP_OPTION_MSS;
+      *data++ = TCP_OPTION_LEN_MSS;
+      buf = clib_host_to_net_u16 (opts->mss);
+      clib_memcpy (data, &buf, sizeof (opts->mss));
+      data += sizeof (opts->mss);
+      opts_len += TCP_OPTION_LEN_MSS;
+    }
+
+  if (tcp_opts_wscale (opts))
+    {
+      *data++ = TCP_OPTION_WINDOW_SCALE;
+      *data++ = TCP_OPTION_LEN_WINDOW_SCALE;
+      *data++ = opts->wscale;
+      opts_len += TCP_OPTION_LEN_WINDOW_SCALE;
+    }
+
+  if (tcp_opts_sack_permitted (opts))
+    {
+      *data++ = TCP_OPTION_SACK_PERMITTED;
+      *data++ = TCP_OPTION_LEN_SACK_PERMITTED;
+      opts_len += TCP_OPTION_LEN_SACK_PERMITTED;
+    }
+
+  if (tcp_opts_tstamp (opts))
+    {
+      *data++ = TCP_OPTION_TIMESTAMP;
+      *data++ = TCP_OPTION_LEN_TIMESTAMP;
+      buf = clib_host_to_net_u32 (opts->tsval);
+      clib_memcpy (data, &buf, sizeof (opts->tsval));
+      data += sizeof (opts->tsval);
+      buf = clib_host_to_net_u32 (opts->tsecr);
+      clib_memcpy (data, &buf, sizeof (opts->tsecr));
+      data += sizeof (opts->tsecr);
+      opts_len += TCP_OPTION_LEN_TIMESTAMP;
+    }
+
+  if (tcp_opts_sack (opts))
+    {
+      int i;
+      u32 n_sack_blocks = clib_min (vec_len (opts->sacks),
+                                   TCP_OPTS_MAX_SACK_BLOCKS);
+
+      if (n_sack_blocks != 0)
+       {
+         *data++ = TCP_OPTION_SACK_BLOCK;
+         *data++ = 2 + n_sack_blocks * TCP_OPTION_LEN_SACK_BLOCK;
+         for (i = 0; i < n_sack_blocks; i++)
+           {
+             buf = clib_host_to_net_u32 (opts->sacks[i].start);
+             clib_memcpy (data, &buf, seq_len);
+             data += seq_len;
+             buf = clib_host_to_net_u32 (opts->sacks[i].end);
+             clib_memcpy (data, &buf, seq_len);
+             data += seq_len;
+           }
+         opts_len += 2 + n_sack_blocks * TCP_OPTION_LEN_SACK_BLOCK;
+       }
+    }
+
+  /* Terminate TCP options */
+  if (opts_len % 4)
+    {
+      *data++ = TCP_OPTION_EOL;
+      opts_len += TCP_OPTION_LEN_EOL;
+    }
+
+  /* Pad with zeroes to a u32 boundary */
+  while (opts_len % 4)
+    {
+      *data++ = TCP_OPTION_NOOP;
+      opts_len += TCP_OPTION_LEN_NOOP;
+    }
+  return opts_len;
+}
+
+always_inline int
+tcp_make_syn_options (tcp_options_t * opts, u32 initial_wnd)
+{
+  u8 len = 0;
+
+  opts->flags |= TCP_OPTS_FLAG_MSS;
+  opts->mss = dummy_mtu;       /*XXX discover that */
+  len += TCP_OPTION_LEN_MSS;
+
+  opts->flags |= TCP_OPTS_FLAG_WSCALE;
+  opts->wscale = tcp_window_compute_scale (initial_wnd);
+  len += TCP_OPTION_LEN_WINDOW_SCALE;
+
+  opts->flags |= TCP_OPTS_FLAG_TSTAMP;
+  opts->tsval = tcp_time_now ();
+  opts->tsecr = 0;
+  len += TCP_OPTION_LEN_TIMESTAMP;
+
+  opts->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
+  len += TCP_OPTION_LEN_SACK_PERMITTED;
+
+  /* Align to needed boundary */
+  len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
+  return len;
+}
+
+always_inline int
+tcp_make_synack_options (tcp_connection_t * tc, tcp_options_t * opts)
+{
+  u8 len = 0;
+
+  opts->flags |= TCP_OPTS_FLAG_MSS;
+  opts->mss = dummy_mtu;       /*XXX discover that */
+  len += TCP_OPTION_LEN_MSS;
+
+  if (tcp_opts_wscale (&tc->opt))
+    {
+      opts->flags |= TCP_OPTS_FLAG_WSCALE;
+      opts->wscale = tc->rcv_wscale;
+      len += TCP_OPTION_LEN_WINDOW_SCALE;
+    }
+
+  if (tcp_opts_tstamp (&tc->opt))
+    {
+      opts->flags |= TCP_OPTS_FLAG_TSTAMP;
+      opts->tsval = tcp_time_now ();
+      opts->tsecr = tc->tsval_recent;
+      len += TCP_OPTION_LEN_TIMESTAMP;
+    }
+
+  if (tcp_opts_sack_permitted (&tc->opt))
+    {
+      opts->flags |= TCP_OPTS_FLAG_SACK_PERMITTED;
+      len += TCP_OPTION_LEN_SACK_PERMITTED;
+    }
+
+  /* Align to needed boundary */
+  len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
+  return len;
+}
+
+always_inline int
+tcp_make_established_options (tcp_connection_t * tc, tcp_options_t * opts)
+{
+  u8 len = 0;
+
+  opts->flags = 0;
+
+  if (tcp_opts_tstamp (&tc->opt))
+    {
+      opts->flags |= TCP_OPTS_FLAG_TSTAMP;
+      opts->tsval = tcp_time_now ();
+      opts->tsecr = tc->tsval_recent;
+      len += TCP_OPTION_LEN_TIMESTAMP;
+    }
+  if (tcp_opts_sack_permitted (&tc->opt))
+    {
+      if (vec_len (tc->snd_sacks))
+       {
+         opts->flags |= TCP_OPTS_FLAG_SACK;
+         opts->sacks = tc->snd_sacks;
+         opts->n_sack_blocks = vec_len (tc->snd_sacks);
+         len += 2 + TCP_OPTION_LEN_SACK_BLOCK * opts->n_sack_blocks;
+       }
+    }
+
+  /* Align to needed boundary */
+  len += (TCP_OPTS_ALIGN - len % TCP_OPTS_ALIGN) % TCP_OPTS_ALIGN;
+  return len;
+}
+
+always_inline int
+tcp_make_options (tcp_connection_t * tc, tcp_options_t * opts,
+                 tcp_state_t state)
+{
+  switch (state)
+    {
+    case TCP_STATE_ESTABLISHED:
+    case TCP_STATE_FIN_WAIT_1:
+      return tcp_make_established_options (tc, opts);
+    case TCP_STATE_SYN_RCVD:
+      return tcp_make_synack_options (tc, opts);
+    case TCP_STATE_SYN_SENT:
+      return tcp_make_syn_options (opts,
+                                  tcp_initial_window_to_advertise (tc));
+    default:
+      clib_warning ("Not handled!");
+      return 0;
+    }
+}
+
+#define tcp_get_free_buffer_index(tm, bidx)                             \
+do {                                                                    \
+  u32 *my_tx_buffers, n_free_buffers;                                   \
+  u32 cpu_index = tm->vlib_main->cpu_index;                             \
+  my_tx_buffers = tm->tx_buffers[cpu_index];                            \
+  if (PREDICT_FALSE(vec_len (my_tx_buffers) == 0))                      \
+    {                                                                   \
+      n_free_buffers = 32;      /* TODO config or macro */              \
+      vec_validate (my_tx_buffers, n_free_buffers - 1);                 \
+      _vec_len(my_tx_buffers) = vlib_buffer_alloc_from_free_list (      \
+          tm->vlib_main, my_tx_buffers, n_free_buffers,                 \
+          VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);                         \
+      tm->tx_buffers[cpu_index] = my_tx_buffers;                        \
+    }                                                                   \
+  /* buffer shortage */                                                 \
+  if (PREDICT_FALSE (vec_len (my_tx_buffers) == 0))                     \
+    return;                                                             \
+  *bidx = my_tx_buffers[_vec_len (my_tx_buffers)-1];                    \
+  _vec_len (my_tx_buffers) -= 1;                                        \
+} while (0)
+
+always_inline void
+tcp_reuse_buffer (vlib_main_t * vm, vlib_buffer_t * b)
+{
+  vlib_buffer_t *it = b;
+  do
+    {
+      it->current_data = 0;
+      it->current_length = 0;
+      it->total_length_not_including_first_buffer = 0;
+    }
+  while ((it->flags & VLIB_BUFFER_NEXT_PRESENT)
+        && (it = vlib_get_buffer (vm, it->next_buffer)));
+
+  /* Leave enough space for headers */
+  vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
+}
+
+/**
+ * Prepare ACK
+ */
+void
+tcp_make_ack_i (tcp_connection_t * tc, vlib_buffer_t * b, tcp_state_t state,
+               u8 flags)
+{
+  tcp_options_t _snd_opts, *snd_opts = &_snd_opts;
+  u8 tcp_opts_len, tcp_hdr_opts_len;
+  tcp_header_t *th;
+  u16 wnd;
+
+  wnd = tcp_window_to_advertise (tc, state);
+
+  /* Make and write options */
+  tcp_opts_len = tcp_make_established_options (tc, snd_opts);
+  tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
+
+  th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->snd_nxt,
+                            tc->rcv_nxt, tcp_hdr_opts_len, flags, wnd);
+
+  tcp_options_write ((u8 *) (th + 1), snd_opts);
+
+  /* Mark as ACK */
+  vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
+}
+
+/**
+ * Convert buffer to ACK
+ */
+void
+tcp_make_ack (tcp_connection_t * tc, vlib_buffer_t * b)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+
+  tcp_reuse_buffer (vm, b);
+  tcp_make_ack_i (tc, b, TCP_STATE_ESTABLISHED, TCP_FLAG_ACK);
+  vnet_buffer (b)->tcp.flags = TCP_BUF_FLAG_ACK;
+}
+
+/**
+ * Convert buffer to FIN-ACK
+ */
+void
+tcp_make_finack (tcp_connection_t * tc, vlib_buffer_t * b)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+
+  tcp_reuse_buffer (vm, b);
+  tcp_make_ack_i (tc, b, TCP_STATE_ESTABLISHED, TCP_FLAG_ACK | TCP_FLAG_FIN);
+
+  /* Reset flags, make sure ack is sent */
+  tc->flags = TCP_CONN_SNDACK;
+  vnet_buffer (b)->tcp.flags &= ~TCP_BUF_FLAG_DUPACK;
+
+  tc->snd_nxt += 1;
+}
+
+/**
+ * Convert buffer to SYN-ACK
+ */
+void
+tcp_make_synack (tcp_connection_t * tc, vlib_buffer_t * b)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+  tcp_options_t _snd_opts, *snd_opts = &_snd_opts;
+  u8 tcp_opts_len, tcp_hdr_opts_len;
+  tcp_header_t *th;
+  u16 initial_wnd;
+  u32 time_now;
+
+  memset (snd_opts, 0, sizeof (*snd_opts));
+
+  tcp_reuse_buffer (vm, b);
+
+  /* Set random initial sequence */
+  time_now = tcp_time_now ();
+
+  tc->iss = random_u32 (&time_now);
+  tc->snd_una = tc->iss;
+  tc->snd_nxt = tc->iss + 1;
+  tc->snd_una_max = tc->snd_nxt;
+
+  initial_wnd = tcp_initial_window_to_advertise (tc);
+
+  /* Make and write options */
+  tcp_opts_len = tcp_make_synack_options (tc, snd_opts);
+  tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
+
+  th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->iss,
+                            tc->rcv_nxt, tcp_hdr_opts_len,
+                            TCP_FLAG_SYN | TCP_FLAG_ACK, initial_wnd);
+
+  tcp_options_write ((u8 *) (th + 1), snd_opts);
+
+  vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
+  vnet_buffer (b)->tcp.flags = TCP_BUF_FLAG_ACK;
+
+  /* Init retransmit timer */
+  tcp_retransmit_timer_set (tm, tc);
+}
+
+always_inline void
+tcp_enqueue_to_ip_lookup (vlib_main_t * vm, vlib_buffer_t * b, u32 bi,
+                         u8 is_ip4)
+{
+  u32 *to_next, next_index;
+  vlib_frame_t *f;
+
+  b->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
+  b->error = 0;
+
+  /* Default FIB for now */
+  vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
+
+  /* Send to IP lookup */
+  next_index = is_ip4 ? ip4_lookup_node.index : ip6_lookup_node.index;
+  f = vlib_get_frame_to_node (vm, next_index);
+
+  /* Enqueue the packet */
+  to_next = vlib_frame_vector_args (f);
+  to_next[0] = bi;
+  f->n_vectors = 1;
+  vlib_put_frame_to_node (vm, next_index, f);
+}
+
+int
+tcp_make_reset_in_place (vlib_main_t * vm, vlib_buffer_t * b0,
+                        tcp_state_t state, u32 my_thread_index, u8 is_ip4)
+{
+  u8 tcp_hdr_len = sizeof (tcp_header_t);
+  ip4_header_t *ih4;
+  ip6_header_t *ih6;
+  tcp_header_t *th0;
+  ip4_address_t src_ip40;
+  ip6_address_t src_ip60;
+  u16 src_port0;
+  u32 tmp;
+
+  /* Find IP and TCP headers */
+  if (is_ip4)
+    {
+      ih4 = vlib_buffer_get_current (b0);
+      th0 = ip4_next_header (ih4);
+    }
+  else
+    {
+      ih6 = vlib_buffer_get_current (b0);
+      th0 = ip6_next_header (ih6);
+    }
+
+  /* Swap src and dst ip */
+  if (is_ip4)
+    {
+      ASSERT ((ih4->ip_version_and_header_length & 0xF0) == 0x40);
+      src_ip40.as_u32 = ih4->src_address.as_u32;
+      ih4->src_address.as_u32 = ih4->dst_address.as_u32;
+      ih4->dst_address.as_u32 = src_ip40.as_u32;
+
+      /* Chop the end of the pkt */
+      b0->current_length += ip4_header_bytes (ih4) + tcp_hdr_len;
+    }
+  else
+    {
+      ASSERT ((ih6->ip_version_traffic_class_and_flow_label & 0xF0) == 0x60);
+      clib_memcpy (&src_ip60, &ih6->src_address, sizeof (ip6_address_t));
+      clib_memcpy (&ih6->src_address, &ih6->dst_address,
+                  sizeof (ip6_address_t));
+      clib_memcpy (&ih6->dst_address, &src_ip60, sizeof (ip6_address_t));
+
+      /* Chop the end of the pkt */
+      b0->current_length += sizeof (ip6_header_t) + tcp_hdr_len;
+    }
+
+  /* Try to determine what/why we're actually resetting and swap
+   * src and dst ports */
+  if (state == TCP_STATE_CLOSED)
+    {
+      if (!tcp_syn (th0))
+       return -1;
+
+      tmp = clib_net_to_host_u32 (th0->seq_number);
+
+      /* Got a SYN for no listener. */
+      th0->flags = TCP_FLAG_RST | TCP_FLAG_ACK;
+      th0->ack_number = clib_host_to_net_u32 (tmp + 1);
+      th0->seq_number = 0;
+
+    }
+  else if (state >= TCP_STATE_SYN_SENT)
+    {
+      th0->flags = TCP_FLAG_RST | TCP_FLAG_ACK;
+      th0->seq_number = th0->ack_number;
+      th0->ack_number = 0;
+    }
+
+  src_port0 = th0->src_port;
+  th0->src_port = th0->dst_port;
+  th0->dst_port = src_port0;
+  th0->window = 0;
+  th0->data_offset_and_reserved = (tcp_hdr_len >> 2) << 4;
+  th0->urgent_pointer = 0;
+
+  /* Compute checksum */
+  if (is_ip4)
+    {
+      th0->checksum = ip4_tcp_udp_compute_checksum (vm, b0, ih4);
+    }
+  else
+    {
+      int bogus = ~0;
+      th0->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b0, ih6, &bogus);
+      ASSERT (!bogus);
+    }
+
+  return 0;
+}
+
+/**
+ *  Send reset without reusing existing buffer
+ */
+void
+tcp_send_reset (vlib_buffer_t * pkt, u8 is_ip4)
+{
+  vlib_buffer_t *b;
+  u32 bi;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+  u8 tcp_hdr_len, flags = 0;
+  tcp_header_t *th, *pkt_th;
+  u32 seq, ack;
+  ip4_header_t *ih4, *pkt_ih4;
+  ip6_header_t *ih6, *pkt_ih6;
+
+  tcp_get_free_buffer_index (tm, &bi);
+  b = vlib_get_buffer (vm, bi);
+
+  /* Leave enough space for headers */
+  vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
+
+  /* Make and write options */
+  tcp_hdr_len = sizeof (tcp_header_t);
+
+  if (is_ip4)
+    {
+      pkt_ih4 = vlib_buffer_get_current (pkt);
+      pkt_th = ip4_next_header (pkt_ih4);
+    }
+  else
+    {
+      pkt_ih6 = vlib_buffer_get_current (pkt);
+      pkt_th = ip6_next_header (pkt_ih6);
+    }
+
+  if (tcp_ack (pkt_th))
+    {
+      flags = TCP_FLAG_RST;
+      seq = pkt_th->ack_number;
+      ack = 0;
+    }
+  else
+    {
+      flags = TCP_FLAG_RST | TCP_FLAG_ACK;
+      seq = 0;
+      ack = clib_host_to_net_u32 (vnet_buffer (pkt)->tcp.seq_end);
+    }
+
+  th = vlib_buffer_push_tcp_net_order (b, pkt_th->dst_port, pkt_th->src_port,
+                                      seq, ack, tcp_hdr_len, flags, 0);
+
+  /* Swap src and dst ip */
+  if (is_ip4)
+    {
+      ASSERT ((pkt_ih4->ip_version_and_header_length & 0xF0) == 0x40);
+      ih4 = vlib_buffer_push_ip4 (vm, b, &pkt_ih4->dst_address,
+                                 &pkt_ih4->src_address, IP_PROTOCOL_TCP);
+      th->checksum = ip4_tcp_udp_compute_checksum (vm, b, ih4);
+    }
+  else
+    {
+      int bogus = ~0;
+      pkt_ih6 = (ip6_header_t *) (pkt_th - 1);
+      ASSERT ((pkt_ih6->ip_version_traffic_class_and_flow_label & 0xF0) ==
+             0x60);
+      ih6 =
+       vlib_buffer_push_ip6 (vm, b, &pkt_ih6->dst_address,
+                             &pkt_ih6->src_address, IP_PROTOCOL_TCP);
+      th->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b, ih6, &bogus);
+      ASSERT (!bogus);
+    }
+
+  tcp_enqueue_to_ip_lookup (vm, b, bi, is_ip4);
+}
+
+void
+tcp_push_ip_hdr (tcp_main_t * tm, tcp_connection_t * tc, vlib_buffer_t * b)
+{
+  tcp_header_t *th = vlib_buffer_get_current (b);
+
+  if (tc->c_is_ip4)
+    {
+      ip4_header_t *ih;
+      ih = vlib_buffer_push_ip4 (tm->vlib_main, b, &tc->c_lcl_ip4,
+                                &tc->c_rmt_ip4, IP_PROTOCOL_TCP);
+      th->checksum = ip4_tcp_udp_compute_checksum (tm->vlib_main, b, ih);
+    }
+  else
+    {
+      ip6_header_t *ih;
+      int bogus = ~0;
+
+      ih = vlib_buffer_push_ip6 (tm->vlib_main, b, &tc->c_lcl_ip6,
+                                &tc->c_rmt_ip6, IP_PROTOCOL_TCP);
+      th->checksum = ip6_tcp_udp_icmp_compute_checksum (tm->vlib_main, b, ih,
+                                                       &bogus);
+      ASSERT (!bogus);
+    }
+}
+
+/**
+ *  Send SYN
+ *
+ *  Builds a SYN packet for a half-open connection and sends it to ipx_lookup.
+ *  The packet is not forwarded through tcpx_output to avoid doing lookups
+ *  in the half_open pool.
+ */
+void
+tcp_send_syn (tcp_connection_t * tc)
+{
+  vlib_buffer_t *b;
+  u32 bi;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+  u8 tcp_hdr_opts_len, tcp_opts_len;
+  tcp_header_t *th;
+  u32 time_now;
+  u16 initial_wnd;
+  tcp_options_t snd_opts;
+
+  tcp_get_free_buffer_index (tm, &bi);
+  b = vlib_get_buffer (vm, bi);
+
+  /* Leave enough space for headers */
+  vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
+
+  /* Set random initial sequence */
+  time_now = tcp_time_now ();
+
+  tc->iss = random_u32 (&time_now);
+  tc->snd_una = tc->iss;
+  tc->snd_una_max = tc->snd_nxt = tc->iss + 1;
+
+  initial_wnd = tcp_initial_window_to_advertise (tc);
+
+  /* Make and write options */
+  memset (&snd_opts, 0, sizeof (snd_opts));
+  tcp_opts_len = tcp_make_syn_options (&snd_opts, initial_wnd);
+  tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
+
+  th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->iss,
+                            tc->rcv_nxt, tcp_hdr_opts_len, TCP_FLAG_SYN,
+                            initial_wnd);
+
+  tcp_options_write ((u8 *) (th + 1), &snd_opts);
+
+  /* Measure RTT with this */
+  tc->rtt_ts = tcp_time_now ();
+  tc->rtt_seq = tc->snd_nxt;
+
+  /* Start retransmit trimer  */
+  tcp_timer_set (tc, TCP_TIMER_RETRANSMIT_SYN, tc->rto * TCP_TO_TIMER_TICK);
+  tc->rto_boff = 0;
+
+  /* Set the connection establishment timer */
+  tcp_timer_set (tc, TCP_TIMER_ESTABLISH, TCP_ESTABLISH_TIME);
+
+  tcp_push_ip_hdr (tm, tc, b);
+  tcp_enqueue_to_ip_lookup (vm, b, bi, tc->c_is_ip4);
+}
+
+always_inline void
+tcp_enqueue_to_output (vlib_main_t * vm, vlib_buffer_t * b, u32 bi, u8 is_ip4)
+{
+  u32 *to_next, next_index;
+  vlib_frame_t *f;
+
+  b->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
+  b->error = 0;
+
+  /* Decide where to send the packet */
+  next_index = is_ip4 ? tcp4_output_node.index : tcp6_output_node.index;
+  f = vlib_get_frame_to_node (vm, next_index);
+
+  /* Enqueue the packet */
+  to_next = vlib_frame_vector_args (f);
+  to_next[0] = bi;
+  f->n_vectors = 1;
+  vlib_put_frame_to_node (vm, next_index, f);
+}
+
+/**
+ *  Send FIN
+ */
+void
+tcp_send_fin (tcp_connection_t * tc)
+{
+  vlib_buffer_t *b;
+  u32 bi;
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+
+  tcp_get_free_buffer_index (tm, &bi);
+  b = vlib_get_buffer (vm, bi);
+
+  /* Leave enough space for headers */
+  vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
+
+  tcp_make_finack (tc, b);
+
+  tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
+}
+
+always_inline u8
+tcp_make_state_flags (tcp_state_t next_state)
+{
+  switch (next_state)
+    {
+    case TCP_STATE_ESTABLISHED:
+      return TCP_FLAG_ACK;
+    case TCP_STATE_SYN_RCVD:
+      return TCP_FLAG_SYN | TCP_FLAG_ACK;
+    case TCP_STATE_SYN_SENT:
+      return TCP_FLAG_SYN;
+    case TCP_STATE_LAST_ACK:
+    case TCP_STATE_FIN_WAIT_1:
+      return TCP_FLAG_FIN;
+    default:
+      clib_warning ("Shouldn't be here!");
+    }
+  return 0;
+}
+
+/**
+ * Push TCP header and update connection variables
+ */
+static void
+tcp_push_hdr_i (tcp_connection_t * tc, vlib_buffer_t * b,
+               tcp_state_t next_state)
+{
+  u32 advertise_wnd, data_len;
+  u8 tcp_opts_len, tcp_hdr_opts_len, opts_write_len, flags;
+  tcp_options_t _snd_opts, *snd_opts = &_snd_opts;
+  tcp_header_t *th;
+
+  data_len = b->current_length;
+  vnet_buffer (b)->tcp.flags = 0;
+
+  /* Make and write options */
+  memset (snd_opts, 0, sizeof (*snd_opts));
+  tcp_opts_len = tcp_make_options (tc, snd_opts, next_state);
+  tcp_hdr_opts_len = tcp_opts_len + sizeof (tcp_header_t);
+
+  /* Get rcv window to advertise */
+  advertise_wnd = tcp_window_to_advertise (tc, next_state);
+  flags = tcp_make_state_flags (next_state);
+
+  /* Push header and options */
+  th = vlib_buffer_push_tcp (b, tc->c_lcl_port, tc->c_rmt_port, tc->snd_nxt,
+                            tc->rcv_nxt, tcp_hdr_opts_len, flags,
+                            advertise_wnd);
+
+  opts_write_len = tcp_options_write ((u8 *) (th + 1), snd_opts);
+
+  ASSERT (opts_write_len == tcp_opts_len);
+
+  /* Tag the buffer with the connection index  */
+  vnet_buffer (b)->tcp.connection_index = tc->c_c_index;
+
+  tc->snd_nxt += data_len;
+}
+
+/* Send delayed ACK when timer expires */
+void
+tcp_timer_delack_handler (u32 index)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+  u32 thread_index = os_get_cpu_number ();
+  tcp_connection_t *tc;
+  vlib_buffer_t *b;
+  u32 bi;
+
+  tc = tcp_connection_get (index, thread_index);
+
+  /* Get buffer */
+  tcp_get_free_buffer_index (tm, &bi);
+  b = vlib_get_buffer (vm, bi);
+
+  /* Fill in the ACK */
+  tcp_make_ack (tc, b);
+
+  tc->timers[TCP_TIMER_DELACK] = TCP_TIMER_HANDLE_INVALID;
+  tc->flags &= ~TCP_CONN_DELACK;
+
+  tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
+}
+
+/** Build a retransmit segment
+ *
+ * @return the number of bytes in the segment or 0 if there's nothing to
+ *         retransmit
+ * */
+u32
+tcp_prepare_retransmit_segment (tcp_connection_t * tc, vlib_buffer_t * b,
+                               u32 max_bytes)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+  u32 n_bytes, offset = 0;
+  sack_scoreboard_hole_t *hole;
+  u32 hole_size;
+
+  tcp_reuse_buffer (vm, b);
+
+  ASSERT (tc->state == TCP_STATE_ESTABLISHED);
+  ASSERT (max_bytes != 0);
+
+  if (tcp_opts_sack_permitted (&tc->opt))
+    {
+      /* XXX get first hole not retransmitted yet  */
+      hole = scoreboard_first_hole (&tc->sack_sb);
+      if (!hole)
+       return 0;
+
+      offset = hole->start - tc->snd_una;
+      hole_size = hole->end - hole->start;
+
+      ASSERT (hole_size);
+
+      if (hole_size < max_bytes)
+       max_bytes = hole_size;
+    }
+  else
+    {
+      if (seq_geq (tc->snd_nxt, tc->snd_una_max))
+       return 0;
+    }
+
+  n_bytes = stream_session_peek_bytes (&tc->connection,
+                                      vlib_buffer_get_current (b), offset,
+                                      max_bytes);
+  ASSERT (n_bytes != 0);
+
+  tc->snd_nxt += n_bytes;
+  tcp_push_hdr_i (tc, b, tc->state);
+
+  return n_bytes;
+}
+
+static void
+tcp_timer_retransmit_handler_i (u32 index, u8 is_syn)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  vlib_main_t *vm = tm->vlib_main;
+  u32 thread_index = os_get_cpu_number ();
+  tcp_connection_t *tc;
+  vlib_buffer_t *b;
+  u32 bi, max_bytes, snd_space;
+
+  if (is_syn)
+    {
+      tc = tcp_half_open_connection_get (index);
+    }
+  else
+    {
+      tc = tcp_connection_get (index, thread_index);
+    }
+
+  /* Make sure timer handle is set to invalid */
+  tc->timers[TCP_TIMER_RETRANSMIT] = TCP_TIMER_HANDLE_INVALID;
+
+  /* Increment RTO backoff (also equal to number of retries) */
+  tc->rto_boff += 1;
+
+  /* Go back to first un-acked byte */
+  tc->snd_nxt = tc->snd_una;
+
+  /* Get buffer */
+  tcp_get_free_buffer_index (tm, &bi);
+  b = vlib_get_buffer (vm, bi);
+
+  if (tc->state == TCP_STATE_ESTABLISHED)
+    {
+      tcp_fastrecovery_off (tc);
+
+      /* Exponential backoff */
+      tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
+
+      /* Figure out what and how many bytes we can send */
+      snd_space = tcp_available_snd_space (tc);
+      max_bytes = clib_min (tc->snd_mss, snd_space);
+      tcp_prepare_retransmit_segment (tc, b, max_bytes);
+
+      tc->rtx_bytes += max_bytes;
+
+      /* No fancy recovery for now! */
+      scoreboard_clear (&tc->sack_sb);
+    }
+  else
+    {
+      /* Retransmit for SYN/SYNACK */
+      ASSERT (tc->state == TCP_STATE_SYN_RCVD
+             || tc->state == TCP_STATE_SYN_SENT);
+
+      /* Try without increasing RTO a number of times. If this fails,
+       * start growing RTO exponentially */
+      if (tc->rto_boff > TCP_RTO_SYN_RETRIES)
+       tc->rto = clib_min (tc->rto << 1, TCP_RTO_MAX);
+
+      vlib_buffer_make_headroom (b, MAX_HDRS_LEN);
+      tcp_push_hdr_i (tc, b, tc->state);
+    }
+
+  if (!is_syn)
+    {
+      tcp_enqueue_to_output (vm, b, bi, tc->c_is_ip4);
+
+      /* Re-enable retransmit timer */
+      tcp_retransmit_timer_set (tm, tc);
+    }
+  else
+    {
+      ASSERT (tc->state == TCP_STATE_SYN_SENT);
+
+      /* This goes straight to ipx_lookup */
+      tcp_push_ip_hdr (tm, tc, b);
+      tcp_enqueue_to_ip_lookup (vm, b, bi, tc->c_is_ip4);
+
+      /* Re-enable retransmit timer */
+      tcp_timer_set (tc, TCP_TIMER_RETRANSMIT_SYN,
+                    tc->rto * TCP_TO_TIMER_TICK);
+    }
+}
+
+void
+tcp_timer_retransmit_handler (u32 index)
+{
+  tcp_timer_retransmit_handler_i (index, 0);
+}
+
+void
+tcp_timer_retransmit_syn_handler (u32 index)
+{
+  tcp_timer_retransmit_handler_i (index, 1);
+}
+
+/**
+ * Retansmit first unacked segment */
+void
+tcp_retransmit_first_unacked (tcp_connection_t * tc)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  u32 snd_nxt = tc->snd_nxt;
+  vlib_buffer_t *b;
+  u32 bi;
+
+  tc->snd_nxt = tc->snd_una;
+
+  /* Get buffer */
+  tcp_get_free_buffer_index (tm, &bi);
+  b = vlib_get_buffer (tm->vlib_main, bi);
+
+  tcp_prepare_retransmit_segment (tc, b, tc->snd_mss);
+  tcp_enqueue_to_output (tm->vlib_main, b, bi, tc->c_is_ip4);
+
+  tc->snd_nxt = snd_nxt;
+  tc->rtx_bytes += tc->snd_mss;
+}
+
+void
+tcp_fast_retransmit (tcp_connection_t * tc)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  u32 snd_space, max_bytes, n_bytes, bi;
+  vlib_buffer_t *b;
+
+  ASSERT (tcp_in_fastrecovery (tc));
+
+  clib_warning ("fast retransmit!");
+
+  /* Start resending from first un-acked segment */
+  tc->snd_nxt = tc->snd_una;
+
+  snd_space = tcp_available_snd_space (tc);
+
+  while (snd_space)
+    {
+      tcp_get_free_buffer_index (tm, &bi);
+      b = vlib_get_buffer (tm->vlib_main, bi);
+
+      max_bytes = clib_min (tc->snd_mss, snd_space);
+      n_bytes = tcp_prepare_retransmit_segment (tc, b, max_bytes);
+
+      /* Nothing left to retransmit */
+      if (n_bytes == 0)
+       return;
+
+      tcp_enqueue_to_output (tm->vlib_main, b, bi, tc->c_is_ip4);
+
+      snd_space -= n_bytes;
+    }
+
+  /* If window allows, send new data */
+  tc->snd_nxt = tc->snd_una_max;
+}
+
+always_inline u32
+tcp_session_has_ooo_data (tcp_connection_t * tc)
+{
+  stream_session_t *s =
+    stream_session_get (tc->c_s_index, tc->c_thread_index);
+  return svm_fifo_has_ooo_data (s->server_rx_fifo);
+}
+
+always_inline uword
+tcp46_output_inline (vlib_main_t * vm,
+                    vlib_node_runtime_t * node,
+                    vlib_frame_t * from_frame, int is_ip4)
+{
+  tcp_main_t *tm = vnet_get_tcp_main ();
+  u32 n_left_from, next_index, *from, *to_next;
+  u32 my_thread_index = vm->cpu_index;
+
+  from = vlib_frame_vector_args (from_frame);
+  n_left_from = from_frame->n_vectors;
+
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         tcp_connection_t *tc0;
+         tcp_header_t *th0;
+         u32 error0 = TCP_ERROR_PKTS_SENT, next0 = TCP_OUTPUT_NEXT_IP_LOOKUP;
+
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+         tc0 = tcp_connection_get (vnet_buffer (b0)->tcp.connection_index,
+                                   my_thread_index);
+         th0 = vlib_buffer_get_current (b0);
+
+         if (is_ip4)
+           {
+             ip4_header_t *ih0;
+             ih0 = vlib_buffer_push_ip4 (vm, b0, &tc0->c_lcl_ip4,
+                                         &tc0->c_rmt_ip4, IP_PROTOCOL_TCP);
+             th0->checksum = ip4_tcp_udp_compute_checksum (vm, b0, ih0);
+           }
+         else
+           {
+             ip6_header_t *ih0;
+             int bogus = ~0;
+
+             ih0 = vlib_buffer_push_ip6 (vm, b0, &tc0->c_lcl_ip6,
+                                         &tc0->c_rmt_ip6, IP_PROTOCOL_TCP);
+             th0->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b0, ih0,
+                                                                &bogus);
+             ASSERT (!bogus);
+           }
+
+         /* Filter out DUPACKs if there are no OOO segments left */
+         if (PREDICT_FALSE
+             (vnet_buffer (b0)->tcp.flags & TCP_BUF_FLAG_DUPACK))
+           {
+             tc0->snt_dupacks--;
+             ASSERT (tc0->snt_dupacks >= 0);
+             if (!tcp_session_has_ooo_data (tc0))
+               {
+                 error0 = TCP_ERROR_FILTERED_DUPACKS;
+                 next0 = TCP_OUTPUT_NEXT_DROP;
+                 goto done;
+               }
+           }
+
+         /* Retransmitted SYNs do reach this but it should be harmless */
+         tc0->rcv_las = tc0->rcv_nxt;
+
+         /* Stop DELACK timer and fix flags */
+         tc0->flags &=
+           ~(TCP_CONN_SNDACK | TCP_CONN_DELACK | TCP_CONN_BURSTACK);
+         if (tcp_timer_is_active (tc0, TCP_TIMER_DELACK))
+           {
+             tcp_timer_reset (tc0, TCP_TIMER_DELACK);
+           }
+
+         /* If not retransmitting
+          * 1) update snd_una_max (SYN, SYNACK, new data, FIN)
+          * 2) If we're not tracking an ACK, start tracking */
+         if (seq_lt (tc0->snd_una_max, tc0->snd_nxt))
+           {
+             tc0->snd_una_max = tc0->snd_nxt;
+             if (tc0->rtt_ts == 0)
+               {
+                 tc0->rtt_ts = tcp_time_now ();
+                 tc0->rtt_seq = tc0->snd_nxt;
+               }
+           }
+
+         /* Set the retransmit timer if not set already and not
+          * doing a pure ACK */
+         if (!tcp_timer_is_active (tc0, TCP_TIMER_RETRANSMIT)
+             && tc0->snd_nxt != tc0->snd_una)
+           {
+             tcp_retransmit_timer_set (tm, tc0);
+             tc0->rto_boff = 0;
+           }
+
+         /* set fib index to default and lookup node */
+         /* XXX network virtualization (vrf/vni) */
+         vnet_buffer (b0)->sw_if_index[VLIB_RX] = 0;
+         vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
+
+         b0->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
+
+       done:
+         b0->error = error0 != 0 ? node->errors[error0] : 0;
+         if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
+           {
+
+           }
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  return from_frame->n_vectors;
+}
+
+static uword
+tcp4_output (vlib_main_t * vm, vlib_node_runtime_t * node,
+            vlib_frame_t * from_frame)
+{
+  return tcp46_output_inline (vm, node, from_frame, 1 /* is_ip4 */ );
+}
+
+static uword
+tcp6_output (vlib_main_t * vm, vlib_node_runtime_t * node,
+            vlib_frame_t * from_frame)
+{
+  return tcp46_output_inline (vm, node, from_frame, 0 /* is_ip4 */ );
+}
+
+VLIB_REGISTER_NODE (tcp4_output_node) =
+{
+  .function = tcp4_output,.name = "tcp4-output",
+    /* Takes a vector of packets. */
+    .vector_size = sizeof (u32),.n_errors = TCP_N_ERROR,.error_strings =
+    tcp_error_strings,.n_next_nodes = TCP_OUTPUT_N_NEXT,.next_nodes =
+  {
+#define _(s,n) [TCP_OUTPUT_NEXT_##s] = n,
+    foreach_tcp4_output_next
+#undef _
+  }
+,.format_buffer = format_tcp_header,.format_trace = format_tcp_tx_trace,};
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp4_output_node, tcp4_output)
+VLIB_REGISTER_NODE (tcp6_output_node) =
+{
+  .function = tcp6_output,.name = "tcp6-output",
+    /* Takes a vector of packets. */
+    .vector_size = sizeof (u32),.n_errors = TCP_N_ERROR,.error_strings =
+    tcp_error_strings,.n_next_nodes = TCP_OUTPUT_N_NEXT,.next_nodes =
+  {
+#define _(s,n) [TCP_OUTPUT_NEXT_##s] = n,
+    foreach_tcp6_output_next
+#undef _
+  }
+,.format_buffer = format_tcp_header,.format_trace = format_tcp_tx_trace,};
+
+VLIB_NODE_FUNCTION_MULTIARCH (tcp6_output_node, tcp6_output) u32
+tcp_push_header (transport_connection_t * tconn, vlib_buffer_t * b)
+{
+  tcp_connection_t *tc;
+
+  tc = (tcp_connection_t *) tconn;
+  tcp_push_hdr_i (tc, b, TCP_STATE_ESTABLISHED);
+  return 0;
+}
+
+typedef enum _tcp_reset_next
+{
+  TCP_RESET_NEXT_DROP,
+  TCP_RESET_NEXT_IP_LOOKUP,
+  TCP_RESET_N_NEXT
+} tcp_reset_next_t;
+
+#define foreach_tcp4_reset_next                \
+  _(DROP, "error-drop")                 \
+  _(IP_LOOKUP, "ip4-lookup")
+
+#define foreach_tcp6_reset_next                \
+  _(DROP, "error-drop")                 \
+  _(IP_LOOKUP, "ip6-lookup")
+
+static uword
+tcp46_send_reset_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
+                        vlib_frame_t * from_frame, u8 is_ip4)
+{
+  u32 n_left_from, next_index, *from, *to_next;
+  u32 my_thread_index = vm->cpu_index;
+
+  from = vlib_frame_vector_args (from_frame);
+  n_left_from = from_frame->n_vectors;
+
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         u32 error0 = TCP_ERROR_RST_SENT, next0 = TCP_RESET_NEXT_IP_LOOKUP;
+
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+
+         if (tcp_make_reset_in_place (vm, b0, vnet_buffer (b0)->tcp.flags,
+                                      my_thread_index, is_ip4))
+           {
+             error0 = TCP_ERROR_LOOKUP_DROPS;
+             next0 = TCP_RESET_NEXT_DROP;
+             goto done;
+           }
+
+         /* Prepare to send to IP lookup */
+         vnet_buffer (b0)->sw_if_index[VLIB_TX] = 0;
+         next0 = TCP_RESET_NEXT_IP_LOOKUP;
+
+       done:
+         b0->error = error0 != 0 ? node->errors[error0] : 0;
+         b0->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
+         if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
+           {
+
+           }
+
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
+                                          n_left_to_next, bi0, next0);
+       }
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+  return from_frame->n_vectors;
+}
+
+static uword
+tcp4_send_reset (vlib_main_t * vm, vlib_node_runtime_t * node,
+                vlib_frame_t * from_frame)
+{
+  return tcp46_send_reset_inline (vm, node, from_frame, 1);
+}
+
+static uword
+tcp6_send_reset (vlib_main_t * vm, vlib_node_runtime_t * node,
+                vlib_frame_t * from_frame)
+{
+  return tcp46_send_reset_inline (vm, node, from_frame, 0);
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp4_reset_node) = {
+  .function = tcp4_send_reset,
+  .name = "tcp4-reset",
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_RESET_N_NEXT,
+  .next_nodes = {
+#define _(s,n) [TCP_RESET_NEXT_##s] = n,
+    foreach_tcp4_reset_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (tcp6_reset_node) = {
+  .function = tcp6_send_reset,
+  .name = "tcp6-reset",
+  .vector_size = sizeof (u32),
+  .n_errors = TCP_N_ERROR,
+  .error_strings = tcp_error_strings,
+  .n_next_nodes = TCP_RESET_N_NEXT,
+  .next_nodes = {
+#define _(s,n) [TCP_RESET_NEXT_##s] = n,
+    foreach_tcp6_reset_next
+#undef _
+  },
+};
+/* *INDENT-ON* */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp_packet.h b/src/vnet/tcp/tcp_packet.h
new file mode 100644 (file)
index 0000000..866c5fd
--- /dev/null
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef included_tcp_packet_h
+#define included_tcp_packet_h
+
+#include <vnet/vnet.h>
+
+/* TCP flags bit 0 first. */
+#define foreach_tcp_flag                                \
+  _ (FIN) /**< No more data from sender. */             \
+  _ (SYN) /**< Synchronize sequence numbers. */         \
+  _ (RST) /**< Reset the connection. */                 \
+  _ (PSH) /**< Push function. */                        \
+  _ (ACK) /**< Ack field significant. */                \
+  _ (URG) /**< Urgent pointer field significant. */     \
+  _ (ECE) /**< ECN-echo. Receiver got CE packet */      \
+  _ (CWR) /**< Sender reduced congestion window */
+
+enum
+{
+#define _(f) TCP_FLAG_BIT_##f,
+  foreach_tcp_flag
+#undef _
+    TCP_N_FLAG_BITS,
+};
+
+enum
+{
+#define _(f) TCP_FLAG_##f = 1 << TCP_FLAG_BIT_##f,
+  foreach_tcp_flag
+#undef _
+};
+
+typedef struct _tcp_header
+{
+  union
+  {
+    struct
+    {
+      u16 src_port; /**< Source port. */
+      u16 dst_port; /**< Destination port. */
+    };
+    struct
+    {
+      u16 src, dst;
+    };
+  };
+
+  u32 seq_number;      /**< Sequence number of the first data octet in this
+                         *   segment, except when SYN is present. If SYN
+                         *   is present the seq number is is the ISN and the
+                         *   first data octet is ISN+1 */
+  u32 ack_number;      /**< Acknowledgement number if ACK is set. It contains
+                         *   the value of the next sequence number the sender
+                         *   of the segment is expecting to receive. */
+  u8 data_offset_and_reserved;
+  u8 flags;            /**< Flags: see the macro above */
+  u16 window;          /**< Number of bytes sender is willing to receive. */
+
+  u16 checksum;                /**< Checksum of TCP pseudo header and data. */
+  u16 urgent_pointer;  /**< Seq number of the byte after the urgent data. */
+} __attribute__ ((packed)) tcp_header_t;
+
+/* Flag tests that return 0 or !0 */
+#define tcp_doff(_th) ((_th)->data_offset_and_reserved >> 4)
+#define tcp_fin(_th) ((_th)->flags & TCP_FLAG_FIN)
+#define tcp_syn(_th) ((_th)->flags & TCP_FLAG_SYN)
+#define tcp_rst(_th) ((_th)->flags & TCP_FLAG_RST)
+#define tcp_psh(_th) ((_th)->flags & TCP_FLAG_PSH)
+#define tcp_ack(_th) ((_th)->flags & TCP_FLAG_ACK)
+#define tcp_urg(_th) ((_th)->flags & TCP_FLAG_URG)
+#define tcp_ece(_th) ((_th)->flags & TCP_FLAG_ECE)
+#define tcp_cwr(_th) ((_th)->flags & TCP_FLAG_CWR)
+
+/* Flag tests that return 0 or 1 */
+#define tcp_is_syn(_th) !!((_th)->flags & TCP_FLAG_SYN)
+#define tcp_is_fin(_th) !!((_th)->flags & TCP_FLAG_FIN)
+
+always_inline int
+tcp_header_bytes (tcp_header_t * t)
+{
+  return tcp_doff (t) * sizeof (u32);
+}
+
+/*
+ * TCP options.
+ */
+
+typedef enum tcp_option_type
+{
+  TCP_OPTION_EOL = 0,                  /**< End of options. */
+  TCP_OPTION_NOOP = 1,                 /**< No operation. */
+  TCP_OPTION_MSS = 2,                  /**< Limit MSS. */
+  TCP_OPTION_WINDOW_SCALE = 3,         /**< Window scale. */
+  TCP_OPTION_SACK_PERMITTED = 4,       /**< Selective Ack permitted. */
+  TCP_OPTION_SACK_BLOCK = 5,           /**< Selective Ack block. */
+  TCP_OPTION_TIMESTAMP = 8,            /**< Timestamps. */
+  TCP_OPTION_UTO = 28,                 /**< User timeout. */
+  TCP_OPTION_AO = 29,                  /**< Authentication Option. */
+} tcp_option_type_t;
+
+#define foreach_tcp_options_flag                                        \
+  _ (MSS)               /**< MSS advertised in SYN */                   \
+  _ (TSTAMP)            /**< Timestamp capability advertised in SYN */  \
+  _ (WSCALE)            /**< Wnd scale capability advertised in SYN */  \
+  _ (SACK_PERMITTED)    /**< SACK capability advertised in SYN */       \
+  _ (SACK)             /**< SACK present */
+
+enum
+{
+#define _(f) TCP_OPTS_FLAG_BIT_##f,
+  foreach_tcp_options_flag
+#undef _
+    TCP_OPTIONS_N_FLAG_BITS,
+};
+
+enum
+{
+#define _(f) TCP_OPTS_FLAG_##f = 1 << TCP_OPTS_FLAG_BIT_##f,
+  foreach_tcp_options_flag
+#undef _
+};
+
+typedef struct _sack_block
+{
+  u32 start;           /**< Start sequence number */
+  u32 end;             /**< End sequence number */
+} sack_block_t;
+
+typedef struct
+{
+  u8 flags;            /** Option flags, see above */
+
+  /* Received options */
+  u16 mss;             /**< Maximum segment size advertised by peer */
+  u8 wscale;           /**< Window scale advertised by peer */
+  u32 tsval;           /**< Peer's timestamp value */
+  u32 tsecr;           /**< Echoed/reflected time stamp */
+  sack_block_t *sacks; /**< SACK blocks received */
+  u8 n_sack_blocks;    /**< Number of SACKs blocks */
+} tcp_options_t;
+
+/* Flag tests that return 0 or !0 */
+#define tcp_opts_mss(_to) ((_to)->flags & TCP_OPTS_FLAG_MSS)
+#define tcp_opts_tstamp(_to) ((_to)->flags & TCP_OPTS_FLAG_TSTAMP)
+#define tcp_opts_wscale(_to) ((_to)->flags & TCP_OPTS_FLAG_WSCALE)
+#define tcp_opts_sack(_to) ((_to)->flags & TCP_OPTS_FLAG_SACK)
+#define tcp_opts_sack_permitted(_to) ((_to)->flags & TCP_OPTS_FLAG_SACK_PERMITTED)
+
+/* TCP option lengths */
+#define TCP_OPTION_LEN_EOL              1
+#define TCP_OPTION_LEN_NOOP             1
+#define TCP_OPTION_LEN_MSS              4
+#define TCP_OPTION_LEN_WINDOW_SCALE     3
+#define TCP_OPTION_LEN_SACK_PERMITTED   2
+#define TCP_OPTION_LEN_TIMESTAMP        10
+#define TCP_OPTION_LEN_SACK_BLOCK        8
+
+#define TCP_WND_MAX                     65535U
+#define TCP_MAX_WND_SCALE               14     /* See RFC 1323 */
+#define TCP_OPTS_ALIGN                  4
+#define TCP_OPTS_MAX_SACK_BLOCKS        3
+#endif /* included_tcp_packet_h */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp_pg.c b/src/vnet/tcp/tcp_pg.c
new file mode 100644 (file)
index 0000000..dc32404
--- /dev/null
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * ip/tcp_pg: TCP packet-generator interface
+ *
+ * Copyright (c) 2008 Eliot Dresselhaus
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <vnet/ip/ip.h>
+#include <vnet/pg/pg.h>
+
+/* TCP flags bit 0 first. */
+#define foreach_tcp_flag                       \
+  _ (FIN)                                      \
+  _ (SYN)                                      \
+  _ (RST)                                      \
+  _ (PSH)                                      \
+  _ (ACK)                                      \
+  _ (URG)                                      \
+  _ (ECE)                                      \
+  _ (CWR)
+
+static void
+tcp_pg_edit_function (pg_main_t * pg,
+                     pg_stream_t * s,
+                     pg_edit_group_t * g,
+                     u32 * packets,
+                     u32 n_packets)
+{
+  vlib_main_t * vm = vlib_get_main();
+  u32 ip_offset, tcp_offset;
+
+  tcp_offset = g->start_byte_offset;
+  ip_offset = (g-1)->start_byte_offset;
+
+  while (n_packets >= 1)
+    {
+      vlib_buffer_t * p0;
+      ip4_header_t * ip0;
+      tcp_header_t * tcp0;
+      ip_csum_t sum0;
+      u32 tcp_len0;
+
+      p0 = vlib_get_buffer (vm, packets[0]);
+      n_packets -= 1;
+      packets += 1;
+
+      ASSERT (p0->current_data == 0);
+      ip0 = (void *) (p0->data + ip_offset);
+      tcp0 = (void *) (p0->data + tcp_offset);
+      tcp_len0 = clib_net_to_host_u16 (ip0->length) - sizeof (ip0[0]);
+
+      /* Initialize checksum with header. */
+      if (BITS (sum0) == 32)
+       {
+         sum0 = clib_mem_unaligned (&ip0->src_address, u32);
+         sum0 = ip_csum_with_carry (sum0, clib_mem_unaligned (&ip0->dst_address, u32));
+       }
+      else
+       sum0 = clib_mem_unaligned (&ip0->src_address, u64);
+
+      sum0 = ip_csum_with_carry
+       (sum0, clib_host_to_net_u32 (tcp_len0 + (ip0->protocol << 16)));
+
+      /* Invalidate possibly old checksum. */
+      tcp0->checksum = 0;
+
+      sum0 = ip_incremental_checksum_buffer (vm, p0, tcp_offset, tcp_len0, sum0);
+
+      tcp0->checksum = ~ ip_csum_fold (sum0);
+    }
+}
+
+typedef struct {
+  pg_edit_t src, dst;
+  pg_edit_t seq_number, ack_number;
+  pg_edit_t data_offset_and_reserved;
+#define _(f) pg_edit_t f##_flag;
+  foreach_tcp_flag
+#undef _
+  pg_edit_t window;
+  pg_edit_t checksum;
+  pg_edit_t urgent_pointer;
+} pg_tcp_header_t;
+
+static inline void
+pg_tcp_header_init (pg_tcp_header_t * p)
+{
+  /* Initialize fields that are not bit fields in the IP header. */
+#define _(f) pg_edit_init (&p->f, tcp_header_t, f);
+  _ (src);
+  _ (dst);
+  _ (seq_number);
+  _ (ack_number);
+  _ (window);
+  _ (checksum);
+  _ (urgent_pointer);
+#undef _
+
+  /* Initialize bit fields. */
+#define _(f)                                           \
+  pg_edit_init_bitfield (&p->f##_flag, tcp_header_t,   \
+                        flags,                         \
+                        TCP_FLAG_BIT_##f, 1);
+
+  foreach_tcp_flag
+#undef _
+
+  pg_edit_init_bitfield (&p->data_offset_and_reserved, tcp_header_t,
+                        data_offset_and_reserved,
+                        4, 4);
+}
+
+uword
+unformat_pg_tcp_header (unformat_input_t * input, va_list * args)
+{
+  pg_stream_t * s = va_arg (*args, pg_stream_t *);
+  pg_tcp_header_t * p;
+  u32 group_index;
+  
+  p = pg_create_edit_group (s, sizeof (p[0]), sizeof (tcp_header_t),
+                           &group_index);
+  pg_tcp_header_init (p);
+
+  /* Defaults. */
+  pg_edit_set_fixed (&p->seq_number, 0);
+  pg_edit_set_fixed (&p->ack_number, 0);
+
+  pg_edit_set_fixed (&p->data_offset_and_reserved, 
+                     sizeof (tcp_header_t) / sizeof (u32));
+
+  pg_edit_set_fixed (&p->window, 4096);
+  pg_edit_set_fixed (&p->urgent_pointer, 0);
+
+#define _(f) pg_edit_set_fixed (&p->f##_flag, 0);
+  foreach_tcp_flag
+#undef _
+
+  p->checksum.type = PG_EDIT_UNSPECIFIED;
+
+  if (! unformat (input, "TCP: %U -> %U",
+                 unformat_pg_edit,
+                   unformat_tcp_udp_port, &p->src,
+                 unformat_pg_edit,
+                   unformat_tcp_udp_port, &p->dst))
+    goto error;
+
+  /* Parse options. */
+  while (1)
+    {
+      if (unformat (input, "window %U",
+                   unformat_pg_edit,
+                   unformat_pg_number, &p->window))
+       ;
+
+      else if (unformat (input, "checksum %U",
+                        unformat_pg_edit,
+                        unformat_pg_number, &p->checksum))
+       ;
+
+      /* Flags. */
+#define _(f) else if (unformat (input, #f)) pg_edit_set_fixed (&p->f##_flag, 1);
+  foreach_tcp_flag
+#undef _
+
+      /* Can't parse input: try next protocol level. */
+      else
+       break;
+    }
+
+  {
+    ip_main_t * im = &ip_main;
+    u16 dst_port;
+    tcp_udp_port_info_t * pi;
+
+    pi = 0;
+    if (p->dst.type == PG_EDIT_FIXED)
+      {
+       dst_port = pg_edit_get_value (&p->dst, PG_EDIT_LO);
+       pi = ip_get_tcp_udp_port_info (im, dst_port);
+      }
+
+    if (pi && pi->unformat_pg_edit
+       && unformat_user (input, pi->unformat_pg_edit, s))
+      ;
+
+    else if (! unformat_user (input, unformat_pg_payload, s))
+      goto error;
+
+    if (p->checksum.type == PG_EDIT_UNSPECIFIED)
+      {
+       pg_edit_group_t * g = pg_stream_get_group (s, group_index);
+       g->edit_function = tcp_pg_edit_function;
+       g->edit_function_opaque = 0;
+      }
+
+    return 1;
+  }
+
+ error:
+  /* Free up any edits we may have added. */
+  pg_free_edit_group (s);
+  return 0;
+}
+
diff --git a/src/vnet/tcp/tcp_syn_filter4.c b/src/vnet/tcp/tcp_syn_filter4.c
new file mode 100644 (file)
index 0000000..c7605a3
--- /dev/null
@@ -0,0 +1,542 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vlib/vlib.h>
+#include <vnet/vnet.h>
+#include <vnet/pg/pg.h>
+#include <vppinfra/error.h>
+#include <vnet/feature/feature.h>
+#include <vnet/ip/ip.h>
+#include <vppinfra/xxhash.h>
+
+typedef struct
+{
+  f64 next_reset;
+  f64 reset_interval;
+  u8 *syn_counts;
+} syn_filter4_runtime_t;
+
+typedef struct
+{
+  u32 next_index;
+  int not_a_syn;
+  u8 filter_value;
+} syn_filter4_trace_t;
+
+/* packet trace format function */
+static u8 *
+format_syn_filter4_trace (u8 * s, va_list * args)
+{
+  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+  syn_filter4_trace_t *t = va_arg (*args, syn_filter4_trace_t *);
+
+  s = format (s, "SYN_FILTER4: next index %d, %s",
+             t->next_index, t->not_a_syn ? "not a syn" : "syn");
+  if (t->not_a_syn == 0)
+    s = format (s, ", filter value %d\n", t->filter_value);
+  else
+    s = format (s, "\n");
+  return s;
+}
+
+static vlib_node_registration_t syn_filter4_node;
+
+#define foreach_syn_filter_error                \
+_(THROTTLED, "TCP SYN packet throttle drops")   \
+_(OK, "TCP SYN packets passed")
+
+typedef enum
+{
+#define _(sym,str) SYN_FILTER_ERROR_##sym,
+  foreach_syn_filter_error
+#undef _
+    SYN_FILTER_N_ERROR,
+} syn_filter_error_t;
+
+static char *syn_filter4_error_strings[] = {
+#define _(sym,string) string,
+  foreach_syn_filter_error
+#undef _
+};
+
+typedef enum
+{
+  SYN_FILTER_NEXT_DROP,
+  SYN_FILTER_N_NEXT,
+} syn_filter_next_t;
+
+extern vnet_feature_arc_registration_t vnet_feat_arc_ip4_local;
+
+static uword
+syn_filter4_node_fn (vlib_main_t * vm,
+                    vlib_node_runtime_t * node, vlib_frame_t * frame)
+{
+  u32 n_left_from, *from, *to_next;
+  syn_filter_next_t next_index;
+  u32 ok_syn_packets = 0;
+  vnet_feature_main_t *fm = &feature_main;
+  u8 arc_index = vnet_feat_arc_ip4_local.feature_arc_index;
+  vnet_feature_config_main_t *cm = &fm->feature_config_mains[arc_index];
+  syn_filter4_runtime_t *rt = (syn_filter4_runtime_t *) node->runtime_data;
+  f64 now = vlib_time_now (vm);
+  /* Shut up spurious gcc warnings. */
+  u8 *c0 = 0, *c1 = 0, *c2 = 0, *c3 = 0;
+
+  from = vlib_frame_vector_args (frame);
+  n_left_from = frame->n_vectors;
+  next_index = node->cached_next_index;
+
+  if (now > rt->next_reset)
+    {
+      memset (rt->syn_counts, 0, vec_len (rt->syn_counts));
+      rt->next_reset = now + rt->reset_interval;
+    }
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from >= 8 && n_left_to_next >= 4)
+       {
+         u32 bi0, bi1, bi2, bi3;
+         vlib_buffer_t *b0, *b1, *b2, *b3;
+         u32 next0, next1, next2, next3;
+         ip4_header_t *ip0, *ip1, *ip2, *ip3;
+         tcp_header_t *tcp0, *tcp1, *tcp2, *tcp3;
+         u32 not_a_syn0 = 1, not_a_syn1 = 1, not_a_syn2 = 1, not_a_syn3 = 1;
+         u64 hash0, hash1, hash2, hash3;
+
+         /* Prefetch next iteration. */
+         {
+           vlib_buffer_t *p4, *p5, *p6, *p7;
+
+           p4 = vlib_get_buffer (vm, from[4]);
+           p5 = vlib_get_buffer (vm, from[5]);
+           p6 = vlib_get_buffer (vm, from[6]);
+           p7 = vlib_get_buffer (vm, from[7]);
+
+           vlib_prefetch_buffer_header (p4, LOAD);
+           vlib_prefetch_buffer_header (p5, LOAD);
+           vlib_prefetch_buffer_header (p6, LOAD);
+           vlib_prefetch_buffer_header (p7, LOAD);
+
+           CLIB_PREFETCH (p4->data, CLIB_CACHE_LINE_BYTES, STORE);
+           CLIB_PREFETCH (p5->data, CLIB_CACHE_LINE_BYTES, STORE);
+           CLIB_PREFETCH (p6->data, CLIB_CACHE_LINE_BYTES, STORE);
+           CLIB_PREFETCH (p7->data, CLIB_CACHE_LINE_BYTES, STORE);
+         }
+
+         /* speculatively enqueue b0 and b1 to the current next frame */
+         to_next[0] = bi0 = from[0];
+         to_next[1] = bi1 = from[1];
+         to_next[2] = bi2 = from[2];
+         to_next[3] = bi3 = from[3];
+         from += 4;
+         to_next += 4;
+         n_left_from -= 4;
+         n_left_to_next -= 4;
+
+         b0 = vlib_get_buffer (vm, bi0);
+         b1 = vlib_get_buffer (vm, bi1);
+         b2 = vlib_get_buffer (vm, bi2);
+         b3 = vlib_get_buffer (vm, bi3);
+
+         vnet_get_config_data
+           (&cm->config_main, &b0->current_config_index,
+            &next0, 0 /* sizeof (c0[0]) */ );
+         vnet_get_config_data
+           (&cm->config_main, &b1->current_config_index,
+            &next1, 0 /* sizeof (c0[0]) */ );
+         vnet_get_config_data
+           (&cm->config_main, &b2->current_config_index,
+            &next2, 0 /* sizeof (c0[0]) */ );
+         vnet_get_config_data
+           (&cm->config_main, &b3->current_config_index,
+            &next3, 0 /* sizeof (c0[0]) */ );
+
+         /* Not TCP? */
+         ip0 = vlib_buffer_get_current (b0);
+         if (ip0->protocol != IP_PROTOCOL_TCP)
+           goto trace00;
+
+         tcp0 = ip4_next_header (ip0);
+         /*
+          * Not a SYN?
+          * $$$$ hack: the TCP bitfield flags seem not to compile
+          * correct code.
+          */
+         if (PREDICT_TRUE (!(tcp0->flags & 0x2)))
+           goto trace00;
+
+         not_a_syn0 = 0;
+         hash0 = clib_xxhash ((u64) ip0->src_address.as_u32);
+         c0 = &rt->syn_counts[hash0 & (_vec_len (rt->syn_counts) - 1)];
+         if (PREDICT_FALSE (*c0 >= 0x80))
+           {
+             next0 = SYN_FILTER_NEXT_DROP;
+             b0->error = node->errors[SYN_FILTER_ERROR_THROTTLED];
+             goto trace00;
+           }
+         *c0 += 1;
+         ok_syn_packets++;
+
+       trace00:
+         if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
+                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
+           {
+             syn_filter4_trace_t *t =
+               vlib_add_trace (vm, node, b0, sizeof (*t));
+             t->not_a_syn = not_a_syn0;
+             t->next_index = next0;
+             t->filter_value = not_a_syn0 ? 0 : *c0;
+           }
+
+         /* Not TCP? */
+         ip1 = vlib_buffer_get_current (b1);
+         if (ip1->protocol != IP_PROTOCOL_TCP)
+           goto trace01;
+
+         tcp1 = ip4_next_header (ip1);
+         /*
+          * Not a SYN?
+          * $$$$ hack: the TCP bitfield flags seem not to compile
+          * correct code.
+          */
+         if (PREDICT_TRUE (!(tcp1->flags & 0x2)))
+           goto trace01;
+
+         not_a_syn1 = 0;
+         hash1 = clib_xxhash ((u64) ip1->src_address.as_u32);
+         c1 = &rt->syn_counts[hash1 & (_vec_len (rt->syn_counts) - 1)];
+         if (PREDICT_FALSE (*c1 >= 0x80))
+           {
+             next1 = SYN_FILTER_NEXT_DROP;
+             b1->error = node->errors[SYN_FILTER_ERROR_THROTTLED];
+             goto trace01;
+           }
+         *c1 += 1;
+         ok_syn_packets++;
+
+       trace01:
+         if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
+                            && (b1->flags & VLIB_BUFFER_IS_TRACED)))
+           {
+             syn_filter4_trace_t *t =
+               vlib_add_trace (vm, node, b1, sizeof (*t));
+             t->not_a_syn = not_a_syn1;
+             t->next_index = next1;
+             t->filter_value = not_a_syn1 ? 0 : *c1;
+           }
+
+         /* Not TCP? */
+         ip2 = vlib_buffer_get_current (b2);
+         if (ip2->protocol != IP_PROTOCOL_TCP)
+           goto trace02;
+
+         tcp2 = ip4_next_header (ip2);
+         /*
+          * Not a SYN?
+          * $$$$ hack: the TCP bitfield flags seem not to compile
+          * correct code.
+          */
+         if (PREDICT_TRUE (!(tcp2->flags & 0x2)))
+           goto trace02;
+
+         not_a_syn2 = 0;
+         hash2 = clib_xxhash ((u64) ip2->src_address.as_u32);
+         c2 = &rt->syn_counts[hash2 & (_vec_len (rt->syn_counts) - 1)];
+         if (PREDICT_FALSE (*c2 >= 0x80))
+           {
+             next2 = SYN_FILTER_NEXT_DROP;
+             b2->error = node->errors[SYN_FILTER_ERROR_THROTTLED];
+             goto trace02;
+           }
+         *c2 += 1;
+         ok_syn_packets++;
+
+       trace02:
+         if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
+                            && (b2->flags & VLIB_BUFFER_IS_TRACED)))
+           {
+             syn_filter4_trace_t *t =
+               vlib_add_trace (vm, node, b2, sizeof (*t));
+             t->not_a_syn = not_a_syn2;
+             t->next_index = next2;
+             t->filter_value = not_a_syn2 ? 0 : *c2;
+           }
+
+         /* Not TCP? */
+         ip3 = vlib_buffer_get_current (b3);
+         if (ip3->protocol != IP_PROTOCOL_TCP)
+           goto trace03;
+
+         tcp3 = ip4_next_header (ip3);
+         /*
+          * Not a SYN?
+          * $$$$ hack: the TCP bitfield flags seem not to compile
+          * correct code.
+          */
+         if (PREDICT_TRUE (!(tcp3->flags & 0x2)))
+           goto trace03;
+
+         not_a_syn3 = 0;
+         hash3 = clib_xxhash ((u64) ip3->src_address.as_u32);
+         c3 = &rt->syn_counts[hash3 & (_vec_len (rt->syn_counts) - 1)];
+         if (PREDICT_FALSE (*c3 >= 0x80))
+           {
+             next3 = SYN_FILTER_NEXT_DROP;
+             b3->error = node->errors[SYN_FILTER_ERROR_THROTTLED];
+             goto trace03;
+           }
+         *c3 += 1;
+         ok_syn_packets++;
+
+       trace03:
+         if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
+                            && (b3->flags & VLIB_BUFFER_IS_TRACED)))
+           {
+             syn_filter4_trace_t *t =
+               vlib_add_trace (vm, node, b3, sizeof (*t));
+             t->not_a_syn = not_a_syn3;
+             t->next_index = next3;
+             t->filter_value = not_a_syn3 ? 0 : *c3;
+           }
+         vlib_validate_buffer_enqueue_x4 (vm, node, next_index,
+                                          to_next, n_left_to_next,
+                                          bi0, bi1, bi2, bi3,
+                                          next0, next1, next2, next3);
+       }
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         u32 next0;
+         ip4_header_t *ip0;
+         tcp_header_t *tcp0;
+         u32 not_a_syn0 = 1;
+         u32 hash0;
+         u8 *c0;
+
+         /* speculatively enqueue b0 to the current next frame */
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+
+         vnet_get_config_data
+           (&cm->config_main, &b0->current_config_index,
+            &next0, 0 /* sizeof (c0[0]) */ );
+
+         /* Not TCP? */
+         ip0 = vlib_buffer_get_current (b0);
+         if (ip0->protocol != IP_PROTOCOL_TCP)
+           goto trace0;
+
+         tcp0 = ip4_next_header (ip0);
+         /*
+          * Not a SYN?
+          * $$$$ hack: the TCP bitfield flags seem not to compile
+          * correct code.
+          */
+         if (PREDICT_TRUE (!(tcp0->flags & 0x2)))
+           goto trace0;
+
+         not_a_syn0 = 0;
+         hash0 = clib_xxhash ((u64) ip0->src_address.as_u32);
+         c0 = &rt->syn_counts[hash0 & (_vec_len (rt->syn_counts) - 1)];
+         if (PREDICT_FALSE (*c0 >= 0x80))
+           {
+             next0 = SYN_FILTER_NEXT_DROP;
+             b0->error = node->errors[SYN_FILTER_ERROR_THROTTLED];
+             goto trace0;
+           }
+         *c0 += 1;
+         ok_syn_packets++;
+
+       trace0:
+
+         if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
+                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
+           {
+             syn_filter4_trace_t *t =
+               vlib_add_trace (vm, node, b0, sizeof (*t));
+             t->not_a_syn = not_a_syn0;
+             t->next_index = next0;
+             t->filter_value = not_a_syn0 ? 0 : *c0;
+           }
+
+         /* verify speculative enqueue, maybe switch current next frame */
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
+                                          to_next, n_left_to_next,
+                                          bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  vlib_node_increment_counter (vm, syn_filter4_node.index,
+                              SYN_FILTER_ERROR_OK, ok_syn_packets);
+  return frame->n_vectors;
+}
+
+/* *INDENT-OFF* */
+VLIB_REGISTER_NODE (syn_filter4_node, static) =
+{
+  .function = syn_filter4_node_fn,
+  .name = "syn-filter-4",
+  .vector_size = sizeof (u32),
+  .format_trace = format_syn_filter4_trace,
+  .type = VLIB_NODE_TYPE_INTERNAL,
+
+  .runtime_data_bytes = sizeof (syn_filter4_runtime_t),
+  .n_errors = ARRAY_LEN(syn_filter4_error_strings),
+  .error_strings = syn_filter4_error_strings,
+
+  .n_next_nodes = SYN_FILTER_N_NEXT,
+
+  /* edit / add dispositions here */
+  .next_nodes = {
+    [SYN_FILTER_NEXT_DROP] = "error-drop",
+  },
+};
+/* *INDENT-ON* */
+
+VLIB_NODE_FUNCTION_MULTIARCH (syn_filter4_node, syn_filter4_node_fn);
+
+/* *INDENT-OFF* */
+VNET_FEATURE_INIT (syn_filter_4, static) =
+{
+  .arc_name = "ip4-local",
+  .node_name = "syn-filter-4",
+  .runs_before = VNET_FEATURES("ip4-local-end-of-arc"),
+};
+/* *INDENT-ON* */
+
+int
+syn_filter_enable_disable (u32 sw_if_index, int enable_disable)
+{
+  vnet_main_t *vnm = vnet_get_main ();
+  vnet_sw_interface_t *sw;
+  int rv = 0;
+
+  /* Utterly wrong? */
+  if (pool_is_free_index (vnm->interface_main.sw_interfaces, sw_if_index))
+    return VNET_API_ERROR_INVALID_SW_IF_INDEX;
+
+  /* Not a physical port? */
+  sw = vnet_get_sw_interface (vnm, sw_if_index);
+  if (sw->type != VNET_SW_INTERFACE_TYPE_HARDWARE)
+    return VNET_API_ERROR_INVALID_SW_IF_INDEX;
+
+  if (enable_disable)
+    {
+      vlib_main_t *vm = vlib_get_main ();
+      syn_filter4_runtime_t *rt;
+
+      rt = vlib_node_get_runtime_data (vm, syn_filter4_node.index);
+      vec_validate (rt->syn_counts, 1023);
+      /*
+       * Given perfect disperson / optimal hashing results:
+       * Allow 128k (successful) syns/sec. 1024, buckets each of which
+       * absorb 128 syns before filtering. Reset table once a second.
+       * Reality bites, lets try resetting once every 100ms.
+       */
+      rt->reset_interval = 0.1;        /* reset interval in seconds */
+    }
+
+  rv = vnet_feature_enable_disable ("ip4-local", "syn-filter-4",
+                                   sw_if_index, enable_disable, 0, 0);
+
+  return rv;
+}
+
+static clib_error_t *
+syn_filter_enable_disable_command_fn (vlib_main_t * vm,
+                                     unformat_input_t * input,
+                                     vlib_cli_command_t * cmd)
+{
+  vnet_main_t *vnm = vnet_get_main ();
+  u32 sw_if_index = ~0;
+  int enable_disable = 1;
+  int rv;
+
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "disable"))
+       enable_disable = 0;
+      else if (unformat (input, "%U", unformat_vnet_sw_interface,
+                        vnm, &sw_if_index))
+       ;
+      else
+       break;
+    }
+
+  if (sw_if_index == ~0)
+    return clib_error_return (0, "Please specify an interface...");
+
+  rv = syn_filter_enable_disable (sw_if_index, enable_disable);
+
+  switch (rv)
+    {
+    case 0:
+      break;
+
+    case VNET_API_ERROR_INVALID_SW_IF_INDEX:
+      return clib_error_return
+       (0, "Invalid interface, only works on physical ports");
+      break;
+
+    case VNET_API_ERROR_UNIMPLEMENTED:
+      return clib_error_return (0,
+                               "Device driver doesn't support redirection");
+      break;
+
+    case VNET_API_ERROR_INVALID_VALUE:
+      return clib_error_return (0, "feature arc not found");
+
+    case VNET_API_ERROR_INVALID_VALUE_2:
+      return clib_error_return (0, "feature node not found");
+
+    default:
+      return clib_error_return (0, "syn_filter_enable_disable returned %d",
+                               rv);
+    }
+  return 0;
+}
+
+/* *INDENT-OFF* */
+VLIB_CLI_COMMAND (sr_content_command, static) =
+{
+  .path = "ip syn filter",
+  .short_help = "ip syn filter <interface-name> [disable]",
+  .function = syn_filter_enable_disable_command_fn,
+};
+/* *INDENT-ON* */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/tcp/tcp_timer.h b/src/vnet/tcp/tcp_timer.h
new file mode 100644 (file)
index 0000000..fa25268
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __included_tcp_timer_h__
+#define __included_tcp_timer_h__
+
+#include <vppinfra/tw_timer_16t_2w_512sl.h>
+#include <vppinfra/tw_timer_16t_1w_2048sl.h>
+
+#endif /* __included_tcp_timer_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/udp/builtin_server.c b/src/vnet/udp/builtin_server.c
new file mode 100644 (file)
index 0000000..afa66ba
--- /dev/null
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** @file
+    udp builtin server
+*/
+
+#include <vnet/udp/udp.h>
+#include <vnet/session/session.h>
+#include <vnet/session/application_interface.h>
+
+/** per-worker built-in server copy buffers */
+u8 **copy_buffers;
+
+static int
+builtin_session_create_callback (stream_session_t * s)
+{
+  /* Simple version: declare session ready-to-go... */
+  s->session_state = SESSION_STATE_READY;
+  return 0;
+}
+
+static void
+builtin_session_disconnect_callback (stream_session_t * s)
+{
+  stream_session_disconnect (s);
+}
+
+static int
+builtin_server_rx_callback (stream_session_t * s)
+{
+  svm_fifo_t *rx_fifo, *tx_fifo;
+  u32 this_transfer;
+  int actual_transfer;
+  u8 *my_copy_buffer;
+  session_fifo_event_t evt;
+  unix_shared_memory_queue_t *q;
+
+  my_copy_buffer = copy_buffers[s->thread_index];
+  rx_fifo = s->server_rx_fifo;
+  tx_fifo = s->server_tx_fifo;
+
+  this_transfer = svm_fifo_max_enqueue (tx_fifo)
+    < svm_fifo_max_dequeue (rx_fifo) ?
+    svm_fifo_max_enqueue (tx_fifo) : svm_fifo_max_dequeue (rx_fifo);
+
+  vec_validate (my_copy_buffer, this_transfer - 1);
+  _vec_len (my_copy_buffer) = this_transfer;
+
+  actual_transfer = svm_fifo_dequeue_nowait (rx_fifo, 0, this_transfer,
+                                            my_copy_buffer);
+  ASSERT (actual_transfer == this_transfer);
+  actual_transfer = svm_fifo_enqueue_nowait (tx_fifo, 0, this_transfer,
+                                            my_copy_buffer);
+
+  copy_buffers[s->thread_index] = my_copy_buffer;
+
+  /* Fabricate TX event, send to ourselves */
+  evt.fifo = tx_fifo;
+  evt.event_type = FIFO_EVENT_SERVER_TX;
+  /* $$$$ for event logging */
+  evt.enqueue_length = actual_transfer;
+  evt.event_id = 0;
+  q = session_manager_get_vpp_event_queue (s->thread_index);
+  unix_shared_memory_queue_add (q, (u8 *) & evt, 0 /* do wait for mutex */ );
+
+  return 0;
+}
+
+/* *INDENT-OFF* */
+static session_cb_vft_t builtin_server = {
+    .session_accept_callback = builtin_session_create_callback,
+    .session_disconnect_callback = builtin_session_disconnect_callback,
+    .builtin_server_rx_callback = builtin_server_rx_callback
+};
+/* *INDENT-ON* */
+
+static int
+bind_builtin_uri_server (u8 * uri)
+{
+  vnet_bind_args_t _a, *a = &_a;
+  char segment_name[128];
+  u32 segment_name_length;
+  int rv;
+  u64 options[16];
+
+  segment_name_length = ARRAY_LEN (segment_name);
+
+  memset (a, 0, sizeof (*a));
+  memset (options, 0, sizeof (options));
+
+  a->uri = (char *) uri;
+  a->api_client_index = ~0;    /* built-in server */
+  a->segment_name = segment_name;
+  a->segment_name_length = segment_name_length;
+  a->session_cb_vft = &builtin_server;
+
+  options[SESSION_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
+  options[SESSION_OPTIONS_SEGMENT_SIZE] = (2 << 30);   /*$$$$ config / arg */
+  a->options = options;
+
+  rv = vnet_bind_uri (a);
+
+  return rv;
+}
+
+static int
+unbind_builtin_uri_server (u8 * uri)
+{
+  int rv;
+
+  rv = vnet_unbind_uri ((char *) uri, ~0 /* client_index */ );
+
+  return rv;
+}
+
+static clib_error_t *
+builtin_server_init (vlib_main_t * vm)
+{
+  vlib_thread_main_t *vtm = vlib_get_thread_main ();
+  u32 num_threads;
+
+  num_threads = 1 /* main thread */  + vtm->n_threads;
+
+  vec_validate (copy_buffers, num_threads - 1);
+  return 0;
+}
+
+VLIB_INIT_FUNCTION (builtin_server_init);
+
+static clib_error_t *
+builtin_uri_bind_command_fn (vlib_main_t * vm,
+                            unformat_input_t * input,
+                            vlib_cli_command_t * cmd)
+{
+  u8 *uri = 0;
+  int rv;
+
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "uri %s", &uri))
+       ;
+      else
+       break;
+    }
+
+  if (uri == 0)
+    return clib_error_return (0, "uri to bind not specified...");
+
+  rv = bind_builtin_uri_server (uri);
+
+  vec_free (uri);
+
+  switch (rv)
+    {
+    case 0:
+      break;
+
+    default:
+      return clib_error_return (0, "bind_uri_server returned %d", rv);
+      break;
+    }
+
+  return 0;
+}
+
+/* *INDENT-OFF* */
+VLIB_CLI_COMMAND (builtin_uri_bind_command, static) =
+{
+  .path = "builtin uri bind",
+  .short_help = "builtin uri bind",
+  .function = builtin_uri_bind_command_fn,
+};
+/* *INDENT-ON* */
+
+static clib_error_t *
+builtin_uri_unbind_command_fn (vlib_main_t * vm,
+                              unformat_input_t * input,
+                              vlib_cli_command_t * cmd)
+{
+  u8 *uri = 0;
+  int rv;
+
+  while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
+    {
+      if (unformat (input, "uri %s", &uri))
+       ;
+      else
+       break;
+    }
+
+  if (uri == 0)
+    return clib_error_return (0, "uri to unbind not specified...");
+
+  rv = unbind_builtin_uri_server (uri);
+
+  vec_free (uri);
+
+  switch (rv)
+    {
+    case 0:
+      break;
+
+    default:
+      return clib_error_return (0, "unbind_uri_server returned %d", rv);
+      break;
+    }
+
+  return 0;
+}
+
+/* *INDENT-OFF* */
+VLIB_CLI_COMMAND (builtin_uri_unbind_command, static) =
+{
+  .path = "builtin uri unbind",
+  .short_help = "builtin uri unbind",
+  .function = builtin_uri_unbind_command_fn,
+};
+/* *INDENT-ON* */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vnet/udp/udp.c b/src/vnet/udp/udp.c
new file mode 100644 (file)
index 0000000..9e74046
--- /dev/null
@@ -0,0 +1,342 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** @file
+    udp state machine, etc.
+*/
+
+#include <vnet/udp/udp.h>
+#include <vnet/session/session.h>
+#include <vnet/dpo/load_balance.h>
+#include <vnet/fib/ip4_fib.h>
+
+udp_uri_main_t udp_uri_main;
+
+u32
+udp_session_bind_ip4 (vlib_main_t * vm, u32 session_index,
+                     ip46_address_t * ip, u16 port_number_host_byte_order)
+{
+  udp_uri_main_t *um = vnet_get_udp_main ();
+  udp_connection_t *listener;
+
+  pool_get (um->udp_listeners, listener);
+  memset (listener, 0, sizeof (udp_connection_t));
+  listener->c_lcl_port = clib_host_to_net_u16 (port_number_host_byte_order);
+  listener->c_lcl_ip4.as_u32 = ip->ip4.as_u32;
+  listener->c_proto = SESSION_TYPE_IP4_UDP;
+  udp_register_dst_port (um->vlib_main, port_number_host_byte_order,
+                        udp4_uri_input_node.index, 1 /* is_ipv4 */ );
+  return 0;
+}
+
+u32
+udp_session_bind_ip6 (vlib_main_t * vm, u32 session_index,
+                     ip46_address_t * ip, u16 port_number_host_byte_order)
+{
+  udp_uri_main_t *um = vnet_get_udp_main ();
+  udp_connection_t *listener;
+
+  pool_get (um->udp_listeners, listener);
+  listener->c_lcl_port = clib_host_to_net_u16 (port_number_host_byte_order);
+  clib_memcpy (&listener->c_lcl_ip6, &ip->ip6, sizeof (ip6_address_t));
+  listener->c_proto = SESSION_TYPE_IP6_UDP;
+  udp_register_dst_port (um->vlib_main, port_number_host_byte_order,
+                        udp4_uri_input_node.index, 0 /* is_ipv4 */ );
+  return 0;
+}
+
+u32
+udp_session_unbind_ip4 (vlib_main_t * vm, u32 listener_index)
+{
+  udp_connection_t *listener;
+  listener = udp_listener_get (listener_index);
+
+  /* deregister the udp_local mapping */
+  udp_unregister_dst_port (vm, listener->c_lcl_port, 1 /* is_ipv4 */ );
+  return 0;
+}
+
+u32
+udp_session_unbind_ip6 (vlib_main_t * vm, u32 listener_index)
+{
+  udp_connection_t *listener;
+
+  listener = udp_listener_get (listener_index);
+
+  /* deregister the udp_local mapping */
+  udp_unregister_dst_port (vm, listener->c_lcl_port, 0 /* is_ipv4 */ );
+  return 0;
+}
+
+transport_connection_t *
+udp_session_get_listener (u32 listener_index)
+{
+  udp_connection_t *us;
+
+  us = udp_listener_get (listener_index);
+  return &us->connection;
+}
+
+u32
+udp_push_header (transport_connection_t * tconn, vlib_buffer_t * b)
+{
+  udp_connection_t *us;
+  u8 *data;
+  udp_header_t *udp;
+
+  us = (udp_connection_t *) tconn;
+
+  if (tconn->is_ip4)
+    {
+      ip4_header_t *ip;
+
+      data = vlib_buffer_get_current (b);
+      udp = (udp_header_t *) (data - sizeof (udp_header_t));
+      ip = (ip4_header_t *) ((u8 *) udp - sizeof (ip4_header_t));
+
+      /* Build packet header, swap rx key src + dst fields */
+      ip->src_address.as_u32 = us->c_lcl_ip4.as_u32;
+      ip->dst_address.as_u32 = us->c_rmt_ip4.as_u32;
+      ip->ip_version_and_header_length = 0x45;
+      ip->ttl = 254;
+      ip->protocol = IP_PROTOCOL_UDP;
+      ip->length = clib_host_to_net_u16 (b->current_length + sizeof (*udp));
+      ip->checksum = ip4_header_checksum (ip);
+
+      udp->src_port = us->c_lcl_port;
+      udp->dst_port = us->c_rmt_port;
+      udp->length = clib_host_to_net_u16 (b->current_length);
+      udp->checksum = 0;
+
+      b->current_length = sizeof (*ip) + sizeof (*udp);
+      return SESSION_QUEUE_NEXT_IP4_LOOKUP;
+    }
+  else
+    {
+      vlib_main_t *vm = vlib_get_main ();
+      ip6_header_t *ip;
+      u16 payload_length;
+      int bogus = ~0;
+
+      data = vlib_buffer_get_current (b);
+      udp = (udp_header_t *) (data - sizeof (udp_header_t));
+      ip = (ip6_header_t *) ((u8 *) udp - sizeof (ip6_header_t));
+
+      /* Build packet header, swap rx key src + dst fields */
+      clib_memcpy (&ip->src_address, &us->c_lcl_ip6, sizeof (ip6_address_t));
+      clib_memcpy (&ip->dst_address, &us->c_rmt_ip6, sizeof (ip6_address_t));
+
+      ip->ip_version_traffic_class_and_flow_label =
+       clib_host_to_net_u32 (0x6 << 28);
+
+      ip->hop_limit = 0xff;
+      ip->protocol = IP_PROTOCOL_UDP;
+
+      payload_length = vlib_buffer_length_in_chain (vm, b);
+      payload_length -= sizeof (*ip);
+
+      ip->payload_length = clib_host_to_net_u16 (payload_length);
+
+      udp->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b, ip, &bogus);
+      ASSERT (!bogus);
+
+      udp->src_port = us->c_lcl_port;
+      udp->dst_port = us->c_rmt_port;
+      udp->length = clib_host_to_net_u16 (b->current_length);
+      udp->checksum = 0;
+
+      b->current_length = sizeof (*ip) + sizeof (*udp);
+
+      return SESSION_QUEUE_NEXT_IP6_LOOKUP;
+    }
+}
+
+transport_connection_t *
+udp_session_get (u32 connection_index, u32 my_thread_index)
+{
+  udp_uri_main_t *um = vnet_get_udp_main ();
+
+  udp_connection_t *us;
+  us =
+    pool_elt_at_index (um->udp_sessions[my_thread_index], connection_index);
+  return &us->connection;
+}
+
+void
+udp_session_close (u32 connection_index, u32 my_thread_index)
+{
+  udp_uri_main_t *um = vnet_get_udp_main ();
+  pool_put_index (um->udp_sessions[my_thread_index], connection_index);
+}
+
+u8 *
+format_udp_session_ip4 (u8 * s, va_list * args)
+{
+  u32 uci = va_arg (*args, u32);
+  u32 thread_index = va_arg (*args, u32);
+  udp_connection_t *u4;
+
+  u4 = udp_connection_get (uci, thread_index);
+
+  s = format (s, "[%s] %U:%d->%U:%d", "udp", format_ip4_address,
+             &u4->c_lcl_ip4, clib_net_to_host_u16 (u4->c_lcl_port),
+             format_ip4_address, &u4->c_rmt_ip4,
+             clib_net_to_host_u16 (u4->c_rmt_port));
+  return s;
+}
+
+u8 *
+format_udp_session_ip6 (u8 * s, va_list * args)
+{
+  u32 uci = va_arg (*args, u32);
+  u32 thread_index = va_arg (*args, u32);
+  udp_connection_t *tc = udp_connection_get (uci, thread_index);
+  s = format (s, "[%s] %U:%d->%U:%d", "udp", format_ip6_address,
+             &tc->c_lcl_ip6, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip6_address, &tc->c_rmt_ip6,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+u8 *
+format_udp_listener_session_ip4 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  udp_connection_t *tc = udp_listener_get (tci);
+  s = format (s, "[%s] %U:%d->%U:%d", "udp", format_ip4_address,
+             &tc->c_lcl_ip4, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip4_address, &tc->c_rmt_ip4,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+u8 *
+format_udp_listener_session_ip6 (u8 * s, va_list * args)
+{
+  u32 tci = va_arg (*args, u32);
+  udp_connection_t *tc = udp_listener_get (tci);
+  s = format (s, "[%s] %U:%d->%U:%d", "udp", format_ip6_address,
+             &tc->c_lcl_ip6, clib_net_to_host_u16 (tc->c_lcl_port),
+             format_ip6_address, &tc->c_rmt_ip6,
+             clib_net_to_host_u16 (tc->c_rmt_port));
+  return s;
+}
+
+u16
+udp_send_mss_uri (transport_connection_t * t)
+{
+  /* TODO figure out MTU of output interface */
+  return 400;
+}
+
+u32
+udp_send_space_uri (transport_connection_t * t)
+{
+  /* No constraint on TX window */
+  return ~0;
+}
+
+int
+udp_open_connection (ip46_address_t * addr, u16 port)
+{
+  clib_warning ("Not implemented");
+  return 0;
+}
+
+/* *INDENT-OFF* */
+const static transport_proto_vft_t udp4_proto = {
+  .bind = udp_session_bind_ip4,
+  .open = udp_open_connection,
+  .unbind = udp_session_unbind_ip4,
+  .push_header = udp_push_header,
+  .get_connection = udp_session_get,
+  .get_listener = udp_session_get_listener,
+  .close = udp_session_close,
+  .send_mss = udp_send_mss_uri,
+  .send_space = udp_send_space_uri,
+  .format_connection = format_udp_session_ip4,
+  .format_listener = format_udp_listener_session_ip4
+};
+
+const static transport_proto_vft_t udp6_proto = {
+  .bind = udp_session_bind_ip6,
+  .open = udp_open_connection,
+  .unbind = udp_session_unbind_ip6,
+  .push_header = udp_push_header,
+  .get_connection = udp_session_get,
+  .get_listener = udp_session_get_listener,
+  .close = udp_session_close,
+  .send_mss = udp_send_mss_uri,
+  .send_space = udp_send_space_uri,
+  .format_connection = format_udp_session_ip6,
+  .format_listener = format_udp_listener_session_ip6
+};
+/* *INDENT-ON* */
+
+static clib_error_t *
+udp_init (vlib_main_t * vm)
+{
+  udp_uri_main_t *um = vnet_get_udp_main ();
+  ip_main_t *im = &ip_main;
+  vlib_thread_main_t *tm = vlib_get_thread_main ();
+  u32 num_threads;
+  clib_error_t *error = 0;
+  ip_protocol_info_t *pi;
+
+  um->vlib_main = vm;
+  um->vnet_main = vnet_get_main ();
+
+  if ((error = vlib_call_init_function (vm, ip_main_init)))
+    return error;
+  if ((error = vlib_call_init_function (vm, ip4_lookup_init)))
+    return error;
+  if ((error = vlib_call_init_function (vm, ip6_lookup_init)))
+    return error;
+
+  /*
+   * Registrations
+   */
+
+  /* IP registration */
+  pi = ip_get_protocol_info (im, IP_PROTOCOL_UDP);
+  if (pi == 0)
+    return clib_error_return (0, "UDP protocol info AWOL");
+  pi->format_header = format_udp_header;
+  pi->unformat_pg_edit = unformat_pg_udp_header;
+
+
+  /* Register as transport with URI */
+  session_register_transport (SESSION_TYPE_IP4_UDP, &udp4_proto);
+  session_register_transport (SESSION_TYPE_IP6_UDP, &udp6_proto);
+
+  /*
+   * Initialize data structures
+   */
+
+  num_threads = 1 /* main thread */  + tm->n_threads;
+  vec_validate (um->udp_sessions, num_threads - 1);
+
+  return error;
+}
+
+VLIB_INIT_FUNCTION (udp_init);
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
similarity index 85%
rename from src/vnet/ip/udp.h
rename to src/vnet/udp/udp.h
index bad58b5..7ab26ce 100644 (file)
@@ -1,7 +1,5 @@
 /*
- * ip/udp.h: udp protocol
- *
- * Copyright (c) 2013 Cisco and/or its affiliates.
+ * Copyright (c) 2017 Cisco and/or its affiliates.
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at:
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
-#ifndef included_udp_h
-#define included_udp_h
+#ifndef __included_udp_h__
+#define __included_udp_h__
 
 #include <vnet/vnet.h>
-#include <vnet/ip/udp_packet.h>
+#include <vnet/udp/udp_packet.h>
 #include <vnet/ip/ip.h>
 #include <vnet/ip/ip4.h>
 #include <vnet/ip/ip4_packet.h>
 #include <vnet/pg/pg.h>
 #include <vnet/ip/format.h>
 
+#include <vnet/ip/ip.h>
+#include <vnet/session/transport.h>
+
+typedef struct
+{
+  transport_connection_t connection;         /** must be first */
+
+  /** ersatz MTU to limit fifo pushes to test data size */
+  u32 mtu;
+} udp_connection_t;
+
+typedef struct _udp_uri_main
+{
+  /* Per-worker thread udp connection pools */
+  udp_connection_t **udp_sessions;
+  udp_connection_t *udp_listeners;
+
+  /* convenience */
+  vlib_main_t *vlib_main;
+  vnet_main_t *vnet_main;
+  ip4_main_t *ip4_main;
+  ip6_main_t *ip6_main;
+} udp_uri_main_t;
+
+extern udp_uri_main_t udp_uri_main;
+extern vlib_node_registration_t udp4_uri_input_node;
+
+always_inline udp_uri_main_t *
+vnet_get_udp_main ()
+{
+  return &udp_uri_main;
+}
+
+always_inline udp_connection_t *
+udp_connection_get (u32 conn_index, u32 thread_index)
+{
+  return pool_elt_at_index (udp_uri_main.udp_sessions[thread_index],
+                           conn_index);
+}
+
+always_inline udp_connection_t *
+udp_listener_get (u32 conn_index)
+{
+  return pool_elt_at_index (udp_uri_main.udp_listeners, conn_index);
+}
+
 typedef enum
 {
 #define udp_error(n,s) UDP_ERROR_##n,
-#include <vnet/ip/udp_error.def>
+#include <vnet/udp/udp_error.def>
 #undef udp_error
   UDP_N_ERROR,
 } udp_error_t;
@@ -123,6 +166,10 @@ void udp_register_dst_port (vlib_main_t * vm,
                            udp_dst_port_t dst_port,
                            u32 node_index, u8 is_ip4);
 
+void
+udp_unregister_dst_port (vlib_main_t * vm,
+                        udp_dst_port_t dst_port, u8 is_ip4);
+
 void udp_punt_unknown (vlib_main_t * vm, u8 is_ip4, u8 is_add);
 
 always_inline void
@@ -304,8 +351,6 @@ ip_udp_encap_two (vlib_main_t * vm, vlib_buffer_t * b0, vlib_buffer_t * b1,
     }
 }
 
-#endif /* included_udp_h */
-
 /*
  * fd.io coding-style-patch-verification: ON
  *
@@ -313,3 +358,5 @@ ip_udp_encap_two (vlib_main_t * vm, vlib_buffer_t * b0, vlib_buffer_t * b1,
  * eval: (c-set-style "gnu")
  * End:
  */
+
+#endif /* __included_udp_h__ */
diff --git a/src/vnet/udp/udp_input.c b/src/vnet/udp/udp_input.c
new file mode 100644 (file)
index 0000000..4d50933
--- /dev/null
@@ -0,0 +1,314 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vlib/vlib.h>
+#include <vnet/vnet.h>
+#include <vnet/pg/pg.h>
+#include <vnet/ip/ip.h>
+
+#include <vnet/udp/udp.h>
+#include <vppinfra/hash.h>
+#include <vppinfra/error.h>
+#include <vppinfra/elog.h>
+
+#include <vnet/udp/udp_packet.h>
+
+#include <vlibmemory/api.h>
+#include "../session/application_interface.h"
+
+vlib_node_registration_t udp4_uri_input_node;
+
+typedef struct
+{
+  u32 session;
+  u32 disposition;
+  u32 thread_index;
+} udp4_uri_input_trace_t;
+
+/* packet trace format function */
+static u8 *
+format_udp4_uri_input_trace (u8 * s, va_list * args)
+{
+  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
+  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
+  udp4_uri_input_trace_t *t = va_arg (*args, udp4_uri_input_trace_t *);
+
+  s = format (s, "UDP4_URI_INPUT: session %d, disposition %d, thread %d",
+             t->session, t->disposition, t->thread_index);
+  return s;
+}
+
+typedef enum
+{
+  UDP4_URI_INPUT_NEXT_DROP,
+  UDP4_URI_INPUT_N_NEXT,
+} udp4_uri_input_next_t;
+
+static char *udp4_uri_input_error_strings[] = {
+#define _(sym,string) string,
+  foreach_session_input_error
+#undef _
+};
+
+static uword
+udp4_uri_input_node_fn (vlib_main_t * vm,
+                       vlib_node_runtime_t * node, vlib_frame_t * frame)
+{
+  u32 n_left_from, *from, *to_next;
+  udp4_uri_input_next_t next_index;
+  udp_uri_main_t *um = vnet_get_udp_main ();
+  session_manager_main_t *smm = vnet_get_session_manager_main ();
+  u32 my_thread_index = vm->cpu_index;
+  u8 my_enqueue_epoch;
+  u32 *session_indices_to_enqueue;
+  static u32 serial_number;
+  int i;
+
+  my_enqueue_epoch = ++smm->current_enqueue_epoch[my_thread_index];
+
+  from = vlib_frame_vector_args (frame);
+  n_left_from = frame->n_vectors;
+  next_index = node->cached_next_index;
+
+  while (n_left_from > 0)
+    {
+      u32 n_left_to_next;
+
+      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
+
+      while (n_left_from > 0 && n_left_to_next > 0)
+       {
+         u32 bi0;
+         vlib_buffer_t *b0;
+         u32 next0 = UDP4_URI_INPUT_NEXT_DROP;
+         u32 error0 = SESSION_ERROR_ENQUEUED;
+         udp_header_t *udp0;
+         ip4_header_t *ip0;
+         stream_session_t *s0;
+         svm_fifo_t *f0;
+         u16 udp_len0;
+         u8 *data0;
+
+         /* speculatively enqueue b0 to the current next frame */
+         bi0 = from[0];
+         to_next[0] = bi0;
+         from += 1;
+         to_next += 1;
+         n_left_from -= 1;
+         n_left_to_next -= 1;
+
+         b0 = vlib_get_buffer (vm, bi0);
+
+         /* udp_local hands us a pointer to the udp data */
+
+         data0 = vlib_buffer_get_current (b0);
+         udp0 = (udp_header_t *) (data0 - sizeof (*udp0));
+
+         /* $$$$ fixme: udp_local doesn't do ip options correctly anyhow */
+         ip0 = (ip4_header_t *) (((u8 *) udp0) - sizeof (*ip0));
+         s0 = 0;
+
+         /* lookup session */
+         s0 = stream_session_lookup4 (&ip0->dst_address, &ip0->src_address,
+                                      udp0->dst_port, udp0->src_port,
+                                      SESSION_TYPE_IP4_UDP, my_thread_index);
+
+         /* no listener */
+         if (PREDICT_FALSE (s0 == 0))
+           {
+             error0 = SESSION_ERROR_NO_LISTENER;
+             goto trace0;
+           }
+
+         f0 = s0->server_rx_fifo;
+
+         /* established hit */
+         if (PREDICT_TRUE (s0->session_state == SESSION_STATE_READY))
+           {
+             udp_len0 = clib_net_to_host_u16 (udp0->length);
+
+             if (PREDICT_FALSE (udp_len0 > svm_fifo_max_enqueue (f0)))
+               {
+                 error0 = SESSION_ERROR_FIFO_FULL;
+                 goto trace0;
+               }
+
+             svm_fifo_enqueue_nowait (f0, 0 /* pid */ ,
+                                      udp_len0 - sizeof (*udp0),
+                                      (u8 *) (udp0 + 1));
+
+             b0->error = node->errors[SESSION_ERROR_ENQUEUED];
+
+             /* We need to send an RX event on this fifo */
+             if (s0->enqueue_epoch != my_enqueue_epoch)
+               {
+                 s0->enqueue_epoch = my_enqueue_epoch;
+
+                 vec_add1 (smm->session_indices_to_enqueue_by_thread
+                           [my_thread_index],
+                           s0 - smm->sessions[my_thread_index]);
+               }
+           }
+         /* listener hit */
+         else if (s0->session_state == SESSION_STATE_LISTENING)
+           {
+             udp_connection_t *us;
+             int rv;
+
+             error0 = SESSION_ERROR_NOT_READY;
+
+             /*
+              * create udp transport session
+              */
+             pool_get (um->udp_sessions[my_thread_index], us);
+
+             us->mtu = 1024;   /* $$$$ policy */
+
+             us->c_lcl_ip4.as_u32 = ip0->dst_address.as_u32;
+             us->c_rmt_ip4.as_u32 = ip0->src_address.as_u32;
+             us->c_lcl_port = udp0->dst_port;
+             us->c_rmt_port = udp0->src_port;
+             us->c_proto = SESSION_TYPE_IP4_UDP;
+             us->c_c_index = us - um->udp_sessions[my_thread_index];
+
+             /*
+              * create stream session and attach the udp session to it
+              */
+             rv = stream_session_accept (&us->connection, s0->session_index,
+                                         SESSION_TYPE_IP4_UDP,
+                                         1 /*notify */ );
+             if (rv)
+               error0 = rv;
+
+           }
+         else
+           {
+
+             error0 = SESSION_ERROR_NOT_READY;
+             goto trace0;
+           }
+
+       trace0:
+         b0->error = node->errors[error0];
+
+         if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
+                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
+           {
+             udp4_uri_input_trace_t *t =
+               vlib_add_trace (vm, node, b0, sizeof (*t));
+
+             t->session = ~0;
+             if (s0)
+               t->session = s0 - smm->sessions[my_thread_index];
+             t->disposition = error0;
+             t->thread_index = my_thread_index;
+           }
+
+         /* verify speculative enqueue, maybe switch current next frame */
+         vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
+                                          to_next, n_left_to_next,
+                                          bi0, next0);
+       }
+
+      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
+    }
+
+  /* Send enqueue events */
+
+  session_indices_to_enqueue =
+    smm->session_indices_to_enqueue_by_thread[my_thread_index];
+
+  for (i = 0; i < vec_len (session_indices_to_enqueue); i++)
+    {
+      session_fifo_event_t evt;
+      unix_shared_memory_queue_t *q;
+      stream_session_t *s0;
+      application_t *server0;
+
+      /* Get session */
+      s0 = pool_elt_at_index (smm->sessions[my_thread_index],
+                             session_indices_to_enqueue[i]);
+
+      /* Get session's server */
+      server0 = application_get (s0->app_index);
+
+      /* Built-in server? Deliver the goods... */
+      if (server0->cb_fns.builtin_server_rx_callback)
+       {
+         server0->cb_fns.builtin_server_rx_callback (s0);
+         continue;
+       }
+
+      /* Fabricate event */
+      evt.fifo = s0->server_rx_fifo;
+      evt.event_type = FIFO_EVENT_SERVER_RX;
+      evt.event_id = serial_number++;
+      evt.enqueue_length = svm_fifo_max_dequeue (s0->server_rx_fifo);
+
+      /* Add event to server's event queue */
+      q = server0->event_queue;
+
+      /* Don't block for lack of space */
+      if (PREDICT_TRUE (q->cursize < q->maxsize))
+       unix_shared_memory_queue_add (server0->event_queue, (u8 *) & evt,
+                                     0 /* do wait for mutex */ );
+      else
+       {
+         vlib_node_increment_counter (vm, udp4_uri_input_node.index,
+                                      SESSION_ERROR_FIFO_FULL, 1);
+       }
+      if (1)
+       {
+         ELOG_TYPE_DECLARE (e) =
+         {
+         .format = "evt-enqueue: id %d length %d",.format_args = "i4i4",};
+         struct
+         {
+           u32 data[2];
+         } *ed;
+         ed = ELOG_DATA (&vlib_global_main.elog_main, e);
+         ed->data[0] = evt.event_id;
+         ed->data[1] = evt.enqueue_length;
+       }
+    }
+
+  vec_reset_length (session_indices_to_enqueue);
+
+  smm->session_indices_to_enqueue_by_thread[my_thread_index] =
+    session_indices_to_enqueue;
+
+  return frame->n_vectors;
+}
+
+VLIB_REGISTER_NODE (udp4_uri_input_node) =
+{
+  .function = udp4_uri_input_node_fn,.name = "udp4-uri-input",.vector_size =
+    sizeof (u32),.format_trace = format_udp4_uri_input_trace,.type =
+    VLIB_NODE_TYPE_INTERNAL,.n_errors =
+    ARRAY_LEN (udp4_uri_input_error_strings),.error_strings =
+    udp4_uri_input_error_strings,.n_next_nodes = UDP4_URI_INPUT_N_NEXT,
+    /* edit / add dispositions here */
+    .next_nodes =
+  {
+  [UDP4_URI_INPUT_NEXT_DROP] = "error-drop",}
+,};
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
similarity index 96%
rename from src/vnet/ip/udp_local.c
rename to src/vnet/udp/udp_local.c
index 13ab6e4..6b239f7 100644 (file)
@@ -17,8 +17,8 @@
 
 #include <vlib/vlib.h>
 #include <vnet/pg/pg.h>
-#include <vnet/ip/udp.h>
-#include <vnet/ip/udp_packet.h>
+#include <vnet/udp/udp.h>
+#include <vnet/udp/udp_packet.h>
 #include <vppinfra/sparse_vec.h>
 
 udp_main_t udp_main;
@@ -527,6 +527,27 @@ udp_register_dst_port (vlib_main_t * vm,
   n[0] = pi->next_index;
 }
 
+void
+udp_unregister_dst_port (vlib_main_t * vm, udp_dst_port_t dst_port, u8 is_ip4)
+{
+  udp_main_t *um = &udp_main;
+  udp_dst_port_info_t *pi;
+  udp_input_runtime_t *rt;
+  u16 *n;
+
+  pi = udp_get_dst_port_info (um, dst_port, is_ip4);
+  /* Not registered? Fagedaboudit */
+  if (!pi)
+    return;
+
+  /* Kill the mapping. Don't bother killing the pi, it may be back. */
+  rt = vlib_node_get_runtime_data
+    (vm, is_ip4 ? udp4_input_node.index : udp6_input_node.index);
+  n = sparse_vec_validate (rt->next_by_dst_port,
+                          clib_host_to_net_u16 (dst_port));
+  n[0] = SPARSE_VEC_INVALID_INDEX;
+}
+
 void
 udp_punt_unknown (vlib_main_t * vm, u8 is_ip4, u8 is_add)
 {
similarity index 100%
rename from src/vnet/ip/udp_pg.c
rename to src/vnet/udp/udp_pg.c
index 142aced..c4075db 100644 (file)
@@ -51,6 +51,7 @@
 #include <vnet/lisp-cp/lisp.api.h>
 #include <vnet/lisp-gpe/lisp_gpe.api.h>
 #include <vnet/lisp-cp/one.api.h>
+#include <vnet/session/session.api.h>
 #include <vnet/mpls/mpls.api.h>
 #include <vnet/sr/sr.api.h>
 #include <vnet/classify/classify.api.h>
index 1b4bc44..e768d23 100644 (file)
@@ -29,7 +29,7 @@
 #include <vnet/vxlan-gpe/vxlan_gpe_packet.h>
 #include <vnet/ip/ip4_packet.h>
 #include <vnet/ip/ip6_packet.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 
 /**
  * @brief VXLAN GPE header struct
index adfa3a8..dca1cd1 100644 (file)
@@ -26,7 +26,7 @@
 #include <vnet/vxlan/vxlan_packet.h>
 #include <vnet/ip/ip4_packet.h>
 #include <vnet/ip/ip6_packet.h>
-#include <vnet/ip/udp.h>
+#include <vnet/udp/udp.h>
 #include <vnet/dpo/dpo.h>
 #include <vnet/adj/adj_types.h>
 
index 24f4829..2d6e4f3 100644 (file)
@@ -38,6 +38,7 @@
  * IPSEC-GRE APIs: see .../src/vnet/ipsec-gre/{ipsec_gre.api, ipsec_gre_api.c}
  * LISP APIs: see .../src/vnet/lisp/{lisp.api, lisp_api.c}
  * LISP-GPE APIs: see .../src/vnet/lisp-gpe/{lisp_gpe.api, lisp_gpe_api.c}
+ * SESSION APIs: .../vnet/session/{session.api session_api.c}
  * MPLS APIs: see .../src/vnet/mpls/{mpls.api, mpls_api.c}
  * SR APIs: see .../src/vnet/sr/{sr.api, sr_api.c}
  * DPDK APIs: see ... /src/vnet/devices/dpdk/{dpdk.api, dpdk_api.c}
index 8d37595..4b9f0c2 100644 (file)
@@ -157,7 +157,9 @@ nobase_include_HEADERS = \
   vppinfra/asm_mips.h \
   vppinfra/asm_x86.h \
   vppinfra/bihash_8_8.h \
+  vppinfra/bihash_16_8.h \
   vppinfra/bihash_24_8.h \
+  vppinfra/bihash_48_8.h \
   vppinfra/bihash_template.h \
   vppinfra/bihash_template.c \
   vppinfra/bitmap.h \
@@ -206,6 +208,7 @@ nobase_include_HEADERS = \
   vppinfra/timer.h \
   vppinfra/tw_timer_2t_1w_2048sl.h \
   vppinfra/tw_timer_16t_2w_512sl.h \
+  vppinfra/tw_timer_16t_1w_2048sl.h \
   vppinfra/tw_timer_template.h \
   vppinfra/tw_timer_template.c \
   vppinfra/types.h \
@@ -261,6 +264,8 @@ CLIB_CORE = \
   vppinfra/tw_timer_2t_1w_2048sl.c \
   vppinfra/tw_timer_16t_2w_512sl.h \
   vppinfra/tw_timer_16t_2w_512sl.c \
+  vppinfra/tw_timer_16t_1w_2048sl.h \
+  vppinfra/tw_timer_16t_1w_2048sl.c \
   vppinfra/unformat.c \
   vppinfra/vec.c \
   vppinfra/vector.c \
diff --git a/src/vppinfra/bihash_16_8.h b/src/vppinfra/bihash_16_8.h
new file mode 100644 (file)
index 0000000..ce80f70
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#undef BIHASH_TYPE
+
+#define BIHASH_TYPE _16_8
+#define BIHASH_KVP_PER_PAGE 4
+
+#ifndef __included_bihash_16_8_h__
+#define __included_bihash_16_8_h__
+
+#include <vppinfra/heap.h>
+#include <vppinfra/format.h>
+#include <vppinfra/pool.h>
+#include <vppinfra/xxhash.h>
+
+typedef struct
+{
+  u64 key[2];
+  u64 value;
+} clib_bihash_kv_16_8_t;
+
+static inline int
+clib_bihash_is_free_16_8 (clib_bihash_kv_16_8_t * v)
+{
+  /* Free values are memset to 0xff, check a bit... */
+  if (v->key[0] == ~0ULL && v->value == ~0ULL)
+    return 1;
+  return 0;
+}
+
+#if __SSE4_2__
+#ifndef __defined_crc_u32__
+#define __defined_crc_u32__
+static inline u32
+crc_u32 (u32 data, u32 value)
+{
+  __asm__ volatile ("crc32l %[data], %[value];":[value] "+r" (value):[data]
+                   "rm" (data));
+  return value;
+}
+#endif /* __defined_crc_u32__ */
+
+static inline u64
+clib_bihash_hash_16_8 (clib_bihash_kv_16_8_t * v)
+{
+  u32 *dp = (u32 *) & v->key[0];
+  u32 value = 0;
+
+  value = crc_u32 (dp[0], value);
+  value = crc_u32 (dp[1], value);
+  value = crc_u32 (dp[2], value);
+  value = crc_u32 (dp[3], value);
+
+  return value;
+}
+#else
+static inline u64
+clib_bihash_hash_16_8 (clib_bihash_kv_16_8_t * v)
+{
+  u64 tmp = v->key[0] ^ v->key[1];
+  return clib_xxhash (tmp);
+}
+#endif
+
+static inline u8 *
+format_bihash_kvp_16_8 (u8 * s, va_list * args)
+{
+  clib_bihash_kv_16_8_t *v = va_arg (*args, clib_bihash_kv_16_8_t *);
+
+  s = format (s, "key %llu %llu value %llu", v->key[0], v->key[1], v->value);
+  return s;
+}
+
+static inline int
+clib_bihash_key_compare_16_8 (u64 * a, u64 * b)
+{
+  return ((a[0] ^ b[0]) | (a[1] ^ b[1])) == 0;
+}
+
+#undef __included_bihash_template_h__
+#include <vppinfra/bihash_template.h>
+
+#endif /* __included_bihash_16_8_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vppinfra/bihash_48_8.h b/src/vppinfra/bihash_48_8.h
new file mode 100644 (file)
index 0000000..1a6e769
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2016 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#undef BIHASH_TYPE
+
+#define BIHASH_TYPE _48_8
+#define BIHASH_KVP_PER_PAGE 4
+
+#ifndef __included_bihash_48_8_h__
+#define __included_bihash_48_8_h__
+
+#include <vppinfra/heap.h>
+#include <vppinfra/format.h>
+#include <vppinfra/pool.h>
+#include <vppinfra/xxhash.h>
+
+typedef struct
+{
+  u64 key[6];
+  u64 value;
+} clib_bihash_kv_48_8_t;
+
+static inline int
+clib_bihash_is_free_48_8 (const clib_bihash_kv_48_8_t * v)
+{
+  /* Free values are memset to 0xff, check a bit... */
+  if (v->key[0] == ~0ULL && v->value == ~0ULL)
+    return 1;
+  return 0;
+}
+
+#if __SSE4_2__
+#ifndef __defined_crc_u32__
+#define __defined_crc_u32__
+static inline u32
+crc_u32 (u32 data, u32 value)
+{
+  __asm__ volatile ("crc32l %[data], %[value];":[value] "+r" (value):[data]
+                   "rm" (data));
+  return value;
+}
+#endif /* __defined_crc_u32__ */
+
+static inline u64
+clib_bihash_hash_48_8 (const clib_bihash_kv_48_8_t * v)
+{
+  const u32 *dp = (const u32 *) &v->key[0];
+  u32 value = 0;
+
+  value = crc_u32 (dp[0], value);
+  value = crc_u32 (dp[1], value);
+  value = crc_u32 (dp[2], value);
+  value = crc_u32 (dp[3], value);
+  value = crc_u32 (dp[4], value);
+  value = crc_u32 (dp[5], value);
+  value = crc_u32 (dp[6], value);
+  value = crc_u32 (dp[7], value);
+  value = crc_u32 (dp[8], value);
+  value = crc_u32 (dp[9], value);
+  value = crc_u32 (dp[10], value);
+  value = crc_u32 (dp[11], value);
+
+  return value;
+}
+#else
+static inline u64
+clib_bihash_hash_48_8 (const clib_bihash_kv_48_8_t * v)
+{
+  u64 tmp = v->key[0] ^ v->key[1] ^ v->key[2] ^ v->key[3] ^ v->key[4]
+    ^ v->key[5];
+  return clib_xxhash (tmp);
+}
+#endif
+
+static inline u8 *
+format_bihash_kvp_48_8 (u8 * s, va_list * args)
+{
+  clib_bihash_kv_48_8_t *v = va_arg (*args, clib_bihash_kv_48_8_t *);
+
+  s = format (s, "key %llu %llu %llu %llu %llu %llu value %llu", v->key[0],
+             v->key[1], v->key[2], v->key[3], v->key[4], v->key[5],
+             v->value);
+  return s;
+}
+
+static inline int
+clib_bihash_key_compare_48_8 (const u64 * a, const u64 * b)
+{
+  return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2]) | (a[3] ^ b[3])
+         | (a[4] ^ b[4]) | (a[5] ^ b[5])) == 0;
+}
+
+#undef __included_bihash_template_h__
+#include <vppinfra/bihash_template.h>
+
+#endif /* __included_bihash_48_8_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vppinfra/tw_timer_16t_1w_2048sl.c b/src/vppinfra/tw_timer_16t_1w_2048sl.c
new file mode 100644 (file)
index 0000000..3f34204
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vppinfra/error.h>
+#include "tw_timer_16t_1w_2048sl.h"
+#include "tw_timer_template.c"
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */
diff --git a/src/vppinfra/tw_timer_16t_1w_2048sl.h b/src/vppinfra/tw_timer_16t_1w_2048sl.h
new file mode 100644 (file)
index 0000000..685ac31
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2017 Cisco and/or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __included_tw_timer_16t_2w_512sl_h__
+#define __included_tw_timer_16t_2w_512sl_h__
+
+/* ... So that a client app can create multiple wheel geometries */
+#undef TW_TIMER_WHEELS
+#undef TW_SLOTS_PER_RING
+#undef TW_RING_SHIFT
+#undef TW_RING_MASK
+#undef TW_TIMERS_PER_OBJECT
+#undef LOG2_TW_TIMERS_PER_OBJECT
+#undef TW_SUFFIX
+
+#define TW_TIMER_WHEELS 1
+#define TW_SLOTS_PER_RING 2048
+#define TW_RING_SHIFT 11
+#define TW_RING_MASK (TW_SLOTS_PER_RING -1)
+#define TW_TIMERS_PER_OBJECT 16
+#define LOG2_TW_TIMERS_PER_OBJECT 4
+#define TW_SUFFIX _16t_1w_2048sl
+
+#include <vppinfra/tw_timer_template.h>
+
+#endif /* __included_tw_timer_16t_2w_512sl_h__ */
+
+/*
+ * fd.io coding-style-patch-verification: ON
+ *
+ * Local Variables:
+ * eval: (c-set-style "gnu")
+ * End:
+ */