acl-plugin: an elog-based tracing implementation for troubleshooting the conn cleaner...
[vpp.git] / src / plugins / acl / fa_node.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <stddef.h>
16 #include <netinet/in.h>
17
18 #include <vlib/vlib.h>
19 #include <vnet/vnet.h>
20 #include <vnet/pg/pg.h>
21 #include <vppinfra/error.h>
22 #include <acl/acl.h>
23 #include <vppinfra/bihash_40_8.h>
24
25 #include <vppinfra/bihash_template.h>
26 #include <vppinfra/bihash_template.c>
27 #include <vnet/ip/icmp46_packet.h>
28
29 #include "fa_node.h"
30 #include "hash_lookup.h"
31
32 typedef struct
33 {
34   u32 next_index;
35   u32 sw_if_index;
36   u32 match_acl_in_index;
37   u32 match_rule_index;
38   u64 packet_info[6];
39   u32 trace_bitmap;
40   u8 action;
41 } acl_fa_trace_t;
42
43 /* ICMPv4 invert type for stateful ACL */
44 static const u8 icmp4_invmap[] = {
45   [ICMP4_echo_reply] = ICMP4_echo_request + 1,
46   [ICMP4_timestamp_reply] = ICMP4_timestamp_request + 1,
47   [ICMP4_information_reply] = ICMP4_information_request + 1,
48   [ICMP4_address_mask_reply] = ICMP4_address_mask_request + 1
49 };
50
51 /* Supported ICMPv4 messages for session creation */
52 static const u8 icmp4_valid_new[] = {
53   [ICMP4_echo_request] = 1,
54   [ICMP4_timestamp_request] = 1,
55   [ICMP4_information_request] = 1,
56   [ICMP4_address_mask_request] = 1
57 };
58
59 /* ICMPv6 invert type for stateful ACL */
60 static const u8 icmp6_invmap[] = {
61   [ICMP6_echo_reply - 128]   = ICMP6_echo_request + 1,
62   [ICMP6_node_information_response - 128] = ICMP6_node_information_request + 1
63 };
64
65 /* Supported ICMPv6 messages for session creation */
66 static const u8 icmp6_valid_new[] = {
67   [ICMP6_echo_request - 128] = 1,
68   [ICMP6_node_information_request - 128] = 1
69 };
70
71 /* IP4 and IP6 protocol numbers of ICMP */
72 static u8 icmp_protos[] = { IP_PROTOCOL_ICMP, IP_PROTOCOL_ICMP6 };
73
74 static u8 *
75 format_fa_5tuple (u8 * s, va_list * args)
76 {
77   fa_5tuple_t *p5t = va_arg (*args, fa_5tuple_t *);
78
79   return format(s, "%s sw_if_index %d (lsb16 %d) l3 %s%s %U -> %U"
80                    " l4 proto %d l4_valid %d port %d -> %d tcp flags (%s) %02x rsvd %x",
81                 p5t->pkt.is_input ? "input" : "output",
82                 p5t->pkt.sw_if_index, p5t->l4.lsb_of_sw_if_index, p5t->pkt.is_ip6 ? "ip6" : "ip4",
83                 p5t->pkt.is_nonfirst_fragment ? " non-initial fragment" : "",
84                 format_ip46_address, &p5t->addr[0], p5t->pkt.is_ip6 ? IP46_TYPE_IP6 : IP46_TYPE_IP4,
85                 format_ip46_address, &p5t->addr[1], p5t->pkt.is_ip6 ? IP46_TYPE_IP6 : IP46_TYPE_IP4,
86                 p5t->l4.proto, p5t->pkt.l4_valid,
87                 p5t->l4.port[0], p5t->l4.port[1],
88                 p5t->pkt.tcp_flags_valid ? "valid": "invalid",
89                 p5t->pkt.tcp_flags,
90                 p5t->pkt.flags_reserved);
91 }
92
93 u8 *
94 format_acl_plugin_5tuple (u8 * s, va_list * args)
95 {
96   return format_fa_5tuple(s, args);
97 }
98
99 /* packet trace format function */
100 static u8 *
101 format_acl_fa_trace (u8 * s, va_list * args)
102 {
103   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
104   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
105   acl_fa_trace_t *t = va_arg (*args, acl_fa_trace_t *);
106
107   s =
108     format (s,
109             "acl-plugin: sw_if_index %d, next index %d, action: %d, match: acl %d rule %d trace_bits %08x\n"
110             "  pkt info %016llx %016llx %016llx %016llx %016llx %016llx",
111             t->sw_if_index, t->next_index, t->action, t->match_acl_in_index,
112             t->match_rule_index, t->trace_bitmap,
113             t->packet_info[0], t->packet_info[1], t->packet_info[2],
114             t->packet_info[3], t->packet_info[4], t->packet_info[5]);
115
116   /* Now also print out the packet_info in a form usable by humans */
117   s = format (s, "\n   %U", format_fa_5tuple, t->packet_info);
118   return s;
119 }
120
121 /* *INDENT-OFF* */
122 #define foreach_acl_fa_error \
123 _(ACL_DROP, "ACL deny packets")  \
124 _(ACL_PERMIT, "ACL permit packets")  \
125 _(ACL_NEW_SESSION, "new sessions added") \
126 _(ACL_EXIST_SESSION, "existing session packets") \
127 _(ACL_CHECK, "checked packets") \
128 _(ACL_RESTART_SESSION_TIMER, "restart session timer") \
129 _(ACL_TOO_MANY_SESSIONS, "too many sessions to add new") \
130 /* end  of errors */
131
132 typedef enum
133 {
134 #define _(sym,str) ACL_FA_ERROR_##sym,
135   foreach_acl_fa_error
136 #undef _
137     ACL_FA_N_ERROR,
138 } acl_fa_error_t;
139
140 static char *acl_fa_error_strings[] = {
141 #define _(sym,string) string,
142   foreach_acl_fa_error
143 #undef _
144 };
145 /* *INDENT-ON* */
146
147 static void *
148 get_ptr_to_offset (vlib_buffer_t * b0, int offset)
149 {
150   u8 *p = vlib_buffer_get_current (b0) + offset;
151   return p;
152 }
153
154
155 static int
156 fa_acl_match_addr (ip46_address_t * addr1, ip46_address_t * addr2,
157                    int prefixlen, int is_ip6)
158 {
159   if (prefixlen == 0)
160     {
161       /* match any always succeeds */
162       return 1;
163     }
164   if (is_ip6)
165     {
166       if (memcmp (addr1, addr2, prefixlen / 8))
167         {
168           /* If the starting full bytes do not match, no point in bittwidling the thumbs further */
169           return 0;
170         }
171       if (prefixlen % 8)
172         {
173           u8 b1 = *((u8 *) addr1 + 1 + prefixlen / 8);
174           u8 b2 = *((u8 *) addr2 + 1 + prefixlen / 8);
175           u8 mask0 = (0xff - ((1 << (8 - (prefixlen % 8))) - 1));
176           return (b1 & mask0) == b2;
177         }
178       else
179         {
180           /* The prefix fits into integer number of bytes, so nothing left to do */
181           return 1;
182         }
183     }
184   else
185     {
186       uint32_t a1 = ntohl (addr1->ip4.as_u32);
187       uint32_t a2 = ntohl (addr2->ip4.as_u32);
188       uint32_t mask0 = 0xffffffff - ((1 << (32 - prefixlen)) - 1);
189       return (a1 & mask0) == a2;
190     }
191 }
192
193 static int
194 fa_acl_match_port (u16 port, u16 port_first, u16 port_last, int is_ip6)
195 {
196   return ((port >= port_first) && (port <= port_last));
197 }
198
199 int
200 single_acl_match_5tuple (acl_main_t * am, u32 acl_index, fa_5tuple_t * pkt_5tuple,
201                   int is_ip6, u8 * r_action, u32 * r_acl_match_p,
202                   u32 * r_rule_match_p, u32 * trace_bitmap)
203 {
204   int i;
205   acl_list_t *a;
206   acl_rule_t *r;
207
208   if (pool_is_free_index (am->acls, acl_index))
209     {
210       if (r_acl_match_p)
211         *r_acl_match_p = acl_index;
212       if (r_rule_match_p)
213         *r_rule_match_p = -1;
214       /* the ACL does not exist but is used for policy. Block traffic. */
215       return 0;
216     }
217   a = am->acls + acl_index;
218   for (i = 0; i < a->count; i++)
219     {
220       r = a->rules + i;
221       if (is_ip6 != r->is_ipv6)
222         {
223           continue;
224         }
225       if (!fa_acl_match_addr
226           (&pkt_5tuple->addr[1], &r->dst, r->dst_prefixlen, is_ip6))
227         continue;
228
229 #ifdef FA_NODE_VERBOSE_DEBUG
230       clib_warning
231         ("ACL_FA_NODE_DBG acl %d rule %d pkt dst addr %U match rule addr %U/%d",
232          acl_index, i, format_ip46_address, &pkt_5tuple->addr[1],
233          r->is_ipv6 ? IP46_TYPE_IP6: IP46_TYPE_IP4, format_ip46_address,
234          &r->dst, r->is_ipv6 ? IP46_TYPE_IP6: IP46_TYPE_IP4,
235          r->dst_prefixlen);
236 #endif
237
238       if (!fa_acl_match_addr
239           (&pkt_5tuple->addr[0], &r->src, r->src_prefixlen, is_ip6))
240         continue;
241
242 #ifdef FA_NODE_VERBOSE_DEBUG
243       clib_warning
244         ("ACL_FA_NODE_DBG acl %d rule %d pkt src addr %U match rule addr %U/%d",
245          acl_index, i, format_ip46_address, &pkt_5tuple->addr[0],
246          r->is_ipv6 ? IP46_TYPE_IP6: IP46_TYPE_IP4, format_ip46_address,
247          &r->src, r->is_ipv6 ? IP46_TYPE_IP6: IP46_TYPE_IP4,
248          r->src_prefixlen);
249       clib_warning
250         ("ACL_FA_NODE_DBG acl %d rule %d trying to match pkt proto %d with rule %d",
251          acl_index, i, pkt_5tuple->l4.proto, r->proto);
252 #endif
253       if (r->proto)
254         {
255           if (pkt_5tuple->l4.proto != r->proto)
256             continue;
257
258           if (PREDICT_FALSE (pkt_5tuple->pkt.is_nonfirst_fragment &&
259                      am->l4_match_nonfirst_fragment))
260           {
261             /* non-initial fragment with frag match configured - match this rule */
262             *trace_bitmap |= 0x80000000;
263             *r_action = r->is_permit;
264             if (r_acl_match_p)
265               *r_acl_match_p = acl_index;
266             if (r_rule_match_p)
267               *r_rule_match_p = i;
268             return 1;
269           }
270
271           /* A sanity check just to ensure we are about to match the ports extracted from the packet */
272           if (PREDICT_FALSE (!pkt_5tuple->pkt.l4_valid))
273             continue;
274
275 #ifdef FA_NODE_VERBOSE_DEBUG
276           clib_warning
277             ("ACL_FA_NODE_DBG acl %d rule %d pkt proto %d match rule %d",
278              acl_index, i, pkt_5tuple->l4.proto, r->proto);
279 #endif
280
281           if (!fa_acl_match_port
282               (pkt_5tuple->l4.port[0], r->src_port_or_type_first,
283                r->src_port_or_type_last, is_ip6))
284             continue;
285
286 #ifdef FA_NODE_VERBOSE_DEBUG
287           clib_warning
288             ("ACL_FA_NODE_DBG acl %d rule %d pkt sport %d match rule [%d..%d]",
289              acl_index, i, pkt_5tuple->l4.port[0], r->src_port_or_type_first,
290              r->src_port_or_type_last);
291 #endif
292
293           if (!fa_acl_match_port
294               (pkt_5tuple->l4.port[1], r->dst_port_or_code_first,
295                r->dst_port_or_code_last, is_ip6))
296             continue;
297
298 #ifdef FA_NODE_VERBOSE_DEBUG
299           clib_warning
300             ("ACL_FA_NODE_DBG acl %d rule %d pkt dport %d match rule [%d..%d]",
301              acl_index, i, pkt_5tuple->l4.port[1], r->dst_port_or_code_first,
302              r->dst_port_or_code_last);
303 #endif
304           if (pkt_5tuple->pkt.tcp_flags_valid
305               && ((pkt_5tuple->pkt.tcp_flags & r->tcp_flags_mask) !=
306                   r->tcp_flags_value))
307             continue;
308         }
309       /* everything matches! */
310 #ifdef FA_NODE_VERBOSE_DEBUG
311       clib_warning ("ACL_FA_NODE_DBG acl %d rule %d FULL-MATCH, action %d",
312                     acl_index, i, r->is_permit);
313 #endif
314       *r_action = r->is_permit;
315       if (r_acl_match_p)
316         *r_acl_match_p = acl_index;
317       if (r_rule_match_p)
318         *r_rule_match_p = i;
319       return 1;
320     }
321   return 0;
322 }
323
324 static u8
325 linear_multi_acl_match_5tuple (u32 sw_if_index, fa_5tuple_t * pkt_5tuple, int is_l2,
326                        int is_ip6, int is_input, u32 * acl_match_p,
327                        u32 * rule_match_p, u32 * trace_bitmap)
328 {
329   acl_main_t *am = &acl_main;
330   int i;
331   u32 *acl_vector;
332   u8 action = 0;
333
334   if (is_input)
335     {
336       vec_validate (am->input_acl_vec_by_sw_if_index, sw_if_index);
337       acl_vector = am->input_acl_vec_by_sw_if_index[sw_if_index];
338     }
339   else
340     {
341       vec_validate (am->output_acl_vec_by_sw_if_index, sw_if_index);
342       acl_vector = am->output_acl_vec_by_sw_if_index[sw_if_index];
343     }
344   for (i = 0; i < vec_len (acl_vector); i++)
345     {
346 #ifdef FA_NODE_VERBOSE_DEBUG
347       clib_warning ("ACL_FA_NODE_DBG: Trying to match ACL: %d",
348                     acl_vector[i]);
349 #endif
350       if (single_acl_match_5tuple
351           (am, acl_vector[i], pkt_5tuple, is_ip6, &action,
352            acl_match_p, rule_match_p, trace_bitmap))
353         {
354           return action;
355         }
356     }
357   if (vec_len (acl_vector) > 0)
358     {
359       /* If there are ACLs and none matched, deny by default */
360       return 0;
361     }
362 #ifdef FA_NODE_VERBOSE_DEBUG
363   clib_warning ("ACL_FA_NODE_DBG: No ACL on sw_if_index %d", sw_if_index);
364 #endif
365   /* Deny by default. If there are no ACLs defined we should not be here. */
366   return 0;
367 }
368
369 static u8
370 multi_acl_match_5tuple (u32 sw_if_index, fa_5tuple_t * pkt_5tuple, int is_l2,
371                        int is_ip6, int is_input, u32 * acl_match_p,
372                        u32 * rule_match_p, u32 * trace_bitmap)
373 {
374   acl_main_t *am = &acl_main;
375   if (am->use_hash_acl_matching) {
376     return hash_multi_acl_match_5tuple(sw_if_index, pkt_5tuple, is_l2, is_ip6,
377                                  is_input, acl_match_p, rule_match_p, trace_bitmap);
378   } else {
379     return linear_multi_acl_match_5tuple(sw_if_index, pkt_5tuple, is_l2, is_ip6,
380                                  is_input, acl_match_p, rule_match_p, trace_bitmap);
381   }
382 }
383
384 static int
385 offset_within_packet (vlib_buffer_t * b0, int offset)
386 {
387   /* For the purposes of this code, "within" means we have at least 8 bytes after it */
388   return (offset <= (b0->current_length - 8));
389 }
390
391 static void
392 acl_fill_5tuple (acl_main_t * am, vlib_buffer_t * b0, int is_ip6,
393                  int is_input, int is_l2_path, fa_5tuple_t * p5tuple_pkt)
394 {
395   int l3_offset;
396   int l4_offset;
397   u16 ports[2];
398   u16 proto;
399
400   if (is_l2_path)
401     {
402       l3_offset = ethernet_buffer_header_size(b0);
403     }
404   else
405     {
406       if (is_input)
407         l3_offset = 0;
408       else
409         l3_offset = vnet_buffer(b0)->ip.save_rewrite_length;
410     }
411
412   /* key[0..3] contains src/dst address and is cleared/set below */
413   /* Remainder of the key and per-packet non-key data */
414   p5tuple_pkt->kv.key[4] = 0;
415   p5tuple_pkt->kv.value = 0;
416
417   if (is_ip6)
418     {
419       clib_memcpy (&p5tuple_pkt->addr,
420                    get_ptr_to_offset (b0,
421                                       offsetof (ip6_header_t,
422                                                 src_address) + l3_offset),
423                    sizeof (p5tuple_pkt->addr));
424       proto =
425         *(u8 *) get_ptr_to_offset (b0,
426                                    offsetof (ip6_header_t,
427                                              protocol) + l3_offset);
428       l4_offset = l3_offset + sizeof (ip6_header_t);
429 #ifdef FA_NODE_VERBOSE_DEBUG
430       clib_warning ("ACL_FA_NODE_DBG: proto: %d, l4_offset: %d", proto,
431                     l4_offset);
432 #endif
433       /* IP6 EH handling is here, increment l4_offset if needs to, update the proto */
434       int need_skip_eh = clib_bitmap_get (am->fa_ipv6_known_eh_bitmap, proto);
435       if (PREDICT_FALSE (need_skip_eh))
436         {
437           while (need_skip_eh && offset_within_packet (b0, l4_offset))
438             {
439               /* Fragment header needs special handling */
440               if (PREDICT_FALSE(ACL_EH_FRAGMENT == proto))
441                 {
442                   proto = *(u8 *) get_ptr_to_offset (b0, l4_offset);
443                   u16 frag_offset;
444                   clib_memcpy (&frag_offset, get_ptr_to_offset (b0, 2 + l4_offset), sizeof(frag_offset));
445                   frag_offset = ntohs(frag_offset) >> 3;
446                   if (frag_offset)
447                     {
448                       p5tuple_pkt->pkt.is_nonfirst_fragment = 1;
449                       /* invalidate L4 offset so we don't try to find L4 info */
450                       l4_offset += b0->current_length;
451                     }
452                   else
453                     {
454                       /* First fragment: skip the frag header and move on. */
455                       l4_offset += 8;
456                     }
457                 }
458               else
459                 {
460                   u8 nwords = *(u8 *) get_ptr_to_offset (b0, 1 + l4_offset);
461                   proto = *(u8 *) get_ptr_to_offset (b0, l4_offset);
462                   l4_offset += 8 * (1 + (u16) nwords);
463                 }
464 #ifdef FA_NODE_VERBOSE_DEBUG
465               clib_warning ("ACL_FA_NODE_DBG: new proto: %d, new offset: %d",
466                             proto, l4_offset);
467 #endif
468               need_skip_eh =
469                 clib_bitmap_get (am->fa_ipv6_known_eh_bitmap, proto);
470             }
471         }
472     }
473   else
474     {
475       p5tuple_pkt->kv.key[0] = 0;
476       p5tuple_pkt->kv.key[1] = 0;
477       p5tuple_pkt->kv.key[2] = 0;
478       p5tuple_pkt->kv.key[3] = 0;
479       clib_memcpy (&p5tuple_pkt->addr[0].ip4,
480                    get_ptr_to_offset (b0,
481                                       offsetof (ip4_header_t,
482                                                 src_address) + l3_offset),
483                    sizeof (p5tuple_pkt->addr[0].ip4));
484       clib_memcpy (&p5tuple_pkt->addr[1].ip4,
485                    get_ptr_to_offset (b0,
486                                       offsetof (ip4_header_t,
487                                                 dst_address) + l3_offset),
488                    sizeof (p5tuple_pkt->addr[1].ip4));
489       proto =
490         *(u8 *) get_ptr_to_offset (b0,
491                                    offsetof (ip4_header_t,
492                                              protocol) + l3_offset);
493       l4_offset = l3_offset + sizeof (ip4_header_t);
494       u16 flags_and_fragment_offset;
495       clib_memcpy (&flags_and_fragment_offset,
496                    get_ptr_to_offset (b0,
497                                       offsetof (ip4_header_t,
498                                                 flags_and_fragment_offset)) + l3_offset,
499                                                 sizeof(flags_and_fragment_offset));
500       flags_and_fragment_offset = ntohs (flags_and_fragment_offset);
501
502       /* non-initial fragments have non-zero offset */
503       if ((PREDICT_FALSE(0xfff & flags_and_fragment_offset)))
504         {
505           p5tuple_pkt->pkt.is_nonfirst_fragment = 1;
506           /* invalidate L4 offset so we don't try to find L4 info */
507           l4_offset += b0->current_length;
508         }
509
510     }
511   p5tuple_pkt->l4.proto = proto;
512   if (PREDICT_TRUE (offset_within_packet (b0, l4_offset)))
513     {
514       p5tuple_pkt->pkt.l4_valid = 1;
515       if (icmp_protos[is_ip6] == proto)
516         {
517           /* type */
518           p5tuple_pkt->l4.port[0] =
519             *(u8 *) get_ptr_to_offset (b0,
520                                        l4_offset + offsetof (icmp46_header_t,
521                                                              type));
522           /* code */
523           p5tuple_pkt->l4.port[1] =
524             *(u8 *) get_ptr_to_offset (b0,
525                                        l4_offset + offsetof (icmp46_header_t,
526                                                              code));
527         }
528       else if ((IPPROTO_TCP == proto) || (IPPROTO_UDP == proto))
529         {
530           clib_memcpy (&ports,
531                        get_ptr_to_offset (b0,
532                                           l4_offset + offsetof (tcp_header_t,
533                                                                 src_port)),
534                        sizeof (ports));
535           p5tuple_pkt->l4.port[0] = ntohs (ports[0]);
536           p5tuple_pkt->l4.port[1] = ntohs (ports[1]);
537
538           p5tuple_pkt->pkt.tcp_flags =
539             *(u8 *) get_ptr_to_offset (b0,
540                                        l4_offset + offsetof (tcp_header_t,
541                                                              flags));
542           p5tuple_pkt->pkt.tcp_flags_valid = (proto == IPPROTO_TCP);
543         }
544       /*
545        * FIXME: rather than the above conditional, here could
546        * be a nice generic mechanism to extract two L4 values:
547        *
548        * have a per-protocol array of 4 elements like this:
549        *   u8 offset; to take the byte from, off L4 header
550        *   u8 mask; to mask it with, before storing
551        *
552        * this way we can describe UDP, TCP and ICMP[46] semantics,
553        * and add a sort of FPM-type behavior for other protocols.
554        *
555        * Of course, is it faster ? and is it needed ?
556        *
557        */
558     }
559 }
560
561 static int
562 acl_fa_ifc_has_sessions (acl_main_t * am, int sw_if_index0)
563 {
564   return am->fa_sessions_hash_is_initialized;
565 }
566
567 static int
568 acl_fa_ifc_has_in_acl (acl_main_t * am, int sw_if_index0)
569 {
570   int it_has = clib_bitmap_get (am->fa_in_acl_on_sw_if_index, sw_if_index0);
571   return it_has;
572 }
573
574 static int
575 acl_fa_ifc_has_out_acl (acl_main_t * am, int sw_if_index0)
576 {
577   int it_has = clib_bitmap_get (am->fa_out_acl_on_sw_if_index, sw_if_index0);
578   return it_has;
579 }
580
581 /* Session keys match the packets received, and mirror the packets sent */
582 static u32
583 acl_make_5tuple_session_key (acl_main_t * am, int is_input, int is_ip6,
584                              u32 sw_if_index, fa_5tuple_t * p5tuple_pkt,
585                              fa_5tuple_t * p5tuple_sess)
586 {
587   int src_index = is_input ? 0 : 1;
588   int dst_index = is_input ? 1 : 0;
589   u32 valid_new_sess = 1;
590   p5tuple_sess->addr[src_index] = p5tuple_pkt->addr[0];
591   p5tuple_sess->addr[dst_index] = p5tuple_pkt->addr[1];
592   p5tuple_sess->l4.as_u64 = p5tuple_pkt->l4.as_u64;
593
594   if (PREDICT_TRUE(p5tuple_pkt->l4.proto != icmp_protos[is_ip6]))
595     {
596       p5tuple_sess->l4.port[src_index] = p5tuple_pkt->l4.port[0];
597       p5tuple_sess->l4.port[dst_index] = p5tuple_pkt->l4.port[1];
598     }
599   else
600     {
601       static const u8 * icmp_invmap[] = { icmp4_invmap, icmp6_invmap };
602       static const u8 * icmp_valid_new[] = { icmp4_valid_new, icmp6_valid_new };
603       static const u8 icmp_invmap_size[] = { sizeof(icmp4_invmap),
604                                              sizeof(icmp6_invmap) };
605       static const u8 icmp_valid_new_size[] = { sizeof(icmp4_valid_new),
606                                                 sizeof(icmp6_valid_new) };
607       int type = is_ip6 ? p5tuple_pkt->l4.port[0]-128: p5tuple_pkt->l4.port[0];
608
609       p5tuple_sess->l4.port[0] = p5tuple_pkt->l4.port[0];
610       p5tuple_sess->l4.port[1] = p5tuple_pkt->l4.port[1];
611
612       /*
613        * Invert ICMP type for valid icmp_invmap messages:
614        *  1) input node with outbound ACL interface
615        *  2) output node with inbound ACL interface
616        *
617        */
618       if ((is_input && acl_fa_ifc_has_out_acl(am, sw_if_index)) ||
619           (!is_input && acl_fa_ifc_has_in_acl(am, sw_if_index)))
620         {
621           if (type >= 0 &&
622               type <= icmp_invmap_size[is_ip6] &&
623               icmp_invmap[is_ip6][type])
624             {
625               p5tuple_sess->l4.port[0] = icmp_invmap[is_ip6][type] - 1;
626             }
627         }
628
629       /*
630        * ONLY ICMP messages defined in icmp4_valid_new/icmp6_valid_new table
631        * are allowed to create stateful ACL.
632        * The other messages will be forwarded without creating a reflexive ACL.
633        */
634       if (type < 0 ||
635           type > icmp_valid_new_size[is_ip6] ||
636           !icmp_valid_new[is_ip6][type])
637         {
638           valid_new_sess = 0;
639         }
640     }
641
642     return valid_new_sess;
643 }
644
645
646 static int
647 fa_session_get_timeout_type (acl_main_t * am, fa_session_t * sess)
648 {
649   /* seen both SYNs and ACKs but not FINs means we are in establshed state */
650   u16 masked_flags =
651     sess->tcp_flags_seen.as_u16 & ((TCP_FLAGS_RSTFINACKSYN << 8) +
652                                    TCP_FLAGS_RSTFINACKSYN);
653   switch (sess->info.l4.proto)
654     {
655     case IPPROTO_TCP:
656       if (((TCP_FLAGS_ACKSYN << 8) + TCP_FLAGS_ACKSYN) == masked_flags)
657         {
658           return ACL_TIMEOUT_TCP_IDLE;
659         }
660       else
661         {
662           return ACL_TIMEOUT_TCP_TRANSIENT;
663         }
664       break;
665     case IPPROTO_UDP:
666       return ACL_TIMEOUT_UDP_IDLE;
667       break;
668     default:
669       return ACL_TIMEOUT_UDP_IDLE;
670     }
671 }
672
673
674 static u64
675 fa_session_get_shortest_timeout(acl_main_t * am)
676 {
677   int timeout_type;
678   u64 timeout = ~0LL;
679   for(timeout_type = 0; timeout_type < ACL_N_TIMEOUTS; timeout_type++) {
680     if (timeout > am->session_timeout_sec[timeout_type]) {
681       timeout = am->session_timeout_sec[timeout_type];
682     }
683   }
684   return timeout;
685 }
686
687 /*
688  * Get the timeout of the session in a list since its enqueue time.
689  */
690
691 static u64
692 fa_session_get_list_timeout (acl_main_t * am, fa_session_t * sess)
693 {
694   u64 timeout = am->vlib_main->clib_time.clocks_per_second;
695   /*
696    * we have the shortest possible timeout type in all the lists
697    * (see README-multicore for the rationale)
698    */
699   timeout *= fa_session_get_shortest_timeout(am);
700   return timeout;
701 }
702
703 /*
704  * Get the idle timeout of a session.
705  */
706
707 static u64
708 fa_session_get_timeout (acl_main_t * am, fa_session_t * sess)
709 {
710   u64 timeout = am->vlib_main->clib_time.clocks_per_second;
711   int timeout_type = fa_session_get_timeout_type (am, sess);
712   timeout *= am->session_timeout_sec[timeout_type];
713   return timeout;
714 }
715
716 static void
717 acl_fa_verify_init_sessions (acl_main_t * am)
718 {
719   if (!am->fa_sessions_hash_is_initialized) {
720     u16 wk;
721     /* Allocate the per-worker sessions pools */
722     for (wk = 0; wk < vec_len (am->per_worker_data); wk++) {
723       acl_fa_per_worker_data_t *pw = &am->per_worker_data[wk];
724
725       /*
726       * // In lieu of trying to preallocate the pool and its free bitmap, rather use pool_init_fixed
727       * pool_alloc_aligned(pw->fa_sessions_pool, am->fa_conn_table_max_entries, CLIB_CACHE_LINE_BYTES);
728       * clib_bitmap_validate(pool_header(pw->fa_sessions_pool)->free_bitmap, am->fa_conn_table_max_entries);
729       */
730       pool_init_fixed(pw->fa_sessions_pool, am->fa_conn_table_max_entries);
731     }
732
733     /* ... and the interface session hash table */
734     BV (clib_bihash_init) (&am->fa_sessions_hash,
735                          "ACL plugin FA session bihash",
736                          am->fa_conn_table_hash_num_buckets,
737                          am->fa_conn_table_hash_memory_size);
738     am->fa_sessions_hash_is_initialized = 1;
739   }
740 }
741
742 static inline fa_session_t *get_session_ptr(acl_main_t *am, u16 thread_index, u32 session_index)
743 {
744   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
745   fa_session_t *sess = pool_is_free_index (pw->fa_sessions_pool, session_index) ? 0 : pool_elt_at_index(pw->fa_sessions_pool, session_index);
746   return sess;
747 }
748
749 static inline int is_valid_session_ptr(acl_main_t *am, u16 thread_index, fa_session_t *sess)
750 {
751   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
752   return ((sess != 0) && ((sess - pw->fa_sessions_pool) < pool_len(pw->fa_sessions_pool)));
753 }
754
755 static void
756 acl_fa_conn_list_add_session (acl_main_t * am, fa_full_session_id_t sess_id, u64 now)
757 {
758   fa_session_t *sess = get_session_ptr(am, sess_id.thread_index, sess_id.session_index);
759   u8 list_id = fa_session_get_timeout_type(am, sess);
760   uword thread_index = os_get_thread_index ();
761   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
762   /* the retrieved session thread index must be necessarily the same as the one in the key */
763   ASSERT (sess->thread_index == sess_id.thread_index);
764   /* the retrieved session thread index must be the same as current thread */
765   ASSERT (sess->thread_index == thread_index);
766   sess->link_enqueue_time = now;
767   sess->link_list_id = list_id;
768   sess->link_next_idx = ~0;
769   sess->link_prev_idx = pw->fa_conn_list_tail[list_id];
770   if (~0 != pw->fa_conn_list_tail[list_id]) {
771     fa_session_t *prev_sess = get_session_ptr(am, thread_index, pw->fa_conn_list_tail[list_id]);
772     prev_sess->link_next_idx = sess_id.session_index;
773     /* We should never try to link with a session on another thread */
774     ASSERT(prev_sess->thread_index == sess->thread_index);
775   }
776   pw->fa_conn_list_tail[list_id] = sess_id.session_index;
777   pw->serviced_sw_if_index_bitmap = clib_bitmap_set(pw->serviced_sw_if_index_bitmap, sess->sw_if_index, 1);
778
779   if (~0 == pw->fa_conn_list_head[list_id]) {
780     pw->fa_conn_list_head[list_id] = sess_id.session_index;
781   }
782 }
783
784 static int
785 acl_fa_conn_list_delete_session (acl_main_t *am, fa_full_session_id_t sess_id)
786 {
787   uword thread_index = os_get_thread_index ();
788   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
789   if (thread_index != sess_id.thread_index) {
790     /* If another thread attempts to delete the session, fail it. */
791 #ifdef FA_NODE_VERBOSE_DEBUG
792     clib_warning("thread id in key %d != curr thread index, not deleting");
793 #endif
794     return 0;
795   }
796   fa_session_t *sess = get_session_ptr(am, sess_id.thread_index, sess_id.session_index);
797   /* we should never try to delete the session with another thread index */
798   ASSERT(sess->thread_index == thread_index);
799   if (~0 != sess->link_prev_idx) {
800     fa_session_t *prev_sess = get_session_ptr(am, thread_index, sess->link_prev_idx);
801     /* the previous session must be in the same list as this one */
802     ASSERT(prev_sess->link_list_id == sess->link_list_id);
803     prev_sess->link_next_idx = sess->link_next_idx;
804   }
805   if (~0 != sess->link_next_idx) {
806     fa_session_t *next_sess = get_session_ptr(am, thread_index, sess->link_next_idx);
807     /* The next session must be in the same list as the one we are deleting */
808     ASSERT(next_sess->link_list_id == sess->link_list_id);
809     next_sess->link_prev_idx = sess->link_prev_idx;
810   }
811   if (pw->fa_conn_list_head[sess->link_list_id] == sess_id.session_index) {
812     pw->fa_conn_list_head[sess->link_list_id] = sess->link_next_idx;
813   }
814   if (pw->fa_conn_list_tail[sess->link_list_id] == sess_id.session_index) {
815     pw->fa_conn_list_tail[sess->link_list_id] = sess->link_prev_idx;
816   }
817   return 1;
818 }
819
820 static int
821 acl_fa_restart_timer_for_session (acl_main_t * am, u64 now, fa_full_session_id_t sess_id)
822 {
823   if (acl_fa_conn_list_delete_session(am, sess_id)) {
824     acl_fa_conn_list_add_session(am, sess_id, now);
825     return 1;
826   } else {
827     /*
828      * Our thread does not own this connection, so we can not delete
829      * The session. To avoid the complicated signaling, we simply
830      * pick the list waiting time to be the shortest of the timeouts.
831      * This way we do not have to do anything special, and let
832      * the regular requeue check take care of everything.
833      */
834     return 0;
835   }
836 }
837
838
839 static u8
840 acl_fa_track_session (acl_main_t * am, int is_input, u32 sw_if_index, u64 now,
841                       fa_session_t * sess, fa_5tuple_t * pkt_5tuple)
842 {
843   sess->last_active_time = now;
844   if (pkt_5tuple->pkt.tcp_flags_valid)
845     {
846       sess->tcp_flags_seen.as_u8[is_input] |= pkt_5tuple->pkt.tcp_flags;
847     }
848   return 3;
849 }
850
851
852 static void
853 acl_fa_delete_session (acl_main_t * am, u32 sw_if_index, fa_full_session_id_t sess_id)
854 {
855   void *oldheap = clib_mem_set_heap(am->acl_mheap);
856   fa_session_t *sess = get_session_ptr(am, sess_id.thread_index, sess_id.session_index);
857   ASSERT(sess->thread_index == os_get_thread_index ());
858   BV (clib_bihash_add_del) (&am->fa_sessions_hash,
859                             &sess->info.kv, 0);
860   acl_fa_per_worker_data_t *pw = &am->per_worker_data[sess_id.thread_index];
861   pool_put_index (pw->fa_sessions_pool, sess_id.session_index);
862   /* Deleting from timer structures not needed,
863      as the caller must have dealt with the timers. */
864   vec_validate (pw->fa_session_dels_by_sw_if_index, sw_if_index);
865   clib_mem_set_heap (oldheap);
866   pw->fa_session_dels_by_sw_if_index[sw_if_index]++;
867   clib_smp_atomic_add(&am->fa_session_total_dels, 1);
868 }
869
870 static int
871 acl_fa_can_add_session (acl_main_t * am, int is_input, u32 sw_if_index)
872 {
873   u64 curr_sess_count;
874   curr_sess_count = am->fa_session_total_adds - am->fa_session_total_dels;
875   return (curr_sess_count < am->fa_conn_table_max_entries);
876 }
877
878 static u64
879 acl_fa_get_list_head_expiry_time(acl_main_t *am, acl_fa_per_worker_data_t *pw, u64 now, u16 thread_index, int timeout_type)
880 {
881   fa_session_t *sess = get_session_ptr(am, thread_index, pw->fa_conn_list_head[timeout_type]);
882   /*
883    * We can not check just the index here because inbetween the worker thread might
884    * dequeue the connection from the head just as we are about to check it.
885    */
886   if (!is_valid_session_ptr(am, thread_index, sess)) {
887     return ~0LL; // infinity.
888   } else {
889     u64 timeout_time =
890               sess->link_enqueue_time + fa_session_get_list_timeout (am, sess);
891     return timeout_time;
892   }
893 }
894
895 static int
896 acl_fa_conn_time_to_check (acl_main_t *am, acl_fa_per_worker_data_t *pw, u64 now, u16 thread_index, u32 session_index)
897 {
898   fa_session_t *sess = get_session_ptr(am, thread_index, session_index);
899   u64 timeout_time =
900               sess->link_enqueue_time + fa_session_get_list_timeout (am, sess);
901   return (timeout_time < now) || (sess->link_enqueue_time <= pw->swipe_end_time);
902 }
903
904 /*
905  * see if there are sessions ready to be checked,
906  * do the maintenance (requeue or delete), and
907  * return the total number of sessions reclaimed.
908  */
909 static int
910 acl_fa_check_idle_sessions(acl_main_t *am, u16 thread_index, u64 now)
911 {
912   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
913   fa_full_session_id_t fsid;
914   fsid.thread_index = thread_index;
915   int total_expired = 0;
916
917   {
918     u8 tt = 0;
919     for(tt = 0; tt < ACL_N_TIMEOUTS; tt++) {
920       while((vec_len(pw->expired) < am->fa_max_deleted_sessions_per_interval)
921             && (~0 != pw->fa_conn_list_head[tt])
922             && (acl_fa_conn_time_to_check(am, pw, now, thread_index,
923                                           pw->fa_conn_list_head[tt]))) {
924         fsid.session_index = pw->fa_conn_list_head[tt];
925         elog_acl_maybe_trace_X2(am, "acl_fa_check_idle_sessions: expire session %d on thread %d", "i4i4", (u32)fsid.session_index, (u32)thread_index);
926         vec_add1(pw->expired, fsid.session_index);
927         acl_fa_conn_list_delete_session(am, fsid);
928       }
929     }
930   }
931
932   u32 *psid = NULL;
933   vec_foreach (psid, pw->expired)
934   {
935     fsid.session_index = *psid;
936     if (!pool_is_free_index (pw->fa_sessions_pool, fsid.session_index))
937       {
938         fa_session_t *sess = get_session_ptr(am, thread_index, fsid.session_index);
939         u32 sw_if_index = sess->sw_if_index;
940         u64 sess_timeout_time =
941           sess->last_active_time + fa_session_get_timeout (am, sess);
942         if ((now < sess_timeout_time) && (0 == clib_bitmap_get(pw->pending_clear_sw_if_index_bitmap, sw_if_index)))
943           {
944 #ifdef FA_NODE_VERBOSE_DEBUG
945             clib_warning ("ACL_FA_NODE_CLEAN: Restarting timer for session %d",
946                (int) session_index);
947 #endif
948             /* There was activity on the session, so the idle timeout
949                has not passed. Enqueue for another time period. */
950
951             acl_fa_conn_list_add_session(am, fsid, now);
952             pw->cnt_session_timer_restarted++;
953           }
954         else
955           {
956 #ifdef FA_NODE_VERBOSE_DEBUG
957             clib_warning ("ACL_FA_NODE_CLEAN: Deleting session %d",
958                (int) session_index);
959 #endif
960             acl_fa_delete_session (am, sw_if_index, fsid);
961             pw->cnt_deleted_sessions++;
962           }
963       }
964     else
965       {
966         pw->cnt_already_deleted_sessions++;
967       }
968   }
969   total_expired = vec_len(pw->expired);
970   /* zero out the vector which we have acted on */
971   if (pw->expired)
972     _vec_len (pw->expired) = 0;
973   /* if we were advancing and reached the end
974    * (no more sessions to recycle), reset the fast-forward timestamp */
975
976   if (pw->swipe_end_time && 0 == total_expired)
977     pw->swipe_end_time = 0;
978   return (total_expired);
979 }
980
981 always_inline void
982 acl_fa_try_recycle_session (acl_main_t * am, int is_input, u16 thread_index, u32 sw_if_index)
983 {
984   /* try to recycle a TCP transient session */
985   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
986   u8 timeout_type = ACL_TIMEOUT_TCP_TRANSIENT;
987   fa_full_session_id_t sess_id;
988   sess_id.session_index = pw->fa_conn_list_head[timeout_type];
989   if (~0 != sess_id.session_index) {
990     sess_id.thread_index = thread_index;
991     acl_fa_conn_list_delete_session(am, sess_id);
992     acl_fa_delete_session(am, sw_if_index, sess_id);
993   }
994 }
995
996 static fa_session_t *
997 acl_fa_add_session (acl_main_t * am, int is_input, u32 sw_if_index, u64 now,
998                     fa_5tuple_t * p5tuple)
999 {
1000   clib_bihash_kv_40_8_t *pkv = &p5tuple->kv;
1001   clib_bihash_kv_40_8_t kv;
1002   fa_full_session_id_t f_sess_id;
1003   uword thread_index = os_get_thread_index();
1004   void *oldheap = clib_mem_set_heap(am->acl_mheap);
1005   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1006
1007   f_sess_id.thread_index = thread_index;
1008   fa_session_t *sess;
1009
1010   pool_get_aligned (pw->fa_sessions_pool, sess, CLIB_CACHE_LINE_BYTES);
1011   f_sess_id.session_index = sess - pw->fa_sessions_pool;
1012
1013   kv.key[0] = pkv->key[0];
1014   kv.key[1] = pkv->key[1];
1015   kv.key[2] = pkv->key[2];
1016   kv.key[3] = pkv->key[3];
1017   kv.key[4] = pkv->key[4];
1018   kv.value = f_sess_id.as_u64;
1019
1020   memcpy (sess, pkv, sizeof (pkv->key));
1021   sess->last_active_time = now;
1022   sess->sw_if_index = sw_if_index;
1023   sess->tcp_flags_seen.as_u16 = 0;
1024   sess->thread_index = thread_index;
1025   sess->link_list_id = ~0;
1026   sess->link_prev_idx = ~0;
1027   sess->link_next_idx = ~0;
1028
1029
1030
1031   ASSERT(am->fa_sessions_hash_is_initialized == 1);
1032   BV (clib_bihash_add_del) (&am->fa_sessions_hash,
1033                             &kv, 1);
1034   acl_fa_conn_list_add_session(am, f_sess_id, now);
1035
1036   vec_validate (pw->fa_session_adds_by_sw_if_index, sw_if_index);
1037   clib_mem_set_heap (oldheap);
1038   pw->fa_session_adds_by_sw_if_index[sw_if_index]++;
1039   clib_smp_atomic_add(&am->fa_session_total_adds, 1);
1040   return sess;
1041 }
1042
1043 static int
1044 acl_fa_find_session (acl_main_t * am, u32 sw_if_index0, fa_5tuple_t * p5tuple,
1045                      clib_bihash_kv_40_8_t * pvalue_sess)
1046 {
1047   return (BV (clib_bihash_search)
1048           (&am->fa_sessions_hash, &p5tuple->kv,
1049            pvalue_sess) == 0);
1050 }
1051
1052
1053 always_inline uword
1054 acl_fa_node_fn (vlib_main_t * vm,
1055                 vlib_node_runtime_t * node, vlib_frame_t * frame, int is_ip6,
1056                 int is_input, int is_l2_path, u32 * l2_feat_next_node_index,
1057                 vlib_node_registration_t * acl_fa_node)
1058 {
1059   u32 n_left_from, *from, *to_next;
1060   acl_fa_next_t next_index;
1061   u32 pkts_acl_checked = 0;
1062   u32 pkts_new_session = 0;
1063   u32 pkts_exist_session = 0;
1064   u32 pkts_acl_permit = 0;
1065   u32 pkts_restart_session_timer = 0;
1066   u32 trace_bitmap = 0;
1067   acl_main_t *am = &acl_main;
1068   fa_5tuple_t fa_5tuple, kv_sess;
1069   clib_bihash_kv_40_8_t value_sess;
1070   vlib_node_runtime_t *error_node;
1071   u64 now = clib_cpu_time_now ();
1072   uword thread_index = os_get_thread_index ();
1073
1074   from = vlib_frame_vector_args (frame);
1075   n_left_from = frame->n_vectors;
1076   next_index = node->cached_next_index;
1077
1078   error_node = vlib_node_get_runtime (vm, acl_fa_node->index);
1079
1080   while (n_left_from > 0)
1081     {
1082       u32 n_left_to_next;
1083
1084       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1085
1086       while (n_left_from > 0 && n_left_to_next > 0)
1087         {
1088           u32 bi0;
1089           vlib_buffer_t *b0;
1090           u32 next0 = 0;
1091           u8 action = 0;
1092           u32 sw_if_index0;
1093           int acl_check_needed = 1;
1094           u32 match_acl_in_index = ~0;
1095           u32 match_rule_index = ~0;
1096           u8 error0 = 0;
1097           u32 valid_new_sess;
1098
1099           /* speculatively enqueue b0 to the current next frame */
1100           bi0 = from[0];
1101           to_next[0] = bi0;
1102           from += 1;
1103           to_next += 1;
1104           n_left_from -= 1;
1105           n_left_to_next -= 1;
1106
1107           b0 = vlib_get_buffer (vm, bi0);
1108
1109           if (is_input)
1110             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
1111           else
1112             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_TX];
1113
1114           /*
1115            * Extract the L3/L4 matching info into a 5-tuple structure,
1116            * then create a session key whose layout is independent on forward or reverse
1117            * direction of the packet.
1118            */
1119
1120           acl_fill_5tuple (am, b0, is_ip6, is_input, is_l2_path, &fa_5tuple);
1121           fa_5tuple.l4.lsb_of_sw_if_index = sw_if_index0 & 0xffff;
1122           valid_new_sess = acl_make_5tuple_session_key (am, is_input, is_ip6, sw_if_index0,  &fa_5tuple, &kv_sess);
1123           fa_5tuple.pkt.sw_if_index = sw_if_index0;
1124           fa_5tuple.pkt.is_ip6 = is_ip6;
1125           fa_5tuple.pkt.is_input = is_input;
1126           fa_5tuple.pkt.mask_type_index_lsb = ~0;
1127 #ifdef FA_NODE_VERBOSE_DEBUG
1128           clib_warning
1129             ("ACL_FA_NODE_DBG: session 5-tuple %016llx %016llx %016llx %016llx %016llx : %016llx",
1130              kv_sess.kv.key[0], kv_sess.kv.key[1], kv_sess.kv.key[2],
1131              kv_sess.kv.key[3], kv_sess.kv.key[4], kv_sess.kv.value);
1132           clib_warning
1133             ("ACL_FA_NODE_DBG: packet 5-tuple %016llx %016llx %016llx %016llx %016llx : %016llx",
1134              fa_5tuple.kv.key[0], fa_5tuple.kv.key[1], fa_5tuple.kv.key[2],
1135              fa_5tuple.kv.key[3], fa_5tuple.kv.key[4], fa_5tuple.kv.value);
1136 #endif
1137
1138           /* Try to match an existing session first */
1139
1140           if (acl_fa_ifc_has_sessions (am, sw_if_index0))
1141             {
1142               if (acl_fa_find_session
1143                   (am, sw_if_index0, &kv_sess, &value_sess))
1144                 {
1145                   trace_bitmap |= 0x80000000;
1146                   error0 = ACL_FA_ERROR_ACL_EXIST_SESSION;
1147                   fa_full_session_id_t f_sess_id;
1148
1149                   f_sess_id.as_u64 = value_sess.value;
1150                   ASSERT(f_sess_id.thread_index < vec_len(vlib_mains));
1151
1152                   fa_session_t *sess = get_session_ptr(am, f_sess_id.thread_index, f_sess_id.session_index);
1153                   int old_timeout_type =
1154                     fa_session_get_timeout_type (am, sess);
1155                   action =
1156                     acl_fa_track_session (am, is_input, sw_if_index0, now,
1157                                           sess, &fa_5tuple);
1158                   /* expose the session id to the tracer */
1159                   match_rule_index = f_sess_id.session_index;
1160                   int new_timeout_type =
1161                     fa_session_get_timeout_type (am, sess);
1162                   acl_check_needed = 0;
1163                   pkts_exist_session += 1;
1164                   /* Tracking might have changed the session timeout type, e.g. from transient to established */
1165                   if (PREDICT_FALSE (old_timeout_type != new_timeout_type))
1166                     {
1167                       acl_fa_restart_timer_for_session (am, now, f_sess_id);
1168                       pkts_restart_session_timer++;
1169                       trace_bitmap |=
1170                         0x00010000 + ((0xff & old_timeout_type) << 8) +
1171                         (0xff & new_timeout_type);
1172                     }
1173                   /*
1174                    * I estimate the likelihood to be very low - the VPP needs
1175                    * to have >64K interfaces to start with and then on
1176                    * exactly 64K indices apart needs to be exactly the same
1177                    * 5-tuple... Anyway, since this probability is nonzero -
1178                    * print an error and drop the unlucky packet.
1179                    * If this shows up in real world, we would need to bump
1180                    * the hash key length.
1181                    */
1182                   if (PREDICT_FALSE(sess->sw_if_index != sw_if_index0)) {
1183                     clib_warning("BUG: session LSB16(sw_if_index) and 5-tuple collision!");
1184                     acl_check_needed = 0;
1185                     action = 0;
1186                   }
1187                 }
1188             }
1189
1190           if (acl_check_needed)
1191             {
1192               action =
1193                 multi_acl_match_5tuple (sw_if_index0, &fa_5tuple, is_l2_path,
1194                                        is_ip6, is_input, &match_acl_in_index,
1195                                        &match_rule_index, &trace_bitmap);
1196               error0 = action;
1197               if (1 == action)
1198                 pkts_acl_permit += 1;
1199               if (2 == action)
1200                 {
1201                   if (!acl_fa_can_add_session (am, is_input, sw_if_index0))
1202                     acl_fa_try_recycle_session (am, is_input, thread_index, sw_if_index0);
1203
1204                   if (acl_fa_can_add_session (am, is_input, sw_if_index0))
1205                     {
1206                       if (PREDICT_TRUE (valid_new_sess)) {
1207                         fa_session_t *sess = acl_fa_add_session (am, is_input,
1208                                                                  sw_if_index0,
1209                                                                  now, &kv_sess);
1210                         acl_fa_track_session (am, is_input, sw_if_index0, now,
1211                                               sess, &fa_5tuple);
1212                         pkts_new_session += 1;
1213                       } else {
1214                         /*
1215                          *  ICMP packets with non-icmp_valid_new type will be
1216                          *  forwared without being dropped.
1217                          */
1218                         action = 1;
1219                         pkts_acl_permit += 1;
1220                       }
1221                     }
1222                   else
1223                     {
1224                       action = 0;
1225                       error0 = ACL_FA_ERROR_ACL_TOO_MANY_SESSIONS;
1226                     }
1227                 }
1228             }
1229
1230
1231
1232           if (action > 0)
1233             {
1234               if (is_l2_path)
1235                 next0 = vnet_l2_feature_next (b0, l2_feat_next_node_index, 0);
1236               else
1237                 vnet_feature_next (sw_if_index0, &next0, b0);
1238             }
1239
1240           if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
1241                              && (b0->flags & VLIB_BUFFER_IS_TRACED)))
1242             {
1243               acl_fa_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
1244               t->sw_if_index = sw_if_index0;
1245               t->next_index = next0;
1246               t->match_acl_in_index = match_acl_in_index;
1247               t->match_rule_index = match_rule_index;
1248               t->packet_info[0] = fa_5tuple.kv.key[0];
1249               t->packet_info[1] = fa_5tuple.kv.key[1];
1250               t->packet_info[2] = fa_5tuple.kv.key[2];
1251               t->packet_info[3] = fa_5tuple.kv.key[3];
1252               t->packet_info[4] = fa_5tuple.kv.key[4];
1253               t->packet_info[5] = fa_5tuple.kv.value;
1254               t->action = action;
1255               t->trace_bitmap = trace_bitmap;
1256             }
1257
1258           next0 = next0 < node->n_next_nodes ? next0 : 0;
1259           if (0 == next0)
1260             b0->error = error_node->errors[error0];
1261
1262           pkts_acl_checked += 1;
1263
1264           /* verify speculative enqueue, maybe switch current next frame */
1265           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
1266                                            to_next, n_left_to_next, bi0,
1267                                            next0);
1268         }
1269
1270       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1271     }
1272
1273   vlib_node_increment_counter (vm, acl_fa_node->index,
1274                                ACL_FA_ERROR_ACL_CHECK, pkts_acl_checked);
1275   vlib_node_increment_counter (vm, acl_fa_node->index,
1276                                ACL_FA_ERROR_ACL_PERMIT, pkts_acl_permit);
1277   vlib_node_increment_counter (vm, acl_fa_node->index,
1278                                ACL_FA_ERROR_ACL_NEW_SESSION,
1279                                pkts_new_session);
1280   vlib_node_increment_counter (vm, acl_fa_node->index,
1281                                ACL_FA_ERROR_ACL_EXIST_SESSION,
1282                                pkts_exist_session);
1283   vlib_node_increment_counter (vm, acl_fa_node->index,
1284                                ACL_FA_ERROR_ACL_RESTART_SESSION_TIMER,
1285                                pkts_restart_session_timer);
1286   return frame->n_vectors;
1287 }
1288
1289
1290 vlib_node_registration_t acl_in_l2_ip6_node;
1291 static uword
1292 acl_in_ip6_l2_node_fn (vlib_main_t * vm,
1293                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1294 {
1295   acl_main_t *am = &acl_main;
1296   return acl_fa_node_fn (vm, node, frame, 1, 1, 1,
1297                          am->fa_acl_in_ip6_l2_node_feat_next_node_index,
1298                          &acl_in_l2_ip6_node);
1299 }
1300
1301 vlib_node_registration_t acl_in_l2_ip4_node;
1302 static uword
1303 acl_in_ip4_l2_node_fn (vlib_main_t * vm,
1304                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1305 {
1306   acl_main_t *am = &acl_main;
1307   return acl_fa_node_fn (vm, node, frame, 0, 1, 1,
1308                          am->fa_acl_in_ip4_l2_node_feat_next_node_index,
1309                          &acl_in_l2_ip4_node);
1310 }
1311
1312 vlib_node_registration_t acl_out_l2_ip6_node;
1313 static uword
1314 acl_out_ip6_l2_node_fn (vlib_main_t * vm,
1315                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1316 {
1317   acl_main_t *am = &acl_main;
1318   return acl_fa_node_fn (vm, node, frame, 1, 0, 1,
1319                          am->fa_acl_out_ip6_l2_node_feat_next_node_index,
1320                          &acl_out_l2_ip6_node);
1321 }
1322
1323 vlib_node_registration_t acl_out_l2_ip4_node;
1324 static uword
1325 acl_out_ip4_l2_node_fn (vlib_main_t * vm,
1326                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1327 {
1328   acl_main_t *am = &acl_main;
1329   return acl_fa_node_fn (vm, node, frame, 0, 0, 1,
1330                          am->fa_acl_out_ip4_l2_node_feat_next_node_index,
1331                          &acl_out_l2_ip4_node);
1332 }
1333
1334
1335 /**** L3 processing path nodes ****/
1336
1337
1338 vlib_node_registration_t acl_in_fa_ip6_node;
1339 static uword
1340 acl_in_ip6_fa_node_fn (vlib_main_t * vm,
1341                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1342 {
1343   return acl_fa_node_fn (vm, node, frame, 1, 1, 0, 0, &acl_in_fa_ip6_node);
1344 }
1345
1346 vlib_node_registration_t acl_in_fa_ip4_node;
1347 static uword
1348 acl_in_ip4_fa_node_fn (vlib_main_t * vm,
1349                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1350 {
1351   return acl_fa_node_fn (vm, node, frame, 0, 1, 0, 0, &acl_in_fa_ip4_node);
1352 }
1353
1354 vlib_node_registration_t acl_out_fa_ip6_node;
1355 static uword
1356 acl_out_ip6_fa_node_fn (vlib_main_t * vm,
1357                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1358 {
1359   return acl_fa_node_fn (vm, node, frame, 1, 0, 0, 0, &acl_out_fa_ip6_node);
1360 }
1361
1362 vlib_node_registration_t acl_out_fa_ip4_node;
1363 static uword
1364 acl_out_ip4_fa_node_fn (vlib_main_t * vm,
1365                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1366 {
1367   return acl_fa_node_fn (vm, node, frame, 0, 0, 0, 0, &acl_out_fa_ip4_node);
1368 }
1369
1370 /*
1371  * This process ensures the connection cleanup happens every so often
1372  * even in absence of traffic, as well as provides general orchestration
1373  * for requests like connection deletion on a given sw_if_index.
1374  */
1375
1376
1377 /* *INDENT-OFF* */
1378 #define foreach_acl_fa_cleaner_error \
1379 _(UNKNOWN_EVENT, "unknown event received")  \
1380 /* end  of errors */
1381
1382 typedef enum
1383 {
1384 #define _(sym,str) ACL_FA_CLEANER_ERROR_##sym,
1385   foreach_acl_fa_cleaner_error
1386 #undef _
1387     ACL_FA_CLEANER_N_ERROR,
1388 } acl_fa_cleaner_error_t;
1389
1390 static char *acl_fa_cleaner_error_strings[] = {
1391 #define _(sym,string) string,
1392   foreach_acl_fa_cleaner_error
1393 #undef _
1394 };
1395
1396 /* *INDENT-ON* */
1397
1398 static vlib_node_registration_t acl_fa_session_cleaner_process_node;
1399 static vlib_node_registration_t acl_fa_worker_session_cleaner_process_node;
1400
1401 /*
1402  * Per-worker thread interrupt-driven cleaner thread
1403  * to clean idle connections if there are no packets
1404  */
1405 static uword
1406 acl_fa_worker_conn_cleaner_process(vlib_main_t * vm,
1407               vlib_node_runtime_t * rt, vlib_frame_t * f)
1408 {
1409    acl_main_t *am = &acl_main;
1410    u64 now = clib_cpu_time_now ();
1411    u16 thread_index = os_get_thread_index ();
1412    acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1413    int num_expired;
1414    elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner interrupt: now %lu", "i8", now);
1415    /* allow another interrupt to be queued */
1416    pw->interrupt_is_pending = 0;
1417    if (pw->clear_in_process) {
1418      if (0 == pw->swipe_end_time) {
1419        /*
1420         * Someone has just set the flag to start clearing.
1421         * we do this by combing through the connections up to a "time T"
1422         * which is now, and requeueing everything except the expired
1423         * connections and those matching the interface(s) being cleared.
1424         */
1425
1426        /*
1427         * first filter the sw_if_index bitmap that they want from us, by
1428         * a bitmap of sw_if_index for which we actually have connections.
1429         */
1430        if ((pw->pending_clear_sw_if_index_bitmap == 0)
1431            || (pw->serviced_sw_if_index_bitmap == 0)) {
1432          elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, someone tried to call clear but one of the bitmaps are empty", "i8", now);
1433          clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1434        } else {
1435 #ifdef FA_NODE_VERBOSE_DEBUG
1436          clib_warning("WORKER-CLEAR: (before and) swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1437                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1438                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1439 #endif
1440          pw->pending_clear_sw_if_index_bitmap = clib_bitmap_and(pw->pending_clear_sw_if_index_bitmap,
1441                                                               pw->serviced_sw_if_index_bitmap);
1442        }
1443
1444        if (clib_bitmap_is_zero(pw->pending_clear_sw_if_index_bitmap)) {
1445          /* if the cross-section is a zero vector, no need to do anything. */
1446          elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, clearing done, nothing to do", "i8", now);
1447          pw->clear_in_process = 0;
1448        } else {
1449 #ifdef FA_NODE_VERBOSE_DEBUG
1450          clib_warning("WORKER-CLEAR: swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1451                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1452                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1453 #endif
1454          elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: swiping until %lu", "i8", now);
1455          /* swipe through the connection lists until enqueue timestamps become above "now" */
1456          pw->swipe_end_time = now;
1457        }
1458      }
1459    }
1460    num_expired = acl_fa_check_idle_sessions(am, thread_index, now);
1461    // clib_warning("WORKER-CLEAR: checked %d sessions (clear_in_progress: %d)", num_expired, pw->clear_in_process);
1462    elog_acl_maybe_trace_X2(am, "acl_fa_worker_conn_cleaner: checked %d sessions (clear_in_process: %d)", "i4i4", (u32)num_expired, (u32)pw->clear_in_process);
1463    if (pw->clear_in_process) {
1464      if (0 == num_expired) {
1465        /* we were clearing but we could not process any more connections. time to stop. */
1466        clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1467        pw->clear_in_process = 0;
1468        elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, clearing done - all done", "i8", now);
1469      } else {
1470        elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, more work to do - requesting interrupt", "i8", now);
1471        /* should continue clearing.. So could they please sent an interrupt again? */
1472        pw->interrupt_is_needed = 1;
1473      }
1474    } else {
1475      if (num_expired >= am->fa_max_deleted_sessions_per_interval) {
1476        /* there was too much work, we should get an interrupt ASAP */
1477        pw->interrupt_is_needed = 1;
1478        pw->interrupt_is_unwanted = 0;
1479      } else if (num_expired <= am->fa_min_deleted_sessions_per_interval) {
1480        /* signal that they should trigger us less */
1481        pw->interrupt_is_needed = 0;
1482        pw->interrupt_is_unwanted = 1;
1483      } else {
1484        /* the current rate of interrupts is ok */
1485        pw->interrupt_is_needed = 0;
1486        pw->interrupt_is_unwanted = 0;
1487      }
1488      elog_acl_maybe_trace_X3(am, "acl_fa_worker_conn_cleaner: now %lu, interrupt needed: %u, interrupt unwanted: %u", "i8i4i4", now, ((u32)pw->interrupt_is_needed), ((u32)pw->interrupt_is_unwanted));
1489    }
1490    pw->interrupt_generation = am->fa_interrupt_generation;
1491    return 0;
1492 }
1493
1494 static void
1495 send_one_worker_interrupt (vlib_main_t * vm, acl_main_t *am, int thread_index)
1496 {
1497   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1498   if (!pw->interrupt_is_pending) {
1499     pw->interrupt_is_pending = 1;
1500     vlib_node_set_interrupt_pending (vlib_mains[thread_index],
1501                   acl_fa_worker_session_cleaner_process_node.index);
1502     elog_acl_maybe_trace_X1(am, "send_one_worker_interrupt: send interrupt to worker %d", "i4", ((u32)thread_index));
1503     /* if the interrupt was requested, mark that done. */
1504     /* pw->interrupt_is_needed = 0; */
1505   }
1506 }
1507
1508 static void
1509 send_interrupts_to_workers (vlib_main_t * vm, acl_main_t *am)
1510 {
1511   int i;
1512   /* Can't use vec_len(am->per_worker_data) since the threads might not have come up yet; */
1513   int n_threads = vec_len(vlib_mains);
1514   for (i = 0; i < n_threads; i++) {
1515     send_one_worker_interrupt(vm, am, i);
1516   }
1517 }
1518
1519 /* centralized process to drive per-worker cleaners */
1520 static uword
1521 acl_fa_session_cleaner_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1522                                 vlib_frame_t * f)
1523 {
1524   acl_main_t *am = &acl_main;
1525   u64 now;
1526   f64 cpu_cps = vm->clib_time.clocks_per_second;
1527   u64 next_expire;
1528   /* We should check if there are connections to clean up - at least twice a second */
1529   u64 max_timer_wait_interval = cpu_cps / 2;
1530   uword event_type, *event_data = 0;
1531   acl_fa_per_worker_data_t *pw0;
1532
1533   am->fa_current_cleaner_timer_wait_interval = max_timer_wait_interval;
1534   am->fa_cleaner_node_index = acl_fa_session_cleaner_process_node.index;
1535   am->fa_interrupt_generation = 1;
1536   while (1)
1537     {
1538       now = clib_cpu_time_now ();
1539       next_expire = now + am->fa_current_cleaner_timer_wait_interval;
1540       int has_pending_conns = 0;
1541       u16 ti;
1542       u8 tt;
1543
1544       /*
1545        * walk over all per-thread list heads of different timeouts,
1546        * and see if there are any connections pending.
1547        * If there aren't - we do not need to wake up until the
1548        * worker code signals that it has added a connection.
1549        *
1550        * Also, while we are at it, calculate the earliest we need to wake up.
1551        */
1552       for(ti = 0; ti < vec_len(vlib_mains); ti++) {
1553         if (ti >= vec_len(am->per_worker_data)) {
1554           continue;
1555         }
1556         acl_fa_per_worker_data_t *pw = &am->per_worker_data[ti];
1557         for(tt = 0; tt < vec_len(pw->fa_conn_list_head); tt++) {
1558           u64 head_expiry = acl_fa_get_list_head_expiry_time(am, pw, now, ti, tt);
1559           if ((head_expiry < next_expire) && !pw->interrupt_is_pending) {
1560             elog_acl_maybe_trace_X3(am, "acl_fa_session_cleaner_process: now %lu, worker: %d tt: %d", "i8i2i2", now, ti, tt);
1561             elog_acl_maybe_trace_X2(am, "acl_fa_session_cleaner_process: head expiry: %lu, is earlier than curr next expire: %lu", "i8i8", head_expiry, next_expire);
1562             next_expire = head_expiry;
1563           }
1564           if (~0 != pw->fa_conn_list_head[tt]) {
1565             has_pending_conns = 1;
1566           }
1567         }
1568       }
1569
1570       /* If no pending connections and no ACL applied then no point in timing out */
1571       if (!has_pending_conns && (0 == am->fa_total_enabled_count))
1572         {
1573           am->fa_cleaner_cnt_wait_without_timeout++;
1574           elog_acl_maybe_trace_X1(am, "acl_conn_cleaner: now %lu entering wait without timeout", "i8", now);
1575           (void) vlib_process_wait_for_event (vm);
1576           event_type = vlib_process_get_events (vm, &event_data);
1577         }
1578       else
1579         {
1580           f64 timeout = ((i64) next_expire - (i64) now) / cpu_cps;
1581           if (timeout <= 0)
1582             {
1583               /* skip waiting altogether */
1584               event_type = ~0;
1585             }
1586           else
1587             {
1588               am->fa_cleaner_cnt_wait_with_timeout++;
1589               elog_acl_maybe_trace_X2(am, "acl_conn_cleaner: now %lu entering wait with timeout %.6f sec", "i8f8", now, timeout);
1590               (void) vlib_process_wait_for_event_or_clock (vm, timeout);
1591               event_type = vlib_process_get_events (vm, &event_data);
1592             }
1593         }
1594
1595       switch (event_type)
1596         {
1597         case ~0:
1598           /* nothing to do */
1599           break;
1600         case ACL_FA_CLEANER_RESCHEDULE:
1601           /* Nothing to do. */
1602           break;
1603         case ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX:
1604           {
1605             uword *clear_sw_if_index_bitmap = 0;
1606             uword *sw_if_index0;
1607             int clear_all = 0;
1608             now = clib_cpu_time_now ();
1609             elog_acl_maybe_trace_X1(am, "acl_fa_session_cleaner_process: now %lu, received ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX", "i8", now);
1610             vec_foreach (sw_if_index0, event_data)
1611             {
1612               am->fa_cleaner_cnt_delete_by_sw_index++;
1613               elog_acl_maybe_trace_X1(am, "acl_fa_session_cleaner_process: ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX %d", "i4", *sw_if_index0);
1614               if (*sw_if_index0 == ~0)
1615                 {
1616                   clear_all = 1;
1617                 }
1618               else
1619                 {
1620                   if (!pool_is_free_index (am->vnet_main->interface_main.sw_interfaces, *sw_if_index0))
1621                     {
1622                       clear_sw_if_index_bitmap = clib_bitmap_set(clear_sw_if_index_bitmap, *sw_if_index0, 1);
1623                     }
1624                 }
1625             }
1626 #ifdef FA_NODE_VERBOSE_DEBUG
1627             clib_warning("ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX bitmap: %U", format_bitmap_hex, clear_sw_if_index_bitmap);
1628 #endif
1629             vec_foreach(pw0, am->per_worker_data) {
1630               CLIB_MEMORY_BARRIER ();
1631               while (pw0->clear_in_process) {
1632                 CLIB_MEMORY_BARRIER ();
1633                 elog_acl_maybe_trace_X1(am, "ACL_FA_NODE_CLEAN: waiting previous cleaning cycle to finish on %d", "i4", (u32)(pw0 - am->per_worker_data));
1634                 vlib_process_suspend(vm, 0.0001);
1635                 if (pw0->interrupt_is_needed) {
1636                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1637                 }
1638               }
1639               if (pw0->clear_in_process) {
1640                 clib_warning("ERROR-BUG! Could not initiate cleaning on worker because another cleanup in progress");
1641               } else {
1642                 if (clear_all)
1643                   {
1644                     /* if we need to clear all, then just clear the interfaces that we are servicing */
1645                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(pw0->serviced_sw_if_index_bitmap);
1646                   }
1647                 else
1648                   {
1649                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(clear_sw_if_index_bitmap);
1650                   }
1651                 pw0->clear_in_process = 1;
1652               }
1653             }
1654             /* send some interrupts so they can start working */
1655             send_interrupts_to_workers(vm, am);
1656
1657             /* now wait till they all complete */
1658 #ifdef FA_NODE_VERBOSE_DEBUG
1659             clib_warning("CLEANER mains len: %d per-worker len: %d", vec_len(vlib_mains), vec_len(am->per_worker_data));
1660 #endif
1661             vec_foreach(pw0, am->per_worker_data) {
1662               CLIB_MEMORY_BARRIER ();
1663               while (pw0->clear_in_process) {
1664                 CLIB_MEMORY_BARRIER ();
1665                 elog_acl_maybe_trace_X1(am, "ACL_FA_NODE_CLEAN: waiting for my cleaning cycle to finish on %d", "i4", (u32)(pw0 - am->per_worker_data));
1666                 vlib_process_suspend(vm, 0.0001);
1667                 if (pw0->interrupt_is_needed) {
1668                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1669                 }
1670               }
1671             }
1672 #ifdef FA_NODE_VERBOSE_DEBUG
1673             clib_warning("ACL_FA_NODE_CLEAN: cleaning done");
1674 #endif
1675             clib_bitmap_free(clear_sw_if_index_bitmap);
1676           }
1677           break;
1678         default:
1679 #ifdef FA_NODE_VERBOSE_DEBUG
1680           clib_warning ("ACL plugin connection cleaner: unknown event %u",
1681                         event_type);
1682 #endif
1683           vlib_node_increment_counter (vm,
1684                                        acl_fa_session_cleaner_process_node.
1685                                        index,
1686                                        ACL_FA_CLEANER_ERROR_UNKNOWN_EVENT, 1);
1687           am->fa_cleaner_cnt_unknown_event++;
1688           break;
1689         }
1690
1691       send_interrupts_to_workers(vm, am);
1692
1693       if (event_data)
1694         _vec_len (event_data) = 0;
1695
1696       /*
1697        * If the interrupts were not processed yet, ensure we wait a bit,
1698        * but up to a point.
1699        */
1700       int need_more_wait = 0;
1701       int max_wait_cycles = 100;
1702       do {
1703         need_more_wait = 0;
1704         vec_foreach(pw0, am->per_worker_data) {
1705           if (pw0->interrupt_generation != am->fa_interrupt_generation) {
1706             need_more_wait = 1;
1707           }
1708         }
1709         if (need_more_wait) {
1710           vlib_process_suspend(vm, 0.0001);
1711         }
1712       } while (need_more_wait && (--max_wait_cycles > 0));
1713
1714       int interrupts_needed = 0;
1715       int interrupts_unwanted = 0;
1716
1717       vec_foreach(pw0, am->per_worker_data) {
1718         if (pw0->interrupt_is_needed) {
1719           interrupts_needed++;
1720           /* the per-worker value is reset when sending the interrupt */
1721         }
1722         if (pw0->interrupt_is_unwanted) {
1723           interrupts_unwanted++;
1724           pw0->interrupt_is_unwanted = 0;
1725         }
1726       }
1727       if (interrupts_needed) {
1728         /* they need more interrupts, do less waiting around next time */
1729         am->fa_current_cleaner_timer_wait_interval /= 2;
1730         /* never go into zero-wait either though - we need to give the space to others */
1731         am->fa_current_cleaner_timer_wait_interval += 1; 
1732       } else if (interrupts_unwanted) {
1733         /* slowly increase the amount of sleep up to a limit */
1734         if (am->fa_current_cleaner_timer_wait_interval < max_timer_wait_interval)
1735           am->fa_current_cleaner_timer_wait_interval += cpu_cps * am->fa_cleaner_wait_time_increment;
1736       }
1737       am->fa_cleaner_cnt_event_cycles++;
1738       am->fa_interrupt_generation++;
1739     }
1740   /* NOT REACHED */
1741   return 0;
1742 }
1743
1744
1745 void
1746 acl_fa_enable_disable (u32 sw_if_index, int is_input, int enable_disable)
1747 {
1748   acl_main_t *am = &acl_main;
1749   if (enable_disable) {
1750     acl_fa_verify_init_sessions(am);
1751     am->fa_total_enabled_count++;
1752     void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1753     vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1754                                  ACL_FA_CLEANER_RESCHEDULE, 0);
1755     clib_mem_set_heap (oldheap);
1756   } else {
1757     am->fa_total_enabled_count--;
1758   }
1759
1760   if (is_input)
1761     {
1762       ASSERT(clib_bitmap_get(am->fa_in_acl_on_sw_if_index, sw_if_index) != enable_disable);
1763       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1764       vnet_feature_enable_disable ("ip4-unicast", "acl-plugin-in-ip4-fa",
1765                                    sw_if_index, enable_disable, 0, 0);
1766       vnet_feature_enable_disable ("ip6-unicast", "acl-plugin-in-ip6-fa",
1767                                    sw_if_index, enable_disable, 0, 0);
1768       clib_mem_set_heap (oldheap);
1769       am->fa_in_acl_on_sw_if_index =
1770         clib_bitmap_set (am->fa_in_acl_on_sw_if_index, sw_if_index,
1771                          enable_disable);
1772     }
1773   else
1774     {
1775       ASSERT(clib_bitmap_get(am->fa_out_acl_on_sw_if_index, sw_if_index) != enable_disable);
1776       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1777       vnet_feature_enable_disable ("ip4-output", "acl-plugin-out-ip4-fa",
1778                                    sw_if_index, enable_disable, 0, 0);
1779       vnet_feature_enable_disable ("ip6-output", "acl-plugin-out-ip6-fa",
1780                                    sw_if_index, enable_disable, 0, 0);
1781       clib_mem_set_heap (oldheap);
1782       am->fa_out_acl_on_sw_if_index =
1783         clib_bitmap_set (am->fa_out_acl_on_sw_if_index, sw_if_index,
1784                          enable_disable);
1785     }
1786   if ((!enable_disable) && (!acl_fa_ifc_has_in_acl (am, sw_if_index))
1787       && (!acl_fa_ifc_has_out_acl (am, sw_if_index)))
1788     {
1789 #ifdef FA_NODE_VERBOSE_DEBUG
1790       clib_warning("ENABLE-DISABLE: clean the connections on interface %d", sw_if_index);
1791 #endif
1792       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1793       vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1794                                  ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX,
1795                                  sw_if_index);
1796       clib_mem_set_heap (oldheap);
1797     }
1798 }
1799
1800 void
1801 show_fa_sessions_hash(vlib_main_t * vm, u32 verbose)
1802 {
1803   acl_main_t *am = &acl_main;
1804   if (am->fa_sessions_hash_is_initialized) {
1805     vlib_cli_output(vm, "\nSession lookup hash table:\n%U\n\n",
1806                   BV (format_bihash), &am->fa_sessions_hash, verbose);
1807   } else {
1808     vlib_cli_output(vm, "\nSession lookup hash table is not allocated.\n\n");
1809   }
1810 }
1811
1812
1813 /* *INDENT-OFF* */
1814
1815 VLIB_REGISTER_NODE (acl_fa_worker_session_cleaner_process_node, static) = {
1816   .function = acl_fa_worker_conn_cleaner_process,
1817   .name = "acl-plugin-fa-worker-cleaner-process",
1818   .type = VLIB_NODE_TYPE_INPUT,
1819   .state = VLIB_NODE_STATE_INTERRUPT,
1820 };
1821
1822 VLIB_REGISTER_NODE (acl_fa_session_cleaner_process_node, static) = {
1823   .function = acl_fa_session_cleaner_process,
1824   .type = VLIB_NODE_TYPE_PROCESS,
1825   .name = "acl-plugin-fa-cleaner-process",
1826   .n_errors = ARRAY_LEN (acl_fa_cleaner_error_strings),
1827   .error_strings = acl_fa_cleaner_error_strings,
1828   .n_next_nodes = 0,
1829   .next_nodes = {},
1830 };
1831
1832
1833 VLIB_REGISTER_NODE (acl_in_l2_ip6_node) =
1834 {
1835   .function = acl_in_ip6_l2_node_fn,
1836   .name = "acl-plugin-in-ip6-l2",
1837   .vector_size = sizeof (u32),
1838   .format_trace = format_acl_fa_trace,
1839   .type = VLIB_NODE_TYPE_INTERNAL,
1840   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1841   .error_strings = acl_fa_error_strings,
1842   .n_next_nodes = ACL_FA_N_NEXT,
1843   .next_nodes =
1844   {
1845     [ACL_FA_ERROR_DROP] = "error-drop",
1846   }
1847 };
1848
1849 VLIB_REGISTER_NODE (acl_in_l2_ip4_node) =
1850 {
1851   .function = acl_in_ip4_l2_node_fn,
1852   .name = "acl-plugin-in-ip4-l2",
1853   .vector_size = sizeof (u32),
1854   .format_trace = format_acl_fa_trace,
1855   .type = VLIB_NODE_TYPE_INTERNAL,
1856   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1857   .error_strings = acl_fa_error_strings,
1858   .n_next_nodes = ACL_FA_N_NEXT,
1859   .next_nodes =
1860   {
1861     [ACL_FA_ERROR_DROP] = "error-drop",
1862   }
1863 };
1864
1865 VLIB_REGISTER_NODE (acl_out_l2_ip6_node) =
1866 {
1867   .function = acl_out_ip6_l2_node_fn,
1868   .name = "acl-plugin-out-ip6-l2",
1869   .vector_size = sizeof (u32),
1870   .format_trace = format_acl_fa_trace,
1871   .type = VLIB_NODE_TYPE_INTERNAL,
1872   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1873   .error_strings = acl_fa_error_strings,
1874   .n_next_nodes = ACL_FA_N_NEXT,
1875   .next_nodes =
1876   {
1877     [ACL_FA_ERROR_DROP] = "error-drop",
1878   }
1879 };
1880
1881 VLIB_REGISTER_NODE (acl_out_l2_ip4_node) =
1882 {
1883   .function = acl_out_ip4_l2_node_fn,
1884   .name = "acl-plugin-out-ip4-l2",
1885   .vector_size = sizeof (u32),
1886   .format_trace = format_acl_fa_trace,
1887   .type = VLIB_NODE_TYPE_INTERNAL,
1888   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1889   .error_strings = acl_fa_error_strings,
1890   .n_next_nodes = ACL_FA_N_NEXT,
1891   .next_nodes =
1892   {
1893     [ACL_FA_ERROR_DROP] = "error-drop",
1894   }
1895 };
1896
1897
1898 VLIB_REGISTER_NODE (acl_in_fa_ip6_node) =
1899 {
1900   .function = acl_in_ip6_fa_node_fn,
1901   .name = "acl-plugin-in-ip6-fa",
1902   .vector_size = sizeof (u32),
1903   .format_trace = format_acl_fa_trace,
1904   .type = VLIB_NODE_TYPE_INTERNAL,
1905   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1906   .error_strings = acl_fa_error_strings,
1907   .n_next_nodes = ACL_FA_N_NEXT,
1908   .next_nodes =
1909   {
1910     [ACL_FA_ERROR_DROP] = "error-drop",
1911   }
1912 };
1913
1914 VNET_FEATURE_INIT (acl_in_ip6_fa_feature, static) =
1915 {
1916   .arc_name = "ip6-unicast",
1917   .node_name = "acl-plugin-in-ip6-fa",
1918   .runs_before = VNET_FEATURES ("ip6-flow-classify"),
1919 };
1920
1921 VLIB_REGISTER_NODE (acl_in_fa_ip4_node) =
1922 {
1923   .function = acl_in_ip4_fa_node_fn,
1924   .name = "acl-plugin-in-ip4-fa",
1925   .vector_size = sizeof (u32),
1926   .format_trace = format_acl_fa_trace,
1927   .type = VLIB_NODE_TYPE_INTERNAL,
1928   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1929   .error_strings = acl_fa_error_strings,
1930   .n_next_nodes = ACL_FA_N_NEXT,
1931   .next_nodes =
1932   {
1933     [ACL_FA_ERROR_DROP] = "error-drop",
1934   }
1935 };
1936
1937 VNET_FEATURE_INIT (acl_in_ip4_fa_feature, static) =
1938 {
1939   .arc_name = "ip4-unicast",
1940   .node_name = "acl-plugin-in-ip4-fa",
1941   .runs_before = VNET_FEATURES ("ip4-flow-classify"),
1942 };
1943
1944
1945 VLIB_REGISTER_NODE (acl_out_fa_ip6_node) =
1946 {
1947   .function = acl_out_ip6_fa_node_fn,
1948   .name = "acl-plugin-out-ip6-fa",
1949   .vector_size = sizeof (u32),
1950   .format_trace = format_acl_fa_trace,
1951   .type = VLIB_NODE_TYPE_INTERNAL,
1952   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1953   .error_strings = acl_fa_error_strings,
1954   .n_next_nodes = ACL_FA_N_NEXT,
1955   .next_nodes =
1956   {
1957     [ACL_FA_ERROR_DROP] = "error-drop",
1958   }
1959 };
1960
1961 VNET_FEATURE_INIT (acl_out_ip6_fa_feature, static) =
1962 {
1963   .arc_name = "ip6-output",
1964   .node_name = "acl-plugin-out-ip6-fa",
1965   .runs_before = VNET_FEATURES ("interface-output"),
1966 };
1967
1968 VLIB_REGISTER_NODE (acl_out_fa_ip4_node) =
1969 {
1970   .function = acl_out_ip4_fa_node_fn,
1971   .name = "acl-plugin-out-ip4-fa",
1972   .vector_size = sizeof (u32),
1973   .format_trace = format_acl_fa_trace,
1974   .type = VLIB_NODE_TYPE_INTERNAL,
1975   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1976   .error_strings = acl_fa_error_strings,
1977   .n_next_nodes = ACL_FA_N_NEXT,
1978     /* edit / add dispositions here */
1979   .next_nodes =
1980   {
1981     [ACL_FA_ERROR_DROP] = "error-drop",
1982   }
1983 };
1984
1985 VNET_FEATURE_INIT (acl_out_ip4_fa_feature, static) =
1986 {
1987   .arc_name = "ip4-output",
1988   .node_name = "acl-plugin-out-ip4-fa",
1989   .runs_before = VNET_FEATURES ("interface-output"),
1990 };
1991
1992
1993 /* *INDENT-ON* */