3ac45c297ffda959e72e6a37628ae72bf23ec68f
[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         vec_add1(pw->expired, fsid.session_index);
926         acl_fa_conn_list_delete_session(am, fsid);
927       }
928     }
929   }
930
931   u32 *psid = NULL;
932   vec_foreach (psid, pw->expired)
933   {
934     fsid.session_index = *psid;
935     if (!pool_is_free_index (pw->fa_sessions_pool, fsid.session_index))
936       {
937         fa_session_t *sess = get_session_ptr(am, thread_index, fsid.session_index);
938         u32 sw_if_index = sess->sw_if_index;
939         u64 sess_timeout_time =
940           sess->last_active_time + fa_session_get_timeout (am, sess);
941         if ((now < sess_timeout_time) && (0 == clib_bitmap_get(pw->pending_clear_sw_if_index_bitmap, sw_if_index)))
942           {
943 #ifdef FA_NODE_VERBOSE_DEBUG
944             clib_warning ("ACL_FA_NODE_CLEAN: Restarting timer for session %d",
945                (int) session_index);
946 #endif
947             /* There was activity on the session, so the idle timeout
948                has not passed. Enqueue for another time period. */
949
950             acl_fa_conn_list_add_session(am, fsid, now);
951             pw->cnt_session_timer_restarted++;
952           }
953         else
954           {
955 #ifdef FA_NODE_VERBOSE_DEBUG
956             clib_warning ("ACL_FA_NODE_CLEAN: Deleting session %d",
957                (int) session_index);
958 #endif
959             acl_fa_delete_session (am, sw_if_index, fsid);
960             pw->cnt_deleted_sessions++;
961           }
962       }
963     else
964       {
965         pw->cnt_already_deleted_sessions++;
966       }
967   }
968   total_expired = vec_len(pw->expired);
969   /* zero out the vector which we have acted on */
970   if (pw->expired)
971     _vec_len (pw->expired) = 0;
972   /* if we were advancing and reached the end
973    * (no more sessions to recycle), reset the fast-forward timestamp */
974
975   if (pw->swipe_end_time && 0 == total_expired)
976     pw->swipe_end_time = 0;
977   return (total_expired);
978 }
979
980 always_inline void
981 acl_fa_try_recycle_session (acl_main_t * am, int is_input, u16 thread_index, u32 sw_if_index)
982 {
983   /* try to recycle a TCP transient session */
984   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
985   u8 timeout_type = ACL_TIMEOUT_TCP_TRANSIENT;
986   fa_full_session_id_t sess_id;
987   sess_id.session_index = pw->fa_conn_list_head[timeout_type];
988   if (~0 != sess_id.session_index) {
989     sess_id.thread_index = thread_index;
990     acl_fa_conn_list_delete_session(am, sess_id);
991     acl_fa_delete_session(am, sw_if_index, sess_id);
992   }
993 }
994
995 static fa_session_t *
996 acl_fa_add_session (acl_main_t * am, int is_input, u32 sw_if_index, u64 now,
997                     fa_5tuple_t * p5tuple)
998 {
999   clib_bihash_kv_40_8_t *pkv = &p5tuple->kv;
1000   clib_bihash_kv_40_8_t kv;
1001   fa_full_session_id_t f_sess_id;
1002   uword thread_index = os_get_thread_index();
1003   void *oldheap = clib_mem_set_heap(am->acl_mheap);
1004   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1005
1006   f_sess_id.thread_index = thread_index;
1007   fa_session_t *sess;
1008
1009   pool_get_aligned (pw->fa_sessions_pool, sess, CLIB_CACHE_LINE_BYTES);
1010   f_sess_id.session_index = sess - pw->fa_sessions_pool;
1011
1012   kv.key[0] = pkv->key[0];
1013   kv.key[1] = pkv->key[1];
1014   kv.key[2] = pkv->key[2];
1015   kv.key[3] = pkv->key[3];
1016   kv.key[4] = pkv->key[4];
1017   kv.value = f_sess_id.as_u64;
1018
1019   memcpy (sess, pkv, sizeof (pkv->key));
1020   sess->last_active_time = now;
1021   sess->sw_if_index = sw_if_index;
1022   sess->tcp_flags_seen.as_u16 = 0;
1023   sess->thread_index = thread_index;
1024   sess->link_list_id = ~0;
1025   sess->link_prev_idx = ~0;
1026   sess->link_next_idx = ~0;
1027
1028
1029
1030   ASSERT(am->fa_sessions_hash_is_initialized == 1);
1031   BV (clib_bihash_add_del) (&am->fa_sessions_hash,
1032                             &kv, 1);
1033   acl_fa_conn_list_add_session(am, f_sess_id, now);
1034
1035   vec_validate (pw->fa_session_adds_by_sw_if_index, sw_if_index);
1036   clib_mem_set_heap (oldheap);
1037   pw->fa_session_adds_by_sw_if_index[sw_if_index]++;
1038   clib_smp_atomic_add(&am->fa_session_total_adds, 1);
1039   return sess;
1040 }
1041
1042 static int
1043 acl_fa_find_session (acl_main_t * am, u32 sw_if_index0, fa_5tuple_t * p5tuple,
1044                      clib_bihash_kv_40_8_t * pvalue_sess)
1045 {
1046   return (BV (clib_bihash_search)
1047           (&am->fa_sessions_hash, &p5tuple->kv,
1048            pvalue_sess) == 0);
1049 }
1050
1051
1052 always_inline uword
1053 acl_fa_node_fn (vlib_main_t * vm,
1054                 vlib_node_runtime_t * node, vlib_frame_t * frame, int is_ip6,
1055                 int is_input, int is_l2_path, u32 * l2_feat_next_node_index,
1056                 vlib_node_registration_t * acl_fa_node)
1057 {
1058   u32 n_left_from, *from, *to_next;
1059   acl_fa_next_t next_index;
1060   u32 pkts_acl_checked = 0;
1061   u32 pkts_new_session = 0;
1062   u32 pkts_exist_session = 0;
1063   u32 pkts_acl_permit = 0;
1064   u32 pkts_restart_session_timer = 0;
1065   u32 trace_bitmap = 0;
1066   acl_main_t *am = &acl_main;
1067   fa_5tuple_t fa_5tuple, kv_sess;
1068   clib_bihash_kv_40_8_t value_sess;
1069   vlib_node_runtime_t *error_node;
1070   u64 now = clib_cpu_time_now ();
1071   uword thread_index = os_get_thread_index ();
1072
1073   from = vlib_frame_vector_args (frame);
1074   n_left_from = frame->n_vectors;
1075   next_index = node->cached_next_index;
1076
1077   error_node = vlib_node_get_runtime (vm, acl_fa_node->index);
1078
1079   while (n_left_from > 0)
1080     {
1081       u32 n_left_to_next;
1082
1083       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1084
1085       while (n_left_from > 0 && n_left_to_next > 0)
1086         {
1087           u32 bi0;
1088           vlib_buffer_t *b0;
1089           u32 next0 = 0;
1090           u8 action = 0;
1091           u32 sw_if_index0;
1092           int acl_check_needed = 1;
1093           u32 match_acl_in_index = ~0;
1094           u32 match_rule_index = ~0;
1095           u8 error0 = 0;
1096           u32 valid_new_sess;
1097
1098           /* speculatively enqueue b0 to the current next frame */
1099           bi0 = from[0];
1100           to_next[0] = bi0;
1101           from += 1;
1102           to_next += 1;
1103           n_left_from -= 1;
1104           n_left_to_next -= 1;
1105
1106           b0 = vlib_get_buffer (vm, bi0);
1107
1108           if (is_input)
1109             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
1110           else
1111             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_TX];
1112
1113           /*
1114            * Extract the L3/L4 matching info into a 5-tuple structure,
1115            * then create a session key whose layout is independent on forward or reverse
1116            * direction of the packet.
1117            */
1118
1119           acl_fill_5tuple (am, b0, is_ip6, is_input, is_l2_path, &fa_5tuple);
1120           fa_5tuple.l4.lsb_of_sw_if_index = sw_if_index0 & 0xffff;
1121           valid_new_sess = acl_make_5tuple_session_key (am, is_input, is_ip6, sw_if_index0,  &fa_5tuple, &kv_sess);
1122           fa_5tuple.pkt.sw_if_index = sw_if_index0;
1123           fa_5tuple.pkt.is_ip6 = is_ip6;
1124           fa_5tuple.pkt.is_input = is_input;
1125           fa_5tuple.pkt.mask_type_index_lsb = ~0;
1126 #ifdef FA_NODE_VERBOSE_DEBUG
1127           clib_warning
1128             ("ACL_FA_NODE_DBG: session 5-tuple %016llx %016llx %016llx %016llx %016llx : %016llx",
1129              kv_sess.kv.key[0], kv_sess.kv.key[1], kv_sess.kv.key[2],
1130              kv_sess.kv.key[3], kv_sess.kv.key[4], kv_sess.kv.value);
1131           clib_warning
1132             ("ACL_FA_NODE_DBG: packet 5-tuple %016llx %016llx %016llx %016llx %016llx : %016llx",
1133              fa_5tuple.kv.key[0], fa_5tuple.kv.key[1], fa_5tuple.kv.key[2],
1134              fa_5tuple.kv.key[3], fa_5tuple.kv.key[4], fa_5tuple.kv.value);
1135 #endif
1136
1137           /* Try to match an existing session first */
1138
1139           if (acl_fa_ifc_has_sessions (am, sw_if_index0))
1140             {
1141               if (acl_fa_find_session
1142                   (am, sw_if_index0, &kv_sess, &value_sess))
1143                 {
1144                   trace_bitmap |= 0x80000000;
1145                   error0 = ACL_FA_ERROR_ACL_EXIST_SESSION;
1146                   fa_full_session_id_t f_sess_id;
1147
1148                   f_sess_id.as_u64 = value_sess.value;
1149                   ASSERT(f_sess_id.thread_index < vec_len(vlib_mains));
1150
1151                   fa_session_t *sess = get_session_ptr(am, f_sess_id.thread_index, f_sess_id.session_index);
1152                   int old_timeout_type =
1153                     fa_session_get_timeout_type (am, sess);
1154                   action =
1155                     acl_fa_track_session (am, is_input, sw_if_index0, now,
1156                                           sess, &fa_5tuple);
1157                   /* expose the session id to the tracer */
1158                   match_rule_index = f_sess_id.session_index;
1159                   int new_timeout_type =
1160                     fa_session_get_timeout_type (am, sess);
1161                   acl_check_needed = 0;
1162                   pkts_exist_session += 1;
1163                   /* Tracking might have changed the session timeout type, e.g. from transient to established */
1164                   if (PREDICT_FALSE (old_timeout_type != new_timeout_type))
1165                     {
1166                       acl_fa_restart_timer_for_session (am, now, f_sess_id);
1167                       pkts_restart_session_timer++;
1168                       trace_bitmap |=
1169                         0x00010000 + ((0xff & old_timeout_type) << 8) +
1170                         (0xff & new_timeout_type);
1171                     }
1172                   /*
1173                    * I estimate the likelihood to be very low - the VPP needs
1174                    * to have >64K interfaces to start with and then on
1175                    * exactly 64K indices apart needs to be exactly the same
1176                    * 5-tuple... Anyway, since this probability is nonzero -
1177                    * print an error and drop the unlucky packet.
1178                    * If this shows up in real world, we would need to bump
1179                    * the hash key length.
1180                    */
1181                   if (PREDICT_FALSE(sess->sw_if_index != sw_if_index0)) {
1182                     clib_warning("BUG: session LSB16(sw_if_index) and 5-tuple collision!");
1183                     acl_check_needed = 0;
1184                     action = 0;
1185                   }
1186                 }
1187             }
1188
1189           if (acl_check_needed)
1190             {
1191               action =
1192                 multi_acl_match_5tuple (sw_if_index0, &fa_5tuple, is_l2_path,
1193                                        is_ip6, is_input, &match_acl_in_index,
1194                                        &match_rule_index, &trace_bitmap);
1195               error0 = action;
1196               if (1 == action)
1197                 pkts_acl_permit += 1;
1198               if (2 == action)
1199                 {
1200                   if (!acl_fa_can_add_session (am, is_input, sw_if_index0))
1201                     acl_fa_try_recycle_session (am, is_input, thread_index, sw_if_index0);
1202
1203                   if (acl_fa_can_add_session (am, is_input, sw_if_index0))
1204                     {
1205                       if (PREDICT_TRUE (valid_new_sess)) {
1206                         fa_session_t *sess = acl_fa_add_session (am, is_input,
1207                                                                  sw_if_index0,
1208                                                                  now, &kv_sess);
1209                         acl_fa_track_session (am, is_input, sw_if_index0, now,
1210                                               sess, &fa_5tuple);
1211                         pkts_new_session += 1;
1212                       } else {
1213                         /*
1214                          *  ICMP packets with non-icmp_valid_new type will be
1215                          *  forwared without being dropped.
1216                          */
1217                         action = 1;
1218                         pkts_acl_permit += 1;
1219                       }
1220                     }
1221                   else
1222                     {
1223                       action = 0;
1224                       error0 = ACL_FA_ERROR_ACL_TOO_MANY_SESSIONS;
1225                     }
1226                 }
1227             }
1228
1229
1230
1231           if (action > 0)
1232             {
1233               if (is_l2_path)
1234                 next0 = vnet_l2_feature_next (b0, l2_feat_next_node_index, 0);
1235               else
1236                 vnet_feature_next (sw_if_index0, &next0, b0);
1237             }
1238
1239           if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
1240                              && (b0->flags & VLIB_BUFFER_IS_TRACED)))
1241             {
1242               acl_fa_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
1243               t->sw_if_index = sw_if_index0;
1244               t->next_index = next0;
1245               t->match_acl_in_index = match_acl_in_index;
1246               t->match_rule_index = match_rule_index;
1247               t->packet_info[0] = fa_5tuple.kv.key[0];
1248               t->packet_info[1] = fa_5tuple.kv.key[1];
1249               t->packet_info[2] = fa_5tuple.kv.key[2];
1250               t->packet_info[3] = fa_5tuple.kv.key[3];
1251               t->packet_info[4] = fa_5tuple.kv.key[4];
1252               t->packet_info[5] = fa_5tuple.kv.value;
1253               t->action = action;
1254               t->trace_bitmap = trace_bitmap;
1255             }
1256
1257           next0 = next0 < node->n_next_nodes ? next0 : 0;
1258           if (0 == next0)
1259             b0->error = error_node->errors[error0];
1260
1261           pkts_acl_checked += 1;
1262
1263           /* verify speculative enqueue, maybe switch current next frame */
1264           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
1265                                            to_next, n_left_to_next, bi0,
1266                                            next0);
1267         }
1268
1269       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1270     }
1271
1272   vlib_node_increment_counter (vm, acl_fa_node->index,
1273                                ACL_FA_ERROR_ACL_CHECK, pkts_acl_checked);
1274   vlib_node_increment_counter (vm, acl_fa_node->index,
1275                                ACL_FA_ERROR_ACL_PERMIT, pkts_acl_permit);
1276   vlib_node_increment_counter (vm, acl_fa_node->index,
1277                                ACL_FA_ERROR_ACL_NEW_SESSION,
1278                                pkts_new_session);
1279   vlib_node_increment_counter (vm, acl_fa_node->index,
1280                                ACL_FA_ERROR_ACL_EXIST_SESSION,
1281                                pkts_exist_session);
1282   vlib_node_increment_counter (vm, acl_fa_node->index,
1283                                ACL_FA_ERROR_ACL_RESTART_SESSION_TIMER,
1284                                pkts_restart_session_timer);
1285   return frame->n_vectors;
1286 }
1287
1288
1289 vlib_node_registration_t acl_in_l2_ip6_node;
1290 static uword
1291 acl_in_ip6_l2_node_fn (vlib_main_t * vm,
1292                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1293 {
1294   acl_main_t *am = &acl_main;
1295   return acl_fa_node_fn (vm, node, frame, 1, 1, 1,
1296                          am->fa_acl_in_ip6_l2_node_feat_next_node_index,
1297                          &acl_in_l2_ip6_node);
1298 }
1299
1300 vlib_node_registration_t acl_in_l2_ip4_node;
1301 static uword
1302 acl_in_ip4_l2_node_fn (vlib_main_t * vm,
1303                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1304 {
1305   acl_main_t *am = &acl_main;
1306   return acl_fa_node_fn (vm, node, frame, 0, 1, 1,
1307                          am->fa_acl_in_ip4_l2_node_feat_next_node_index,
1308                          &acl_in_l2_ip4_node);
1309 }
1310
1311 vlib_node_registration_t acl_out_l2_ip6_node;
1312 static uword
1313 acl_out_ip6_l2_node_fn (vlib_main_t * vm,
1314                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1315 {
1316   acl_main_t *am = &acl_main;
1317   return acl_fa_node_fn (vm, node, frame, 1, 0, 1,
1318                          am->fa_acl_out_ip6_l2_node_feat_next_node_index,
1319                          &acl_out_l2_ip6_node);
1320 }
1321
1322 vlib_node_registration_t acl_out_l2_ip4_node;
1323 static uword
1324 acl_out_ip4_l2_node_fn (vlib_main_t * vm,
1325                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1326 {
1327   acl_main_t *am = &acl_main;
1328   return acl_fa_node_fn (vm, node, frame, 0, 0, 1,
1329                          am->fa_acl_out_ip4_l2_node_feat_next_node_index,
1330                          &acl_out_l2_ip4_node);
1331 }
1332
1333
1334 /**** L3 processing path nodes ****/
1335
1336
1337 vlib_node_registration_t acl_in_fa_ip6_node;
1338 static uword
1339 acl_in_ip6_fa_node_fn (vlib_main_t * vm,
1340                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1341 {
1342   return acl_fa_node_fn (vm, node, frame, 1, 1, 0, 0, &acl_in_fa_ip6_node);
1343 }
1344
1345 vlib_node_registration_t acl_in_fa_ip4_node;
1346 static uword
1347 acl_in_ip4_fa_node_fn (vlib_main_t * vm,
1348                        vlib_node_runtime_t * node, vlib_frame_t * frame)
1349 {
1350   return acl_fa_node_fn (vm, node, frame, 0, 1, 0, 0, &acl_in_fa_ip4_node);
1351 }
1352
1353 vlib_node_registration_t acl_out_fa_ip6_node;
1354 static uword
1355 acl_out_ip6_fa_node_fn (vlib_main_t * vm,
1356                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1357 {
1358   return acl_fa_node_fn (vm, node, frame, 1, 0, 0, 0, &acl_out_fa_ip6_node);
1359 }
1360
1361 vlib_node_registration_t acl_out_fa_ip4_node;
1362 static uword
1363 acl_out_ip4_fa_node_fn (vlib_main_t * vm,
1364                         vlib_node_runtime_t * node, vlib_frame_t * frame)
1365 {
1366   return acl_fa_node_fn (vm, node, frame, 0, 0, 0, 0, &acl_out_fa_ip4_node);
1367 }
1368
1369 /*
1370  * This process ensures the connection cleanup happens every so often
1371  * even in absence of traffic, as well as provides general orchestration
1372  * for requests like connection deletion on a given sw_if_index.
1373  */
1374
1375
1376 /* *INDENT-OFF* */
1377 #define foreach_acl_fa_cleaner_error \
1378 _(UNKNOWN_EVENT, "unknown event received")  \
1379 /* end  of errors */
1380
1381 typedef enum
1382 {
1383 #define _(sym,str) ACL_FA_CLEANER_ERROR_##sym,
1384   foreach_acl_fa_cleaner_error
1385 #undef _
1386     ACL_FA_CLEANER_N_ERROR,
1387 } acl_fa_cleaner_error_t;
1388
1389 static char *acl_fa_cleaner_error_strings[] = {
1390 #define _(sym,string) string,
1391   foreach_acl_fa_cleaner_error
1392 #undef _
1393 };
1394
1395 /* *INDENT-ON* */
1396
1397 static vlib_node_registration_t acl_fa_session_cleaner_process_node;
1398 static vlib_node_registration_t acl_fa_worker_session_cleaner_process_node;
1399
1400 /*
1401  * Per-worker thread interrupt-driven cleaner thread
1402  * to clean idle connections if there are no packets
1403  */
1404 static uword
1405 acl_fa_worker_conn_cleaner_process(vlib_main_t * vm,
1406               vlib_node_runtime_t * rt, vlib_frame_t * f)
1407 {
1408    acl_main_t *am = &acl_main;
1409    u64 now = clib_cpu_time_now ();
1410    u16 thread_index = os_get_thread_index ();
1411    acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1412    int num_expired;
1413 #ifdef FA_NODE_VERBOSE_DEBUG
1414    clib_warning("\nacl_fa_worker_conn_cleaner: thread index %d now %lu\n\n", thread_index, now);
1415 #endif
1416    /* allow another interrupt to be queued */
1417    pw->interrupt_is_pending = 0;
1418    if (pw->clear_in_process) {
1419      if (0 == pw->swipe_end_time) {
1420        /*
1421         * Someone has just set the flag to start clearing.
1422         * we do this by combing through the connections up to a "time T"
1423         * which is now, and requeueing everything except the expired
1424         * connections and those matching the interface(s) being cleared.
1425         */
1426
1427        /*
1428         * first filter the sw_if_index bitmap that they want from us, by
1429         * a bitmap of sw_if_index for which we actually have connections.
1430         */
1431        if ((pw->pending_clear_sw_if_index_bitmap == 0)
1432            || (pw->serviced_sw_if_index_bitmap == 0)) {
1433 #ifdef FA_NODE_VERBOSE_DEBUG
1434          clib_warning("WORKER-CLEAR: someone tried to call clear, but one of the bitmaps are empty");
1435 #endif
1436          clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1437        } else {
1438 #ifdef FA_NODE_VERBOSE_DEBUG
1439          clib_warning("WORKER-CLEAR: (before and) swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1440                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1441                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1442 #endif
1443          pw->pending_clear_sw_if_index_bitmap = clib_bitmap_and(pw->pending_clear_sw_if_index_bitmap,
1444                                                               pw->serviced_sw_if_index_bitmap);
1445        }
1446
1447        if (clib_bitmap_is_zero(pw->pending_clear_sw_if_index_bitmap)) {
1448          /* if the cross-section is a zero vector, no need to do anything. */
1449 #ifdef FA_NODE_VERBOSE_DEBUG
1450          clib_warning("WORKER: clearing done - nothing to do");
1451 #endif
1452          pw->clear_in_process = 0;
1453        } else {
1454 #ifdef FA_NODE_VERBOSE_DEBUG
1455          clib_warning("WORKER-CLEAR: swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1456                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1457                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1458 #endif
1459          /* swipe through the connection lists until enqueue timestamps become above "now" */
1460          pw->swipe_end_time = now;
1461        }
1462      }
1463    }
1464    num_expired = acl_fa_check_idle_sessions(am, thread_index, now);
1465    // clib_warning("WORKER-CLEAR: checked %d sessions (clear_in_progress: %d)", num_expired, pw->clear_in_process);
1466    if (pw->clear_in_process) {
1467      if (0 == num_expired) {
1468        /* we were clearing but we could not process any more connections. time to stop. */
1469        clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1470        pw->clear_in_process = 0;
1471 #ifdef FA_NODE_VERBOSE_DEBUG
1472        clib_warning("WORKER: clearing done, all done");
1473 #endif
1474      } else {
1475 #ifdef FA_NODE_VERBOSE_DEBUG
1476        clib_warning("WORKER-CLEAR: more work to do, raising interrupt");
1477 #endif
1478        /* should continue clearing.. So could they please sent an interrupt again? */
1479        pw->interrupt_is_needed = 1;
1480      }
1481    } else {
1482      if (num_expired >= am->fa_max_deleted_sessions_per_interval) {
1483        /* there was too much work, we should get an interrupt ASAP */
1484        pw->interrupt_is_needed = 1;
1485        pw->interrupt_is_unwanted = 0;
1486      } else if (num_expired <= am->fa_min_deleted_sessions_per_interval) {
1487        /* signal that they should trigger us less */
1488        pw->interrupt_is_needed = 0;
1489        pw->interrupt_is_unwanted = 1;
1490      } else {
1491        /* the current rate of interrupts is ok */
1492        pw->interrupt_is_needed = 0;
1493        pw->interrupt_is_unwanted = 0;
1494      }
1495    }
1496    pw->interrupt_generation = am->fa_interrupt_generation;
1497    return 0;
1498 }
1499
1500 static void
1501 send_one_worker_interrupt (vlib_main_t * vm, acl_main_t *am, int thread_index)
1502 {
1503   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1504   if (!pw->interrupt_is_pending) {
1505     pw->interrupt_is_pending = 1;
1506     vlib_node_set_interrupt_pending (vlib_mains[thread_index],
1507                   acl_fa_worker_session_cleaner_process_node.index);
1508     /* if the interrupt was requested, mark that done. */
1509     /* pw->interrupt_is_needed = 0; */
1510   }
1511 }
1512
1513 static void
1514 send_interrupts_to_workers (vlib_main_t * vm, acl_main_t *am)
1515 {
1516   int i;
1517   /* Can't use vec_len(am->per_worker_data) since the threads might not have come up yet; */
1518   int n_threads = vec_len(vlib_mains);
1519   for (i = 0; i < n_threads; i++) {
1520     send_one_worker_interrupt(vm, am, i);
1521   }
1522 }
1523
1524 /* centralized process to drive per-worker cleaners */
1525 static uword
1526 acl_fa_session_cleaner_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1527                                 vlib_frame_t * f)
1528 {
1529   acl_main_t *am = &acl_main;
1530   u64 now;
1531   f64 cpu_cps = vm->clib_time.clocks_per_second;
1532   u64 next_expire;
1533   /* We should check if there are connections to clean up - at least twice a second */
1534   u64 max_timer_wait_interval = cpu_cps / 2;
1535   uword event_type, *event_data = 0;
1536   acl_fa_per_worker_data_t *pw0;
1537
1538   am->fa_current_cleaner_timer_wait_interval = max_timer_wait_interval;
1539   am->fa_cleaner_node_index = acl_fa_session_cleaner_process_node.index;
1540   am->fa_interrupt_generation = 1;
1541   while (1)
1542     {
1543       now = clib_cpu_time_now ();
1544       next_expire = now + am->fa_current_cleaner_timer_wait_interval;
1545       int has_pending_conns = 0;
1546       u16 ti;
1547       u8 tt;
1548
1549       /*
1550        * walk over all per-thread list heads of different timeouts,
1551        * and see if there are any connections pending.
1552        * If there aren't - we do not need to wake up until the
1553        * worker code signals that it has added a connection.
1554        *
1555        * Also, while we are at it, calculate the earliest we need to wake up.
1556        */
1557       for(ti = 0; ti < vec_len(vlib_mains); ti++) {
1558         if (ti >= vec_len(am->per_worker_data)) {
1559           continue;
1560         }
1561         acl_fa_per_worker_data_t *pw = &am->per_worker_data[ti];
1562         for(tt = 0; tt < vec_len(pw->fa_conn_list_head); tt++) {
1563           u64 head_expiry = acl_fa_get_list_head_expiry_time(am, pw, now, ti, tt);
1564           if ((head_expiry < next_expire) && !pw->interrupt_is_pending) {
1565 #ifdef FA_NODE_VERBOSE_DEBUG
1566             clib_warning("Head expiry: %lu, now: %lu, next_expire: %lu (worker: %d, tt: %d)", head_expiry, now, next_expire, ti, tt);
1567 #endif
1568             next_expire = head_expiry;
1569           }
1570           if (~0 != pw->fa_conn_list_head[tt]) {
1571             has_pending_conns = 1;
1572           }
1573         }
1574       }
1575
1576       /* If no pending connections and no ACL applied then no point in timing out */
1577       if (!has_pending_conns && (0 == am->fa_total_enabled_count))
1578         {
1579           am->fa_cleaner_cnt_wait_without_timeout++;
1580           (void) vlib_process_wait_for_event (vm);
1581           event_type = vlib_process_get_events (vm, &event_data);
1582         }
1583       else
1584         {
1585           f64 timeout = ((i64) next_expire - (i64) now) / cpu_cps;
1586           if (timeout <= 0)
1587             {
1588               /* skip waiting altogether */
1589               event_type = ~0;
1590             }
1591           else
1592             {
1593               am->fa_cleaner_cnt_wait_with_timeout++;
1594               (void) vlib_process_wait_for_event_or_clock (vm, timeout);
1595               event_type = vlib_process_get_events (vm, &event_data);
1596             }
1597         }
1598
1599       switch (event_type)
1600         {
1601         case ~0:
1602           /* nothing to do */
1603           break;
1604         case ACL_FA_CLEANER_RESCHEDULE:
1605           /* Nothing to do. */
1606           break;
1607         case ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX:
1608           {
1609             uword *clear_sw_if_index_bitmap = 0;
1610             uword *sw_if_index0;
1611             int clear_all = 0;
1612 #ifdef FA_NODE_VERBOSE_DEBUG
1613             clib_warning("ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX received");
1614 #endif
1615             vec_foreach (sw_if_index0, event_data)
1616             {
1617               am->fa_cleaner_cnt_delete_by_sw_index++;
1618 #ifdef FA_NODE_VERBOSE_DEBUG
1619               clib_warning
1620                 ("ACL_FA_NODE_CLEAN: ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX: %d",
1621                  *sw_if_index0);
1622 #endif
1623               if (*sw_if_index0 == ~0)
1624                 {
1625                   clear_all = 1;
1626                 }
1627               else
1628                 {
1629                   if (!pool_is_free_index (am->vnet_main->interface_main.sw_interfaces, *sw_if_index0))
1630                     {
1631                       clear_sw_if_index_bitmap = clib_bitmap_set(clear_sw_if_index_bitmap, *sw_if_index0, 1);
1632                     }
1633                 }
1634             }
1635 #ifdef FA_NODE_VERBOSE_DEBUG
1636             clib_warning("ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX bitmap: %U", format_bitmap_hex, clear_sw_if_index_bitmap);
1637 #endif
1638             vec_foreach(pw0, am->per_worker_data) {
1639               CLIB_MEMORY_BARRIER ();
1640               while (pw0->clear_in_process) {
1641                 CLIB_MEMORY_BARRIER ();
1642 #ifdef FA_NODE_VERBOSE_DEBUG
1643                 clib_warning("ACL_FA_NODE_CLEAN: waiting previous cleaning cycle to finish on %d...", pw0 - am->per_worker_data);
1644 #endif
1645                 vlib_process_suspend(vm, 0.0001);
1646                 if (pw0->interrupt_is_needed) {
1647                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1648                 }
1649               }
1650               if (pw0->clear_in_process) {
1651                 clib_warning("ERROR-BUG! Could not initiate cleaning on worker because another cleanup in progress");
1652               } else {
1653                 if (clear_all)
1654                   {
1655                     /* if we need to clear all, then just clear the interfaces that we are servicing */
1656                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(pw0->serviced_sw_if_index_bitmap);
1657                   }
1658                 else
1659                   {
1660                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(clear_sw_if_index_bitmap);
1661                   }
1662                 pw0->clear_in_process = 1;
1663               }
1664             }
1665             /* send some interrupts so they can start working */
1666             send_interrupts_to_workers(vm, am);
1667
1668             /* now wait till they all complete */
1669 #ifdef FA_NODE_VERBOSE_DEBUG
1670             clib_warning("CLEANER mains len: %d per-worker len: %d", vec_len(vlib_mains), vec_len(am->per_worker_data));
1671 #endif
1672             vec_foreach(pw0, am->per_worker_data) {
1673               CLIB_MEMORY_BARRIER ();
1674               while (pw0->clear_in_process) {
1675                 CLIB_MEMORY_BARRIER ();
1676 #ifdef FA_NODE_VERBOSE_DEBUG
1677                 clib_warning("ACL_FA_NODE_CLEAN: waiting for my cleaning cycle to finish on %d...", pw0 - am->per_worker_data);
1678 #endif
1679                 vlib_process_suspend(vm, 0.0001);
1680                 if (pw0->interrupt_is_needed) {
1681                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1682                 }
1683               }
1684             }
1685 #ifdef FA_NODE_VERBOSE_DEBUG
1686             clib_warning("ACL_FA_NODE_CLEAN: cleaning done");
1687 #endif
1688             clib_bitmap_free(clear_sw_if_index_bitmap);
1689           }
1690           break;
1691         default:
1692 #ifdef FA_NODE_VERBOSE_DEBUG
1693           clib_warning ("ACL plugin connection cleaner: unknown event %u",
1694                         event_type);
1695 #endif
1696           vlib_node_increment_counter (vm,
1697                                        acl_fa_session_cleaner_process_node.
1698                                        index,
1699                                        ACL_FA_CLEANER_ERROR_UNKNOWN_EVENT, 1);
1700           am->fa_cleaner_cnt_unknown_event++;
1701           break;
1702         }
1703
1704       send_interrupts_to_workers(vm, am);
1705
1706       if (event_data)
1707         _vec_len (event_data) = 0;
1708
1709       /*
1710        * If the interrupts were not processed yet, ensure we wait a bit,
1711        * but up to a point.
1712        */
1713       int need_more_wait = 0;
1714       int max_wait_cycles = 100;
1715       do {
1716         need_more_wait = 0;
1717         vec_foreach(pw0, am->per_worker_data) {
1718           if (pw0->interrupt_generation != am->fa_interrupt_generation) {
1719             need_more_wait = 1;
1720           }
1721         }
1722         if (need_more_wait) {
1723           vlib_process_suspend(vm, 0.0001);
1724         }
1725       } while (need_more_wait && (--max_wait_cycles > 0));
1726
1727       int interrupts_needed = 0;
1728       int interrupts_unwanted = 0;
1729
1730       vec_foreach(pw0, am->per_worker_data) {
1731         if (pw0->interrupt_is_needed) {
1732           interrupts_needed++;
1733           /* the per-worker value is reset when sending the interrupt */
1734         }
1735         if (pw0->interrupt_is_unwanted) {
1736           interrupts_unwanted++;
1737           pw0->interrupt_is_unwanted = 0;
1738         }
1739       }
1740       if (interrupts_needed) {
1741         /* they need more interrupts, do less waiting around next time */
1742         am->fa_current_cleaner_timer_wait_interval /= 2;
1743         /* never go into zero-wait either though - we need to give the space to others */
1744         am->fa_current_cleaner_timer_wait_interval += 1; 
1745       } else if (interrupts_unwanted) {
1746         /* slowly increase the amount of sleep up to a limit */
1747         if (am->fa_current_cleaner_timer_wait_interval < max_timer_wait_interval)
1748           am->fa_current_cleaner_timer_wait_interval += cpu_cps * am->fa_cleaner_wait_time_increment;
1749       }
1750       am->fa_cleaner_cnt_event_cycles++;
1751       am->fa_interrupt_generation++;
1752     }
1753   /* NOT REACHED */
1754   return 0;
1755 }
1756
1757
1758 void
1759 acl_fa_enable_disable (u32 sw_if_index, int is_input, int enable_disable)
1760 {
1761   acl_main_t *am = &acl_main;
1762   if (enable_disable) {
1763     acl_fa_verify_init_sessions(am);
1764     am->fa_total_enabled_count++;
1765     void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1766     vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1767                                  ACL_FA_CLEANER_RESCHEDULE, 0);
1768     clib_mem_set_heap (oldheap);
1769   } else {
1770     am->fa_total_enabled_count--;
1771   }
1772
1773   if (is_input)
1774     {
1775       ASSERT(clib_bitmap_get(am->fa_in_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-unicast", "acl-plugin-in-ip4-fa",
1778                                    sw_if_index, enable_disable, 0, 0);
1779       vnet_feature_enable_disable ("ip6-unicast", "acl-plugin-in-ip6-fa",
1780                                    sw_if_index, enable_disable, 0, 0);
1781       clib_mem_set_heap (oldheap);
1782       am->fa_in_acl_on_sw_if_index =
1783         clib_bitmap_set (am->fa_in_acl_on_sw_if_index, sw_if_index,
1784                          enable_disable);
1785     }
1786   else
1787     {
1788       ASSERT(clib_bitmap_get(am->fa_out_acl_on_sw_if_index, sw_if_index) != enable_disable);
1789       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1790       vnet_feature_enable_disable ("ip4-output", "acl-plugin-out-ip4-fa",
1791                                    sw_if_index, enable_disable, 0, 0);
1792       vnet_feature_enable_disable ("ip6-output", "acl-plugin-out-ip6-fa",
1793                                    sw_if_index, enable_disable, 0, 0);
1794       clib_mem_set_heap (oldheap);
1795       am->fa_out_acl_on_sw_if_index =
1796         clib_bitmap_set (am->fa_out_acl_on_sw_if_index, sw_if_index,
1797                          enable_disable);
1798     }
1799   if ((!enable_disable) && (!acl_fa_ifc_has_in_acl (am, sw_if_index))
1800       && (!acl_fa_ifc_has_out_acl (am, sw_if_index)))
1801     {
1802 #ifdef FA_NODE_VERBOSE_DEBUG
1803       clib_warning("ENABLE-DISABLE: clean the connections on interface %d", sw_if_index);
1804 #endif
1805       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1806       vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1807                                  ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX,
1808                                  sw_if_index);
1809       clib_mem_set_heap (oldheap);
1810     }
1811 }
1812
1813 void
1814 show_fa_sessions_hash(vlib_main_t * vm, u32 verbose)
1815 {
1816   acl_main_t *am = &acl_main;
1817   if (am->fa_sessions_hash_is_initialized) {
1818     vlib_cli_output(vm, "\nSession lookup hash table:\n%U\n\n",
1819                   BV (format_bihash), &am->fa_sessions_hash, verbose);
1820   } else {
1821     vlib_cli_output(vm, "\nSession lookup hash table is not allocated.\n\n");
1822   }
1823 }
1824
1825
1826 /* *INDENT-OFF* */
1827
1828 VLIB_REGISTER_NODE (acl_fa_worker_session_cleaner_process_node, static) = {
1829   .function = acl_fa_worker_conn_cleaner_process,
1830   .name = "acl-plugin-fa-worker-cleaner-process",
1831   .type = VLIB_NODE_TYPE_INPUT,
1832   .state = VLIB_NODE_STATE_INTERRUPT,
1833 };
1834
1835 VLIB_REGISTER_NODE (acl_fa_session_cleaner_process_node, static) = {
1836   .function = acl_fa_session_cleaner_process,
1837   .type = VLIB_NODE_TYPE_PROCESS,
1838   .name = "acl-plugin-fa-cleaner-process",
1839   .n_errors = ARRAY_LEN (acl_fa_cleaner_error_strings),
1840   .error_strings = acl_fa_cleaner_error_strings,
1841   .n_next_nodes = 0,
1842   .next_nodes = {},
1843 };
1844
1845
1846 VLIB_REGISTER_NODE (acl_in_l2_ip6_node) =
1847 {
1848   .function = acl_in_ip6_l2_node_fn,
1849   .name = "acl-plugin-in-ip6-l2",
1850   .vector_size = sizeof (u32),
1851   .format_trace = format_acl_fa_trace,
1852   .type = VLIB_NODE_TYPE_INTERNAL,
1853   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1854   .error_strings = acl_fa_error_strings,
1855   .n_next_nodes = ACL_FA_N_NEXT,
1856   .next_nodes =
1857   {
1858     [ACL_FA_ERROR_DROP] = "error-drop",
1859   }
1860 };
1861
1862 VLIB_REGISTER_NODE (acl_in_l2_ip4_node) =
1863 {
1864   .function = acl_in_ip4_l2_node_fn,
1865   .name = "acl-plugin-in-ip4-l2",
1866   .vector_size = sizeof (u32),
1867   .format_trace = format_acl_fa_trace,
1868   .type = VLIB_NODE_TYPE_INTERNAL,
1869   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1870   .error_strings = acl_fa_error_strings,
1871   .n_next_nodes = ACL_FA_N_NEXT,
1872   .next_nodes =
1873   {
1874     [ACL_FA_ERROR_DROP] = "error-drop",
1875   }
1876 };
1877
1878 VLIB_REGISTER_NODE (acl_out_l2_ip6_node) =
1879 {
1880   .function = acl_out_ip6_l2_node_fn,
1881   .name = "acl-plugin-out-ip6-l2",
1882   .vector_size = sizeof (u32),
1883   .format_trace = format_acl_fa_trace,
1884   .type = VLIB_NODE_TYPE_INTERNAL,
1885   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1886   .error_strings = acl_fa_error_strings,
1887   .n_next_nodes = ACL_FA_N_NEXT,
1888   .next_nodes =
1889   {
1890     [ACL_FA_ERROR_DROP] = "error-drop",
1891   }
1892 };
1893
1894 VLIB_REGISTER_NODE (acl_out_l2_ip4_node) =
1895 {
1896   .function = acl_out_ip4_l2_node_fn,
1897   .name = "acl-plugin-out-ip4-l2",
1898   .vector_size = sizeof (u32),
1899   .format_trace = format_acl_fa_trace,
1900   .type = VLIB_NODE_TYPE_INTERNAL,
1901   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1902   .error_strings = acl_fa_error_strings,
1903   .n_next_nodes = ACL_FA_N_NEXT,
1904   .next_nodes =
1905   {
1906     [ACL_FA_ERROR_DROP] = "error-drop",
1907   }
1908 };
1909
1910
1911 VLIB_REGISTER_NODE (acl_in_fa_ip6_node) =
1912 {
1913   .function = acl_in_ip6_fa_node_fn,
1914   .name = "acl-plugin-in-ip6-fa",
1915   .vector_size = sizeof (u32),
1916   .format_trace = format_acl_fa_trace,
1917   .type = VLIB_NODE_TYPE_INTERNAL,
1918   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1919   .error_strings = acl_fa_error_strings,
1920   .n_next_nodes = ACL_FA_N_NEXT,
1921   .next_nodes =
1922   {
1923     [ACL_FA_ERROR_DROP] = "error-drop",
1924   }
1925 };
1926
1927 VNET_FEATURE_INIT (acl_in_ip6_fa_feature, static) =
1928 {
1929   .arc_name = "ip6-unicast",
1930   .node_name = "acl-plugin-in-ip6-fa",
1931   .runs_before = VNET_FEATURES ("ip6-flow-classify"),
1932 };
1933
1934 VLIB_REGISTER_NODE (acl_in_fa_ip4_node) =
1935 {
1936   .function = acl_in_ip4_fa_node_fn,
1937   .name = "acl-plugin-in-ip4-fa",
1938   .vector_size = sizeof (u32),
1939   .format_trace = format_acl_fa_trace,
1940   .type = VLIB_NODE_TYPE_INTERNAL,
1941   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1942   .error_strings = acl_fa_error_strings,
1943   .n_next_nodes = ACL_FA_N_NEXT,
1944   .next_nodes =
1945   {
1946     [ACL_FA_ERROR_DROP] = "error-drop",
1947   }
1948 };
1949
1950 VNET_FEATURE_INIT (acl_in_ip4_fa_feature, static) =
1951 {
1952   .arc_name = "ip4-unicast",
1953   .node_name = "acl-plugin-in-ip4-fa",
1954   .runs_before = VNET_FEATURES ("ip4-flow-classify"),
1955 };
1956
1957
1958 VLIB_REGISTER_NODE (acl_out_fa_ip6_node) =
1959 {
1960   .function = acl_out_ip6_fa_node_fn,
1961   .name = "acl-plugin-out-ip6-fa",
1962   .vector_size = sizeof (u32),
1963   .format_trace = format_acl_fa_trace,
1964   .type = VLIB_NODE_TYPE_INTERNAL,
1965   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1966   .error_strings = acl_fa_error_strings,
1967   .n_next_nodes = ACL_FA_N_NEXT,
1968   .next_nodes =
1969   {
1970     [ACL_FA_ERROR_DROP] = "error-drop",
1971   }
1972 };
1973
1974 VNET_FEATURE_INIT (acl_out_ip6_fa_feature, static) =
1975 {
1976   .arc_name = "ip6-output",
1977   .node_name = "acl-plugin-out-ip6-fa",
1978   .runs_before = VNET_FEATURES ("interface-output"),
1979 };
1980
1981 VLIB_REGISTER_NODE (acl_out_fa_ip4_node) =
1982 {
1983   .function = acl_out_ip4_fa_node_fn,
1984   .name = "acl-plugin-out-ip4-fa",
1985   .vector_size = sizeof (u32),
1986   .format_trace = format_acl_fa_trace,
1987   .type = VLIB_NODE_TYPE_INTERNAL,
1988   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1989   .error_strings = acl_fa_error_strings,
1990   .n_next_nodes = ACL_FA_N_NEXT,
1991     /* edit / add dispositions here */
1992   .next_nodes =
1993   {
1994     [ACL_FA_ERROR_DROP] = "error-drop",
1995   }
1996 };
1997
1998 VNET_FEATURE_INIT (acl_out_ip4_fa_feature, static) =
1999 {
2000   .arc_name = "ip4-output",
2001   .node_name = "acl-plugin-out-ip4-fa",
2002   .runs_before = VNET_FEATURES ("interface-output"),
2003 };
2004
2005
2006 /* *INDENT-ON* */