acl-plugin: implement ACL lookup contexts for "ACL as a service" use by other plugins
[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
23
24 #include <acl/acl.h>
25 #include <vnet/ip/icmp46_packet.h>
26
27 #include <plugins/acl/fa_node.h>
28 #include <plugins/acl/acl.h>
29 #include <plugins/acl/lookup_context.h>
30 #include <plugins/acl/public_inlines.h>
31
32 #include <vppinfra/bihash_40_8.h>
33 #include <vppinfra/bihash_template.h>
34 #include <vppinfra/bihash_template.c>
35
36 typedef struct
37 {
38   u32 next_index;
39   u32 sw_if_index;
40   u32 lc_index;
41   u32 match_acl_in_index;
42   u32 match_rule_index;
43   u64 packet_info[6];
44   u32 trace_bitmap;
45   u8 action;
46 } acl_fa_trace_t;
47
48 /* ICMPv4 invert type for stateful ACL */
49 static const u8 icmp4_invmap[] = {
50   [ICMP4_echo_reply] = ICMP4_echo_request + 1,
51   [ICMP4_timestamp_reply] = ICMP4_timestamp_request + 1,
52   [ICMP4_information_reply] = ICMP4_information_request + 1,
53   [ICMP4_address_mask_reply] = ICMP4_address_mask_request + 1
54 };
55
56 /* Supported ICMPv4 messages for session creation */
57 static const u8 icmp4_valid_new[] = {
58   [ICMP4_echo_request] = 1,
59   [ICMP4_timestamp_request] = 1,
60   [ICMP4_information_request] = 1,
61   [ICMP4_address_mask_request] = 1
62 };
63
64 /* ICMPv6 invert type for stateful ACL */
65 static const u8 icmp6_invmap[] = {
66   [ICMP6_echo_reply - 128]   = ICMP6_echo_request + 1,
67   [ICMP6_node_information_response - 128] = ICMP6_node_information_request + 1
68 };
69
70 /* Supported ICMPv6 messages for session creation */
71 static const u8 icmp6_valid_new[] = {
72   [ICMP6_echo_request - 128] = 1,
73   [ICMP6_node_information_request - 128] = 1
74 };
75
76 /* IP4 and IP6 protocol numbers of ICMP */
77 static u8 icmp_protos[] = { IP_PROTOCOL_ICMP, IP_PROTOCOL_ICMP6 };
78
79 static u8 *
80 format_fa_5tuple (u8 * s, va_list * args)
81 {
82   fa_5tuple_t *p5t = va_arg (*args, fa_5tuple_t *);
83
84   return format(s, "lc_index %d (lsb16 of sw_if_index %d) l3 %s%s %U -> %U"
85                    " l4 proto %d l4_valid %d port %d -> %d tcp flags (%s) %02x rsvd %x",
86                 p5t->pkt.lc_index, p5t->l4.lsb_of_sw_if_index, p5t->pkt.is_ip6 ? "ip6" : "ip4",
87                 p5t->pkt.is_nonfirst_fragment ? " non-initial fragment" : "",
88                 format_ip46_address, &p5t->addr[0], p5t->pkt.is_ip6 ? IP46_TYPE_IP6 : IP46_TYPE_IP4,
89                 format_ip46_address, &p5t->addr[1], p5t->pkt.is_ip6 ? IP46_TYPE_IP6 : IP46_TYPE_IP4,
90                 p5t->l4.proto, p5t->pkt.l4_valid,
91                 p5t->l4.port[0], p5t->l4.port[1],
92                 p5t->pkt.tcp_flags_valid ? "valid": "invalid",
93                 p5t->pkt.tcp_flags,
94                 p5t->pkt.flags_reserved);
95 }
96
97 u8 *
98 format_acl_plugin_5tuple (u8 * s, va_list * args)
99 {
100   return format_fa_5tuple(s, args);
101 }
102
103 /* packet trace format function */
104 static u8 *
105 format_acl_fa_trace (u8 * s, va_list * args)
106 {
107   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
108   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
109   acl_fa_trace_t *t = va_arg (*args, acl_fa_trace_t *);
110
111   s =
112     format (s,
113             "acl-plugin: lc_index: %d, sw_if_index %d, next index %d, action: %d, match: acl %d rule %d trace_bits %08x\n"
114             "  pkt info %016llx %016llx %016llx %016llx %016llx %016llx",
115             t->lc_index, t->sw_if_index, t->next_index, t->action, t->match_acl_in_index,
116             t->match_rule_index, t->trace_bitmap,
117             t->packet_info[0], t->packet_info[1], t->packet_info[2],
118             t->packet_info[3], t->packet_info[4], t->packet_info[5]);
119
120   /* Now also print out the packet_info in a form usable by humans */
121   s = format (s, "\n   %U", format_fa_5tuple, t->packet_info);
122   return s;
123 }
124
125 /* *INDENT-OFF* */
126 #define foreach_acl_fa_error \
127 _(ACL_DROP, "ACL deny packets")  \
128 _(ACL_PERMIT, "ACL permit packets")  \
129 _(ACL_NEW_SESSION, "new sessions added") \
130 _(ACL_EXIST_SESSION, "existing session packets") \
131 _(ACL_CHECK, "checked packets") \
132 _(ACL_RESTART_SESSION_TIMER, "restart session timer") \
133 _(ACL_TOO_MANY_SESSIONS, "too many sessions to add new") \
134 /* end  of errors */
135
136 typedef enum
137 {
138 #define _(sym,str) ACL_FA_ERROR_##sym,
139   foreach_acl_fa_error
140 #undef _
141     ACL_FA_N_ERROR,
142 } acl_fa_error_t;
143
144 static char *acl_fa_error_strings[] = {
145 #define _(sym,string) string,
146   foreach_acl_fa_error
147 #undef _
148 };
149 /* *INDENT-ON* */
150
151 static int
152 acl_fa_ifc_has_sessions (acl_main_t * am, int sw_if_index0)
153 {
154   return am->fa_sessions_hash_is_initialized;
155 }
156
157 static int
158 acl_fa_ifc_has_in_acl (acl_main_t * am, int sw_if_index0)
159 {
160   int it_has = clib_bitmap_get (am->fa_in_acl_on_sw_if_index, sw_if_index0);
161   return it_has;
162 }
163
164 static int
165 acl_fa_ifc_has_out_acl (acl_main_t * am, int sw_if_index0)
166 {
167   int it_has = clib_bitmap_get (am->fa_out_acl_on_sw_if_index, sw_if_index0);
168   return it_has;
169 }
170
171 /* Session keys match the packets received, and mirror the packets sent */
172 static u32
173 acl_make_5tuple_session_key (acl_main_t * am, int is_input, int is_ip6,
174                              u32 sw_if_index, fa_5tuple_t * p5tuple_pkt,
175                              fa_5tuple_t * p5tuple_sess)
176 {
177   int src_index = is_input ? 0 : 1;
178   int dst_index = is_input ? 1 : 0;
179   u32 valid_new_sess = 1;
180   p5tuple_sess->addr[src_index] = p5tuple_pkt->addr[0];
181   p5tuple_sess->addr[dst_index] = p5tuple_pkt->addr[1];
182   p5tuple_sess->l4.as_u64 = p5tuple_pkt->l4.as_u64;
183
184   if (PREDICT_TRUE(p5tuple_pkt->l4.proto != icmp_protos[is_ip6]))
185     {
186       p5tuple_sess->l4.port[src_index] = p5tuple_pkt->l4.port[0];
187       p5tuple_sess->l4.port[dst_index] = p5tuple_pkt->l4.port[1];
188     }
189   else
190     {
191       static const u8 * icmp_invmap[] = { icmp4_invmap, icmp6_invmap };
192       static const u8 * icmp_valid_new[] = { icmp4_valid_new, icmp6_valid_new };
193       static const u8 icmp_invmap_size[] = { sizeof(icmp4_invmap),
194                                              sizeof(icmp6_invmap) };
195       static const u8 icmp_valid_new_size[] = { sizeof(icmp4_valid_new),
196                                                 sizeof(icmp6_valid_new) };
197       int type = is_ip6 ? p5tuple_pkt->l4.port[0]-128: p5tuple_pkt->l4.port[0];
198
199       p5tuple_sess->l4.port[0] = p5tuple_pkt->l4.port[0];
200       p5tuple_sess->l4.port[1] = p5tuple_pkt->l4.port[1];
201
202       /*
203        * Invert ICMP type for valid icmp_invmap messages:
204        *  1) input node with outbound ACL interface
205        *  2) output node with inbound ACL interface
206        *
207        */
208       if ((is_input && acl_fa_ifc_has_out_acl(am, sw_if_index)) ||
209           (!is_input && acl_fa_ifc_has_in_acl(am, sw_if_index)))
210         {
211           if (type >= 0 &&
212               type <= icmp_invmap_size[is_ip6] &&
213               icmp_invmap[is_ip6][type])
214             {
215               p5tuple_sess->l4.port[0] = icmp_invmap[is_ip6][type] - 1;
216             }
217         }
218
219       /*
220        * ONLY ICMP messages defined in icmp4_valid_new/icmp6_valid_new table
221        * are allowed to create stateful ACL.
222        * The other messages will be forwarded without creating a reflexive ACL.
223        */
224       if (type < 0 ||
225           type > icmp_valid_new_size[is_ip6] ||
226           !icmp_valid_new[is_ip6][type])
227         {
228           valid_new_sess = 0;
229         }
230     }
231
232     return valid_new_sess;
233 }
234
235
236 static int
237 fa_session_get_timeout_type (acl_main_t * am, fa_session_t * sess)
238 {
239   /* seen both SYNs and ACKs but not FINs means we are in establshed state */
240   u16 masked_flags =
241     sess->tcp_flags_seen.as_u16 & ((TCP_FLAGS_RSTFINACKSYN << 8) +
242                                    TCP_FLAGS_RSTFINACKSYN);
243   switch (sess->info.l4.proto)
244     {
245     case IPPROTO_TCP:
246       if (((TCP_FLAGS_ACKSYN << 8) + TCP_FLAGS_ACKSYN) == masked_flags)
247         {
248           return ACL_TIMEOUT_TCP_IDLE;
249         }
250       else
251         {
252           return ACL_TIMEOUT_TCP_TRANSIENT;
253         }
254       break;
255     case IPPROTO_UDP:
256       return ACL_TIMEOUT_UDP_IDLE;
257       break;
258     default:
259       return ACL_TIMEOUT_UDP_IDLE;
260     }
261 }
262
263
264 static u64
265 fa_session_get_shortest_timeout(acl_main_t * am)
266 {
267   int timeout_type;
268   u64 timeout = ~0LL;
269   for(timeout_type = 0; timeout_type < ACL_N_TIMEOUTS; timeout_type++) {
270     if (timeout > am->session_timeout_sec[timeout_type]) {
271       timeout = am->session_timeout_sec[timeout_type];
272     }
273   }
274   return timeout;
275 }
276
277 /*
278  * Get the timeout of the session in a list since its enqueue time.
279  */
280
281 static u64
282 fa_session_get_list_timeout (acl_main_t * am, fa_session_t * sess)
283 {
284   u64 timeout = am->vlib_main->clib_time.clocks_per_second;
285   /*
286    * we have the shortest possible timeout type in all the lists
287    * (see README-multicore for the rationale)
288    */
289   timeout *= fa_session_get_shortest_timeout(am);
290   return timeout;
291 }
292
293 /*
294  * Get the idle timeout of a session.
295  */
296
297 static u64
298 fa_session_get_timeout (acl_main_t * am, fa_session_t * sess)
299 {
300   u64 timeout = am->vlib_main->clib_time.clocks_per_second;
301   int timeout_type = fa_session_get_timeout_type (am, sess);
302   timeout *= am->session_timeout_sec[timeout_type];
303   return timeout;
304 }
305
306 static void
307 acl_fa_verify_init_sessions (acl_main_t * am)
308 {
309   if (!am->fa_sessions_hash_is_initialized) {
310     u16 wk;
311     /* Allocate the per-worker sessions pools */
312     for (wk = 0; wk < vec_len (am->per_worker_data); wk++) {
313       acl_fa_per_worker_data_t *pw = &am->per_worker_data[wk];
314
315       /*
316       * // In lieu of trying to preallocate the pool and its free bitmap, rather use pool_init_fixed
317       * pool_alloc_aligned(pw->fa_sessions_pool, am->fa_conn_table_max_entries, CLIB_CACHE_LINE_BYTES);
318       * clib_bitmap_validate(pool_header(pw->fa_sessions_pool)->free_bitmap, am->fa_conn_table_max_entries);
319       */
320       pool_init_fixed(pw->fa_sessions_pool, am->fa_conn_table_max_entries);
321     }
322
323     /* ... and the interface session hash table */
324     BV (clib_bihash_init) (&am->fa_sessions_hash,
325                          "ACL plugin FA session bihash",
326                          am->fa_conn_table_hash_num_buckets,
327                          am->fa_conn_table_hash_memory_size);
328     am->fa_sessions_hash_is_initialized = 1;
329   }
330 }
331
332 static inline fa_session_t *get_session_ptr(acl_main_t *am, u16 thread_index, u32 session_index)
333 {
334   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
335   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);
336   return sess;
337 }
338
339 static inline int is_valid_session_ptr(acl_main_t *am, u16 thread_index, fa_session_t *sess)
340 {
341   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
342   return ((sess != 0) && ((sess - pw->fa_sessions_pool) < pool_len(pw->fa_sessions_pool)));
343 }
344
345 static void
346 acl_fa_conn_list_add_session (acl_main_t * am, fa_full_session_id_t sess_id, u64 now)
347 {
348   fa_session_t *sess = get_session_ptr(am, sess_id.thread_index, sess_id.session_index);
349   u8 list_id = fa_session_get_timeout_type(am, sess);
350   uword thread_index = os_get_thread_index ();
351   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
352   /* the retrieved session thread index must be necessarily the same as the one in the key */
353   ASSERT (sess->thread_index == sess_id.thread_index);
354   /* the retrieved session thread index must be the same as current thread */
355   ASSERT (sess->thread_index == thread_index);
356   sess->link_enqueue_time = now;
357   sess->link_list_id = list_id;
358   sess->link_next_idx = ~0;
359   sess->link_prev_idx = pw->fa_conn_list_tail[list_id];
360   if (~0 != pw->fa_conn_list_tail[list_id]) {
361     fa_session_t *prev_sess = get_session_ptr(am, thread_index, pw->fa_conn_list_tail[list_id]);
362     prev_sess->link_next_idx = sess_id.session_index;
363     /* We should never try to link with a session on another thread */
364     ASSERT(prev_sess->thread_index == sess->thread_index);
365   }
366   pw->fa_conn_list_tail[list_id] = sess_id.session_index;
367   
368 #ifdef FA_NODE_VERBOSE_DEBUG
369     clib_warning("FA-SESSION-DEBUG: add session id %d on thread %d sw_if_index %d", sess_id.session_index, thread_index, sess->sw_if_index);
370 #endif
371   pw->serviced_sw_if_index_bitmap = clib_bitmap_set(pw->serviced_sw_if_index_bitmap, sess->sw_if_index, 1);
372
373   if (~0 == pw->fa_conn_list_head[list_id]) {
374     pw->fa_conn_list_head[list_id] = sess_id.session_index;
375   }
376 }
377
378 static int
379 acl_fa_conn_list_delete_session (acl_main_t *am, fa_full_session_id_t sess_id)
380 {
381   uword thread_index = os_get_thread_index ();
382   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
383   if (thread_index != sess_id.thread_index) {
384     /* If another thread attempts to delete the session, fail it. */
385 #ifdef FA_NODE_VERBOSE_DEBUG
386     clib_warning("thread id in key %d != curr thread index, not deleting");
387 #endif
388     return 0;
389   }
390   fa_session_t *sess = get_session_ptr(am, sess_id.thread_index, sess_id.session_index);
391   /* we should never try to delete the session with another thread index */
392   ASSERT(sess->thread_index == thread_index);
393   if (~0 != sess->link_prev_idx) {
394     fa_session_t *prev_sess = get_session_ptr(am, thread_index, sess->link_prev_idx);
395     /* the previous session must be in the same list as this one */
396     ASSERT(prev_sess->link_list_id == sess->link_list_id);
397     prev_sess->link_next_idx = sess->link_next_idx;
398   }
399   if (~0 != sess->link_next_idx) {
400     fa_session_t *next_sess = get_session_ptr(am, thread_index, sess->link_next_idx);
401     /* The next session must be in the same list as the one we are deleting */
402     ASSERT(next_sess->link_list_id == sess->link_list_id);
403     next_sess->link_prev_idx = sess->link_prev_idx;
404   }
405   if (pw->fa_conn_list_head[sess->link_list_id] == sess_id.session_index) {
406     pw->fa_conn_list_head[sess->link_list_id] = sess->link_next_idx;
407   }
408   if (pw->fa_conn_list_tail[sess->link_list_id] == sess_id.session_index) {
409     pw->fa_conn_list_tail[sess->link_list_id] = sess->link_prev_idx;
410   }
411   return 1;
412 }
413
414 static int
415 acl_fa_restart_timer_for_session (acl_main_t * am, u64 now, fa_full_session_id_t sess_id)
416 {
417   if (acl_fa_conn_list_delete_session(am, sess_id)) {
418     acl_fa_conn_list_add_session(am, sess_id, now);
419     return 1;
420   } else {
421     /*
422      * Our thread does not own this connection, so we can not delete
423      * The session. To avoid the complicated signaling, we simply
424      * pick the list waiting time to be the shortest of the timeouts.
425      * This way we do not have to do anything special, and let
426      * the regular requeue check take care of everything.
427      */
428     return 0;
429   }
430 }
431
432
433 static u8
434 acl_fa_track_session (acl_main_t * am, int is_input, u32 sw_if_index, u64 now,
435                       fa_session_t * sess, fa_5tuple_t * pkt_5tuple)
436 {
437   sess->last_active_time = now;
438   if (pkt_5tuple->pkt.tcp_flags_valid)
439     {
440       sess->tcp_flags_seen.as_u8[is_input] |= pkt_5tuple->pkt.tcp_flags;
441     }
442   return 3;
443 }
444
445
446 static void
447 acl_fa_delete_session (acl_main_t * am, u32 sw_if_index, fa_full_session_id_t sess_id)
448 {
449   void *oldheap = clib_mem_set_heap(am->acl_mheap);
450   fa_session_t *sess = get_session_ptr(am, sess_id.thread_index, sess_id.session_index);
451   ASSERT(sess->thread_index == os_get_thread_index ());
452   BV (clib_bihash_add_del) (&am->fa_sessions_hash,
453                             &sess->info.kv, 0);
454   acl_fa_per_worker_data_t *pw = &am->per_worker_data[sess_id.thread_index];
455   pool_put_index (pw->fa_sessions_pool, sess_id.session_index);
456   /* Deleting from timer structures not needed,
457      as the caller must have dealt with the timers. */
458   vec_validate (pw->fa_session_dels_by_sw_if_index, sw_if_index);
459   clib_mem_set_heap (oldheap);
460   pw->fa_session_dels_by_sw_if_index[sw_if_index]++;
461   clib_smp_atomic_add(&am->fa_session_total_dels, 1);
462 }
463
464 static int
465 acl_fa_can_add_session (acl_main_t * am, int is_input, u32 sw_if_index)
466 {
467   u64 curr_sess_count;
468   curr_sess_count = am->fa_session_total_adds - am->fa_session_total_dels;
469   return (curr_sess_count < am->fa_conn_table_max_entries);
470 }
471
472 static u64
473 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)
474 {
475   fa_session_t *sess = get_session_ptr(am, thread_index, pw->fa_conn_list_head[timeout_type]);
476   /*
477    * We can not check just the index here because inbetween the worker thread might
478    * dequeue the connection from the head just as we are about to check it.
479    */
480   if (!is_valid_session_ptr(am, thread_index, sess)) {
481     return ~0LL; // infinity.
482   } else {
483     u64 timeout_time =
484               sess->link_enqueue_time + fa_session_get_list_timeout (am, sess);
485     return timeout_time;
486   }
487 }
488
489 static int
490 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)
491 {
492   fa_session_t *sess = get_session_ptr(am, thread_index, session_index);
493   u64 timeout_time =
494               sess->link_enqueue_time + fa_session_get_list_timeout (am, sess);
495   return (timeout_time < now) || (sess->link_enqueue_time <= pw->swipe_end_time);
496 }
497
498 /*
499  * see if there are sessions ready to be checked,
500  * do the maintenance (requeue or delete), and
501  * return the total number of sessions reclaimed.
502  */
503 static int
504 acl_fa_check_idle_sessions(acl_main_t *am, u16 thread_index, u64 now)
505 {
506   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
507   fa_full_session_id_t fsid;
508   fsid.thread_index = thread_index;
509   int total_expired = 0;
510
511   {
512     u8 tt = 0;
513     for(tt = 0; tt < ACL_N_TIMEOUTS; tt++) {
514       while((vec_len(pw->expired) < am->fa_max_deleted_sessions_per_interval)
515             && (~0 != pw->fa_conn_list_head[tt])
516             && (acl_fa_conn_time_to_check(am, pw, now, thread_index,
517                                           pw->fa_conn_list_head[tt]))) {
518         fsid.session_index = pw->fa_conn_list_head[tt];
519         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);
520         vec_add1(pw->expired, fsid.session_index);
521         acl_fa_conn_list_delete_session(am, fsid);
522       }
523     }
524   }
525
526   u32 *psid = NULL;
527   vec_foreach (psid, pw->expired)
528   {
529     fsid.session_index = *psid;
530     if (!pool_is_free_index (pw->fa_sessions_pool, fsid.session_index))
531       {
532         fa_session_t *sess = get_session_ptr(am, thread_index, fsid.session_index);
533         u32 sw_if_index = sess->sw_if_index;
534         u64 sess_timeout_time =
535           sess->last_active_time + fa_session_get_timeout (am, sess);
536         if ((now < sess_timeout_time) && (0 == clib_bitmap_get(pw->pending_clear_sw_if_index_bitmap, sw_if_index)))
537           {
538 #ifdef FA_NODE_VERBOSE_DEBUG
539             clib_warning ("ACL_FA_NODE_CLEAN: Restarting timer for session %d, sw_if_index %d",
540                (int) fsid.session_index, sess->sw_if_index);
541 #endif
542             /* There was activity on the session, so the idle timeout
543                has not passed. Enqueue for another time period. */
544
545             acl_fa_conn_list_add_session(am, fsid, now);
546             pw->cnt_session_timer_restarted++;
547           }
548         else
549           {
550 #ifdef FA_NODE_VERBOSE_DEBUG
551             clib_warning ("ACL_FA_NODE_CLEAN: Deleting session %d, sw_if_index %d",
552                (int) fsid.session_index, sess->sw_if_index);
553 #endif
554             acl_fa_delete_session (am, sw_if_index, fsid);
555             pw->cnt_deleted_sessions++;
556           }
557       }
558     else
559       {
560         pw->cnt_already_deleted_sessions++;
561       }
562   }
563   total_expired = vec_len(pw->expired);
564   /* zero out the vector which we have acted on */
565   if (pw->expired)
566     _vec_len (pw->expired) = 0;
567   /* if we were advancing and reached the end
568    * (no more sessions to recycle), reset the fast-forward timestamp */
569
570   if (pw->swipe_end_time && 0 == total_expired)
571     pw->swipe_end_time = 0;
572   return (total_expired);
573 }
574
575 always_inline void
576 acl_fa_try_recycle_session (acl_main_t * am, int is_input, u16 thread_index, u32 sw_if_index)
577 {
578   /* try to recycle a TCP transient session */
579   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
580   u8 timeout_type = ACL_TIMEOUT_TCP_TRANSIENT;
581   fa_full_session_id_t sess_id;
582   sess_id.session_index = pw->fa_conn_list_head[timeout_type];
583   if (~0 != sess_id.session_index) {
584     sess_id.thread_index = thread_index;
585     acl_fa_conn_list_delete_session(am, sess_id);
586     acl_fa_delete_session(am, sw_if_index, sess_id);
587   }
588 }
589
590 static fa_session_t *
591 acl_fa_add_session (acl_main_t * am, int is_input, u32 sw_if_index, u64 now,
592                     fa_5tuple_t * p5tuple)
593 {
594   clib_bihash_kv_40_8_t *pkv = &p5tuple->kv;
595   clib_bihash_kv_40_8_t kv;
596   fa_full_session_id_t f_sess_id;
597   uword thread_index = os_get_thread_index();
598   void *oldheap = clib_mem_set_heap(am->acl_mheap);
599   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
600
601   f_sess_id.thread_index = thread_index;
602   fa_session_t *sess;
603
604   pool_get_aligned (pw->fa_sessions_pool, sess, CLIB_CACHE_LINE_BYTES);
605   f_sess_id.session_index = sess - pw->fa_sessions_pool;
606
607   kv.key[0] = pkv->key[0];
608   kv.key[1] = pkv->key[1];
609   kv.key[2] = pkv->key[2];
610   kv.key[3] = pkv->key[3];
611   kv.key[4] = pkv->key[4];
612   kv.value = f_sess_id.as_u64;
613
614   memcpy (sess, pkv, sizeof (pkv->key));
615   sess->last_active_time = now;
616   sess->sw_if_index = sw_if_index;
617   sess->tcp_flags_seen.as_u16 = 0;
618   sess->thread_index = thread_index;
619   sess->link_list_id = ~0;
620   sess->link_prev_idx = ~0;
621   sess->link_next_idx = ~0;
622
623
624
625   ASSERT(am->fa_sessions_hash_is_initialized == 1);
626   BV (clib_bihash_add_del) (&am->fa_sessions_hash,
627                             &kv, 1);
628   acl_fa_conn_list_add_session(am, f_sess_id, now);
629
630   vec_validate (pw->fa_session_adds_by_sw_if_index, sw_if_index);
631   clib_mem_set_heap (oldheap);
632   pw->fa_session_adds_by_sw_if_index[sw_if_index]++;
633   clib_smp_atomic_add(&am->fa_session_total_adds, 1);
634   return sess;
635 }
636
637 static int
638 acl_fa_find_session (acl_main_t * am, u32 sw_if_index0, fa_5tuple_t * p5tuple,
639                      clib_bihash_kv_40_8_t * pvalue_sess)
640 {
641   return (clib_bihash_search_40_8 (&am->fa_sessions_hash, &p5tuple->kv, pvalue_sess) == 0);
642 }
643
644
645 always_inline uword
646 acl_fa_node_fn (vlib_main_t * vm,
647                 vlib_node_runtime_t * node, vlib_frame_t * frame, int is_ip6,
648                 int is_input, int is_l2_path, u32 * l2_feat_next_node_index,
649                 vlib_node_registration_t * acl_fa_node)
650 {
651   u32 n_left_from, *from, *to_next;
652   acl_fa_next_t next_index;
653   u32 pkts_acl_checked = 0;
654   u32 pkts_new_session = 0;
655   u32 pkts_exist_session = 0;
656   u32 pkts_acl_permit = 0;
657   u32 pkts_restart_session_timer = 0;
658   u32 trace_bitmap = 0;
659   acl_main_t *am = &acl_main;
660   fa_5tuple_t fa_5tuple, kv_sess;
661   clib_bihash_kv_40_8_t value_sess;
662   vlib_node_runtime_t *error_node;
663   u64 now = clib_cpu_time_now ();
664   uword thread_index = os_get_thread_index ();
665
666   from = vlib_frame_vector_args (frame);
667   n_left_from = frame->n_vectors;
668   next_index = node->cached_next_index;
669
670   error_node = vlib_node_get_runtime (vm, acl_fa_node->index);
671
672   while (n_left_from > 0)
673     {
674       u32 n_left_to_next;
675
676       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
677
678       while (n_left_from > 0 && n_left_to_next > 0)
679         {
680           u32 bi0;
681           vlib_buffer_t *b0;
682           u32 next0 = 0;
683           u8 action = 0;
684           u32 sw_if_index0;
685           u32 lc_index0;
686           int acl_check_needed = 1;
687           u32 match_acl_in_index = ~0;
688           u32 match_acl_pos = ~0;
689           u32 match_rule_index = ~0;
690           u8 error0 = 0;
691           u32 valid_new_sess;
692
693           /* speculatively enqueue b0 to the current next frame */
694           bi0 = from[0];
695           to_next[0] = bi0;
696           from += 1;
697           to_next += 1;
698           n_left_from -= 1;
699           n_left_to_next -= 1;
700
701           b0 = vlib_get_buffer (vm, bi0);
702
703           if (is_input)
704             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
705           else
706             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_TX];
707
708           if (is_input)
709             lc_index0 = am->input_lc_index_by_sw_if_index[sw_if_index0];
710           else
711             lc_index0 = am->output_lc_index_by_sw_if_index[sw_if_index0];
712           /*
713            * Extract the L3/L4 matching info into a 5-tuple structure,
714            * then create a session key whose layout is independent on forward or reverse
715            * direction of the packet.
716            */
717
718           acl_plugin_fill_5tuple_inline (lc_index0, b0, is_ip6, is_input, is_l2_path, (fa_5tuple_opaque_t *)&fa_5tuple);
719           fa_5tuple.l4.lsb_of_sw_if_index = sw_if_index0 & 0xffff;
720           fa_5tuple.pkt.lc_index = lc_index0;
721           valid_new_sess = acl_make_5tuple_session_key (am, is_input, is_ip6, sw_if_index0,  &fa_5tuple, &kv_sess);
722           fa_5tuple.pkt.is_ip6 = is_ip6;
723           // XXDEL fa_5tuple.pkt.is_input = is_input;
724           fa_5tuple.pkt.mask_type_index_lsb = ~0;
725 #ifdef FA_NODE_VERBOSE_DEBUG
726           clib_warning
727             ("ACL_FA_NODE_DBG: session 5-tuple %016llx %016llx %016llx %016llx %016llx %016llx",
728              kv_sess.kv.key[0], kv_sess.kv.key[1], kv_sess.kv.key[2],
729              kv_sess.kv.key[3], kv_sess.kv.key[4], kv_sess.kv.value);
730           clib_warning
731             ("ACL_FA_NODE_DBG: packet 5-tuple %016llx %016llx %016llx %016llx %016llx %016llx",
732              fa_5tuple.kv.key[0], fa_5tuple.kv.key[1], fa_5tuple.kv.key[2],
733              fa_5tuple.kv.key[3], fa_5tuple.kv.key[4], fa_5tuple.kv.value);
734 #endif
735
736           /* Try to match an existing session first */
737
738           if (acl_fa_ifc_has_sessions (am, sw_if_index0))
739             {
740               if (acl_fa_find_session
741                   (am, sw_if_index0, &kv_sess, &value_sess))
742                 {
743                   trace_bitmap |= 0x80000000;
744                   error0 = ACL_FA_ERROR_ACL_EXIST_SESSION;
745                   fa_full_session_id_t f_sess_id;
746
747                   f_sess_id.as_u64 = value_sess.value;
748                   ASSERT(f_sess_id.thread_index < vec_len(vlib_mains));
749
750                   fa_session_t *sess = get_session_ptr(am, f_sess_id.thread_index, f_sess_id.session_index);
751                   int old_timeout_type =
752                     fa_session_get_timeout_type (am, sess);
753                   action =
754                     acl_fa_track_session (am, is_input, sw_if_index0, now,
755                                           sess, &fa_5tuple);
756                   /* expose the session id to the tracer */
757                   match_rule_index = f_sess_id.session_index;
758                   int new_timeout_type =
759                     fa_session_get_timeout_type (am, sess);
760                   acl_check_needed = 0;
761                   pkts_exist_session += 1;
762                   /* Tracking might have changed the session timeout type, e.g. from transient to established */
763                   if (PREDICT_FALSE (old_timeout_type != new_timeout_type))
764                     {
765                       acl_fa_restart_timer_for_session (am, now, f_sess_id);
766                       pkts_restart_session_timer++;
767                       trace_bitmap |=
768                         0x00010000 + ((0xff & old_timeout_type) << 8) +
769                         (0xff & new_timeout_type);
770                     }
771                   /*
772                    * I estimate the likelihood to be very low - the VPP needs
773                    * to have >64K interfaces to start with and then on
774                    * exactly 64K indices apart needs to be exactly the same
775                    * 5-tuple... Anyway, since this probability is nonzero -
776                    * print an error and drop the unlucky packet.
777                    * If this shows up in real world, we would need to bump
778                    * the hash key length.
779                    */
780                   if (PREDICT_FALSE(sess->sw_if_index != sw_if_index0)) {
781                     clib_warning("BUG: session LSB16(sw_if_index) and 5-tuple collision!");
782                     acl_check_needed = 0;
783                     action = 0;
784                   }
785                 }
786             }
787
788           if (acl_check_needed)
789             {
790               action = 0; /* deny by default */
791               acl_plugin_match_5tuple_inline (lc_index0, (fa_5tuple_opaque_t *)&fa_5tuple,
792                                        is_ip6, &action, &match_acl_pos, &match_acl_in_index,
793                                        &match_rule_index, &trace_bitmap);
794               error0 = action;
795               if (1 == action)
796                 pkts_acl_permit += 1;
797               if (2 == action)
798                 {
799                   if (!acl_fa_can_add_session (am, is_input, sw_if_index0))
800                     acl_fa_try_recycle_session (am, is_input, thread_index, sw_if_index0);
801
802                   if (acl_fa_can_add_session (am, is_input, sw_if_index0))
803                     {
804                       if (PREDICT_TRUE (valid_new_sess)) {
805                         fa_session_t *sess = acl_fa_add_session (am, is_input,
806                                                                  sw_if_index0,
807                                                                  now, &kv_sess);
808                         acl_fa_track_session (am, is_input, sw_if_index0, now,
809                                               sess, &fa_5tuple);
810                         pkts_new_session += 1;
811                       } else {
812                         /*
813                          *  ICMP packets with non-icmp_valid_new type will be
814                          *  forwared without being dropped.
815                          */
816                         action = 1;
817                         pkts_acl_permit += 1;
818                       }
819                     }
820                   else
821                     {
822                       action = 0;
823                       error0 = ACL_FA_ERROR_ACL_TOO_MANY_SESSIONS;
824                     }
825                 }
826             }
827
828
829
830           if (action > 0)
831             {
832               if (is_l2_path)
833                 next0 = vnet_l2_feature_next (b0, l2_feat_next_node_index, 0);
834               else
835                 vnet_feature_next (sw_if_index0, &next0, b0);
836             }
837 #ifdef FA_NODE_VERBOSE_DEBUG
838           clib_warning("ACL_FA_NODE_DBG: sw_if_index %d lc_index %d action %d acl_index %d rule_index %d", sw_if_index0, lc_index0, action, match_acl_in_index, match_rule_index);
839 #endif
840
841           if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
842                              && (b0->flags & VLIB_BUFFER_IS_TRACED)))
843             {
844               acl_fa_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
845               t->sw_if_index = sw_if_index0;
846               t->lc_index = lc_index0;
847               t->next_index = next0;
848               t->match_acl_in_index = match_acl_in_index;
849               t->match_rule_index = match_rule_index;
850               t->packet_info[0] = fa_5tuple.kv.key[0];
851               t->packet_info[1] = fa_5tuple.kv.key[1];
852               t->packet_info[2] = fa_5tuple.kv.key[2];
853               t->packet_info[3] = fa_5tuple.kv.key[3];
854               t->packet_info[4] = fa_5tuple.kv.key[4];
855               t->packet_info[5] = fa_5tuple.kv.value;
856               t->action = action;
857               t->trace_bitmap = trace_bitmap;
858             }
859
860           next0 = next0 < node->n_next_nodes ? next0 : 0;
861           if (0 == next0)
862             b0->error = error_node->errors[error0];
863
864           pkts_acl_checked += 1;
865
866           /* verify speculative enqueue, maybe switch current next frame */
867           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
868                                            to_next, n_left_to_next, bi0,
869                                            next0);
870         }
871
872       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
873     }
874
875   vlib_node_increment_counter (vm, acl_fa_node->index,
876                                ACL_FA_ERROR_ACL_CHECK, pkts_acl_checked);
877   vlib_node_increment_counter (vm, acl_fa_node->index,
878                                ACL_FA_ERROR_ACL_PERMIT, pkts_acl_permit);
879   vlib_node_increment_counter (vm, acl_fa_node->index,
880                                ACL_FA_ERROR_ACL_NEW_SESSION,
881                                pkts_new_session);
882   vlib_node_increment_counter (vm, acl_fa_node->index,
883                                ACL_FA_ERROR_ACL_EXIST_SESSION,
884                                pkts_exist_session);
885   vlib_node_increment_counter (vm, acl_fa_node->index,
886                                ACL_FA_ERROR_ACL_RESTART_SESSION_TIMER,
887                                pkts_restart_session_timer);
888   return frame->n_vectors;
889 }
890
891
892 vlib_node_registration_t acl_in_l2_ip6_node;
893 static uword
894 acl_in_ip6_l2_node_fn (vlib_main_t * vm,
895                        vlib_node_runtime_t * node, vlib_frame_t * frame)
896 {
897   acl_main_t *am = &acl_main;
898   return acl_fa_node_fn (vm, node, frame, 1, 1, 1,
899                          am->fa_acl_in_ip6_l2_node_feat_next_node_index,
900                          &acl_in_l2_ip6_node);
901 }
902
903 vlib_node_registration_t acl_in_l2_ip4_node;
904 static uword
905 acl_in_ip4_l2_node_fn (vlib_main_t * vm,
906                        vlib_node_runtime_t * node, vlib_frame_t * frame)
907 {
908   acl_main_t *am = &acl_main;
909   return acl_fa_node_fn (vm, node, frame, 0, 1, 1,
910                          am->fa_acl_in_ip4_l2_node_feat_next_node_index,
911                          &acl_in_l2_ip4_node);
912 }
913
914 vlib_node_registration_t acl_out_l2_ip6_node;
915 static uword
916 acl_out_ip6_l2_node_fn (vlib_main_t * vm,
917                         vlib_node_runtime_t * node, vlib_frame_t * frame)
918 {
919   acl_main_t *am = &acl_main;
920   return acl_fa_node_fn (vm, node, frame, 1, 0, 1,
921                          am->fa_acl_out_ip6_l2_node_feat_next_node_index,
922                          &acl_out_l2_ip6_node);
923 }
924
925 vlib_node_registration_t acl_out_l2_ip4_node;
926 static uword
927 acl_out_ip4_l2_node_fn (vlib_main_t * vm,
928                         vlib_node_runtime_t * node, vlib_frame_t * frame)
929 {
930   acl_main_t *am = &acl_main;
931   return acl_fa_node_fn (vm, node, frame, 0, 0, 1,
932                          am->fa_acl_out_ip4_l2_node_feat_next_node_index,
933                          &acl_out_l2_ip4_node);
934 }
935
936
937 /**** L3 processing path nodes ****/
938
939
940 vlib_node_registration_t acl_in_fa_ip6_node;
941 static uword
942 acl_in_ip6_fa_node_fn (vlib_main_t * vm,
943                        vlib_node_runtime_t * node, vlib_frame_t * frame)
944 {
945   return acl_fa_node_fn (vm, node, frame, 1, 1, 0, 0, &acl_in_fa_ip6_node);
946 }
947
948 vlib_node_registration_t acl_in_fa_ip4_node;
949 static uword
950 acl_in_ip4_fa_node_fn (vlib_main_t * vm,
951                        vlib_node_runtime_t * node, vlib_frame_t * frame)
952 {
953   return acl_fa_node_fn (vm, node, frame, 0, 1, 0, 0, &acl_in_fa_ip4_node);
954 }
955
956 vlib_node_registration_t acl_out_fa_ip6_node;
957 static uword
958 acl_out_ip6_fa_node_fn (vlib_main_t * vm,
959                         vlib_node_runtime_t * node, vlib_frame_t * frame)
960 {
961   return acl_fa_node_fn (vm, node, frame, 1, 0, 0, 0, &acl_out_fa_ip6_node);
962 }
963
964 vlib_node_registration_t acl_out_fa_ip4_node;
965 static uword
966 acl_out_ip4_fa_node_fn (vlib_main_t * vm,
967                         vlib_node_runtime_t * node, vlib_frame_t * frame)
968 {
969   return acl_fa_node_fn (vm, node, frame, 0, 0, 0, 0, &acl_out_fa_ip4_node);
970 }
971
972 /*
973  * This process ensures the connection cleanup happens every so often
974  * even in absence of traffic, as well as provides general orchestration
975  * for requests like connection deletion on a given sw_if_index.
976  */
977
978
979 /* *INDENT-OFF* */
980 #define foreach_acl_fa_cleaner_error \
981 _(UNKNOWN_EVENT, "unknown event received")  \
982 /* end  of errors */
983
984 typedef enum
985 {
986 #define _(sym,str) ACL_FA_CLEANER_ERROR_##sym,
987   foreach_acl_fa_cleaner_error
988 #undef _
989     ACL_FA_CLEANER_N_ERROR,
990 } acl_fa_cleaner_error_t;
991
992 static char *acl_fa_cleaner_error_strings[] = {
993 #define _(sym,string) string,
994   foreach_acl_fa_cleaner_error
995 #undef _
996 };
997
998 /* *INDENT-ON* */
999
1000 static vlib_node_registration_t acl_fa_session_cleaner_process_node;
1001 static vlib_node_registration_t acl_fa_worker_session_cleaner_process_node;
1002
1003 /*
1004  * Per-worker thread interrupt-driven cleaner thread
1005  * to clean idle connections if there are no packets
1006  */
1007 static uword
1008 acl_fa_worker_conn_cleaner_process(vlib_main_t * vm,
1009               vlib_node_runtime_t * rt, vlib_frame_t * f)
1010 {
1011    acl_main_t *am = &acl_main;
1012    u64 now = clib_cpu_time_now ();
1013    u16 thread_index = os_get_thread_index ();
1014    acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1015    int num_expired;
1016    elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner interrupt: now %lu", "i8", now);
1017    /* allow another interrupt to be queued */
1018    pw->interrupt_is_pending = 0;
1019    if (pw->clear_in_process) {
1020      if (0 == pw->swipe_end_time) {
1021        /*
1022         * Someone has just set the flag to start clearing.
1023         * we do this by combing through the connections up to a "time T"
1024         * which is now, and requeueing everything except the expired
1025         * connections and those matching the interface(s) being cleared.
1026         */
1027
1028        /*
1029         * first filter the sw_if_index bitmap that they want from us, by
1030         * a bitmap of sw_if_index for which we actually have connections.
1031         */
1032        if ((pw->pending_clear_sw_if_index_bitmap == 0)
1033            || (pw->serviced_sw_if_index_bitmap == 0)) {
1034          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);
1035          clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1036        } else {
1037 #ifdef FA_NODE_VERBOSE_DEBUG
1038          clib_warning("WORKER-CLEAR: (before and) swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1039                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1040                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1041 #endif
1042          pw->pending_clear_sw_if_index_bitmap = clib_bitmap_and(pw->pending_clear_sw_if_index_bitmap,
1043                                                               pw->serviced_sw_if_index_bitmap);
1044        }
1045
1046        if (clib_bitmap_is_zero(pw->pending_clear_sw_if_index_bitmap)) {
1047          /* if the cross-section is a zero vector, no need to do anything. */
1048          elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, clearing done, nothing to do", "i8", now);
1049          pw->clear_in_process = 0;
1050        } else {
1051 #ifdef FA_NODE_VERBOSE_DEBUG
1052          clib_warning("WORKER-CLEAR: swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1053                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1054                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1055 #endif
1056          elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: swiping until %lu", "i8", now);
1057          /* swipe through the connection lists until enqueue timestamps become above "now" */
1058          pw->swipe_end_time = now;
1059        }
1060      }
1061    }
1062    num_expired = acl_fa_check_idle_sessions(am, thread_index, now);
1063    // clib_warning("WORKER-CLEAR: checked %d sessions (clear_in_progress: %d)", num_expired, pw->clear_in_process);
1064    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);
1065    if (pw->clear_in_process) {
1066      if (0 == num_expired) {
1067        /* we were clearing but we could not process any more connections. time to stop. */
1068        clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1069        pw->clear_in_process = 0;
1070        elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, clearing done - all done", "i8", now);
1071      } else {
1072        elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, more work to do - requesting interrupt", "i8", now);
1073        /* should continue clearing.. So could they please sent an interrupt again? */
1074        pw->interrupt_is_needed = 1;
1075      }
1076    } else {
1077      if (num_expired >= am->fa_max_deleted_sessions_per_interval) {
1078        /* there was too much work, we should get an interrupt ASAP */
1079        pw->interrupt_is_needed = 1;
1080        pw->interrupt_is_unwanted = 0;
1081      } else if (num_expired <= am->fa_min_deleted_sessions_per_interval) {
1082        /* signal that they should trigger us less */
1083        pw->interrupt_is_needed = 0;
1084        pw->interrupt_is_unwanted = 1;
1085      } else {
1086        /* the current rate of interrupts is ok */
1087        pw->interrupt_is_needed = 0;
1088        pw->interrupt_is_unwanted = 0;
1089      }
1090      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));
1091    }
1092    pw->interrupt_generation = am->fa_interrupt_generation;
1093    return 0;
1094 }
1095
1096 static void
1097 send_one_worker_interrupt (vlib_main_t * vm, acl_main_t *am, int thread_index)
1098 {
1099   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1100   if (!pw->interrupt_is_pending) {
1101     pw->interrupt_is_pending = 1;
1102     vlib_node_set_interrupt_pending (vlib_mains[thread_index],
1103                   acl_fa_worker_session_cleaner_process_node.index);
1104     elog_acl_maybe_trace_X1(am, "send_one_worker_interrupt: send interrupt to worker %d", "i4", ((u32)thread_index));
1105     /* if the interrupt was requested, mark that done. */
1106     /* pw->interrupt_is_needed = 0; */
1107   }
1108 }
1109
1110 static void
1111 send_interrupts_to_workers (vlib_main_t * vm, acl_main_t *am)
1112 {
1113   int i;
1114   /* Can't use vec_len(am->per_worker_data) since the threads might not have come up yet; */
1115   int n_threads = vec_len(vlib_mains);
1116   for (i = 0; i < n_threads; i++) {
1117     send_one_worker_interrupt(vm, am, i);
1118   }
1119 }
1120
1121 /* centralized process to drive per-worker cleaners */
1122 static uword
1123 acl_fa_session_cleaner_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1124                                 vlib_frame_t * f)
1125 {
1126   acl_main_t *am = &acl_main;
1127   u64 now;
1128   f64 cpu_cps = vm->clib_time.clocks_per_second;
1129   u64 next_expire;
1130   /* We should check if there are connections to clean up - at least twice a second */
1131   u64 max_timer_wait_interval = cpu_cps / 2;
1132   uword event_type, *event_data = 0;
1133   acl_fa_per_worker_data_t *pw0;
1134
1135   am->fa_current_cleaner_timer_wait_interval = max_timer_wait_interval;
1136   am->fa_cleaner_node_index = acl_fa_session_cleaner_process_node.index;
1137   am->fa_interrupt_generation = 1;
1138   while (1)
1139     {
1140       now = clib_cpu_time_now ();
1141       next_expire = now + am->fa_current_cleaner_timer_wait_interval;
1142       int has_pending_conns = 0;
1143       u16 ti;
1144       u8 tt;
1145
1146       /*
1147        * walk over all per-thread list heads of different timeouts,
1148        * and see if there are any connections pending.
1149        * If there aren't - we do not need to wake up until the
1150        * worker code signals that it has added a connection.
1151        *
1152        * Also, while we are at it, calculate the earliest we need to wake up.
1153        */
1154       for(ti = 0; ti < vec_len(vlib_mains); ti++) {
1155         if (ti >= vec_len(am->per_worker_data)) {
1156           continue;
1157         }
1158         acl_fa_per_worker_data_t *pw = &am->per_worker_data[ti];
1159         for(tt = 0; tt < vec_len(pw->fa_conn_list_head); tt++) {
1160           u64 head_expiry = acl_fa_get_list_head_expiry_time(am, pw, now, ti, tt);
1161           if ((head_expiry < next_expire) && !pw->interrupt_is_pending) {
1162             elog_acl_maybe_trace_X3(am, "acl_fa_session_cleaner_process: now %lu, worker: %d tt: %d", "i8i2i2", now, ti, tt);
1163             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);
1164             next_expire = head_expiry;
1165           }
1166           if (~0 != pw->fa_conn_list_head[tt]) {
1167             has_pending_conns = 1;
1168           }
1169         }
1170       }
1171
1172       /* If no pending connections and no ACL applied then no point in timing out */
1173       if (!has_pending_conns && (0 == am->fa_total_enabled_count))
1174         {
1175           am->fa_cleaner_cnt_wait_without_timeout++;
1176           elog_acl_maybe_trace_X1(am, "acl_conn_cleaner: now %lu entering wait without timeout", "i8", now);
1177           (void) vlib_process_wait_for_event (vm);
1178           event_type = vlib_process_get_events (vm, &event_data);
1179         }
1180       else
1181         {
1182           f64 timeout = ((i64) next_expire - (i64) now) / cpu_cps;
1183           if (timeout <= 0)
1184             {
1185               /* skip waiting altogether */
1186               event_type = ~0;
1187             }
1188           else
1189             {
1190               am->fa_cleaner_cnt_wait_with_timeout++;
1191               elog_acl_maybe_trace_X2(am, "acl_conn_cleaner: now %lu entering wait with timeout %.6f sec", "i8f8", now, timeout);
1192               (void) vlib_process_wait_for_event_or_clock (vm, timeout);
1193               event_type = vlib_process_get_events (vm, &event_data);
1194             }
1195         }
1196
1197       switch (event_type)
1198         {
1199         case ~0:
1200           /* nothing to do */
1201           break;
1202         case ACL_FA_CLEANER_RESCHEDULE:
1203           /* Nothing to do. */
1204           break;
1205         case ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX:
1206           {
1207             uword *clear_sw_if_index_bitmap = 0;
1208             uword *sw_if_index0;
1209             int clear_all = 0;
1210             now = clib_cpu_time_now ();
1211             elog_acl_maybe_trace_X1(am, "acl_fa_session_cleaner_process: now %lu, received ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX", "i8", now);
1212             vec_foreach (sw_if_index0, event_data)
1213             {
1214               am->fa_cleaner_cnt_delete_by_sw_index++;
1215               elog_acl_maybe_trace_X1(am, "acl_fa_session_cleaner_process: ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX %d", "i4", *sw_if_index0);
1216               if (*sw_if_index0 == ~0)
1217                 {
1218                   clear_all = 1;
1219                 }
1220               else
1221                 {
1222                   if (!pool_is_free_index (am->vnet_main->interface_main.sw_interfaces, *sw_if_index0))
1223                     {
1224                       clear_sw_if_index_bitmap = clib_bitmap_set(clear_sw_if_index_bitmap, *sw_if_index0, 1);
1225                     }
1226                 }
1227             }
1228 #ifdef FA_NODE_VERBOSE_DEBUG
1229             clib_warning("ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX bitmap: %U", format_bitmap_hex, clear_sw_if_index_bitmap);
1230 #endif
1231             vec_foreach(pw0, am->per_worker_data) {
1232               CLIB_MEMORY_BARRIER ();
1233               while (pw0->clear_in_process) {
1234                 CLIB_MEMORY_BARRIER ();
1235                 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));
1236                 vlib_process_suspend(vm, 0.0001);
1237                 if (pw0->interrupt_is_needed) {
1238                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1239                 }
1240               }
1241               if (pw0->clear_in_process) {
1242                 clib_warning("ERROR-BUG! Could not initiate cleaning on worker because another cleanup in progress");
1243               } else {
1244                 if (clear_all)
1245                   {
1246                     /* if we need to clear all, then just clear the interfaces that we are servicing */
1247                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(pw0->serviced_sw_if_index_bitmap);
1248                   }
1249                 else
1250                   {
1251                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(clear_sw_if_index_bitmap);
1252                   }
1253                 pw0->clear_in_process = 1;
1254               }
1255             }
1256             /* send some interrupts so they can start working */
1257             send_interrupts_to_workers(vm, am);
1258
1259             /* now wait till they all complete */
1260 #ifdef FA_NODE_VERBOSE_DEBUG
1261             clib_warning("CLEANER mains len: %d per-worker len: %d", vec_len(vlib_mains), vec_len(am->per_worker_data));
1262 #endif
1263             vec_foreach(pw0, am->per_worker_data) {
1264               CLIB_MEMORY_BARRIER ();
1265               while (pw0->clear_in_process) {
1266                 CLIB_MEMORY_BARRIER ();
1267                 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));
1268                 vlib_process_suspend(vm, 0.0001);
1269                 if (pw0->interrupt_is_needed) {
1270                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1271                 }
1272               }
1273             }
1274 #ifdef FA_NODE_VERBOSE_DEBUG
1275             clib_warning("ACL_FA_NODE_CLEAN: cleaning done");
1276 #endif
1277             clib_bitmap_free(clear_sw_if_index_bitmap);
1278           }
1279           break;
1280         default:
1281 #ifdef FA_NODE_VERBOSE_DEBUG
1282           clib_warning ("ACL plugin connection cleaner: unknown event %u",
1283                         event_type);
1284 #endif
1285           vlib_node_increment_counter (vm,
1286                                        acl_fa_session_cleaner_process_node.
1287                                        index,
1288                                        ACL_FA_CLEANER_ERROR_UNKNOWN_EVENT, 1);
1289           am->fa_cleaner_cnt_unknown_event++;
1290           break;
1291         }
1292
1293       send_interrupts_to_workers(vm, am);
1294
1295       if (event_data)
1296         _vec_len (event_data) = 0;
1297
1298       /*
1299        * If the interrupts were not processed yet, ensure we wait a bit,
1300        * but up to a point.
1301        */
1302       int need_more_wait = 0;
1303       int max_wait_cycles = 100;
1304       do {
1305         need_more_wait = 0;
1306         vec_foreach(pw0, am->per_worker_data) {
1307           if (pw0->interrupt_generation != am->fa_interrupt_generation) {
1308             need_more_wait = 1;
1309           }
1310         }
1311         if (need_more_wait) {
1312           vlib_process_suspend(vm, 0.0001);
1313         }
1314       } while (need_more_wait && (--max_wait_cycles > 0));
1315
1316       int interrupts_needed = 0;
1317       int interrupts_unwanted = 0;
1318
1319       vec_foreach(pw0, am->per_worker_data) {
1320         if (pw0->interrupt_is_needed) {
1321           interrupts_needed++;
1322           /* the per-worker value is reset when sending the interrupt */
1323         }
1324         if (pw0->interrupt_is_unwanted) {
1325           interrupts_unwanted++;
1326           pw0->interrupt_is_unwanted = 0;
1327         }
1328       }
1329       if (interrupts_needed) {
1330         /* they need more interrupts, do less waiting around next time */
1331         am->fa_current_cleaner_timer_wait_interval /= 2;
1332         /* never go into zero-wait either though - we need to give the space to others */
1333         am->fa_current_cleaner_timer_wait_interval += 1; 
1334       } else if (interrupts_unwanted) {
1335         /* slowly increase the amount of sleep up to a limit */
1336         if (am->fa_current_cleaner_timer_wait_interval < max_timer_wait_interval)
1337           am->fa_current_cleaner_timer_wait_interval += cpu_cps * am->fa_cleaner_wait_time_increment;
1338       }
1339       am->fa_cleaner_cnt_event_cycles++;
1340       am->fa_interrupt_generation++;
1341     }
1342   /* NOT REACHED */
1343   return 0;
1344 }
1345
1346
1347 void
1348 acl_fa_enable_disable (u32 sw_if_index, int is_input, int enable_disable)
1349 {
1350   acl_main_t *am = &acl_main;
1351   if (enable_disable) {
1352     acl_fa_verify_init_sessions(am);
1353     am->fa_total_enabled_count++;
1354     void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1355     vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1356                                  ACL_FA_CLEANER_RESCHEDULE, 0);
1357     clib_mem_set_heap (oldheap);
1358   } else {
1359     am->fa_total_enabled_count--;
1360   }
1361
1362   if (is_input)
1363     {
1364       ASSERT(clib_bitmap_get(am->fa_in_acl_on_sw_if_index, sw_if_index) != enable_disable);
1365       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1366       vnet_feature_enable_disable ("ip4-unicast", "acl-plugin-in-ip4-fa",
1367                                    sw_if_index, enable_disable, 0, 0);
1368       vnet_feature_enable_disable ("ip6-unicast", "acl-plugin-in-ip6-fa",
1369                                    sw_if_index, enable_disable, 0, 0);
1370       clib_mem_set_heap (oldheap);
1371       am->fa_in_acl_on_sw_if_index =
1372         clib_bitmap_set (am->fa_in_acl_on_sw_if_index, sw_if_index,
1373                          enable_disable);
1374     }
1375   else
1376     {
1377       ASSERT(clib_bitmap_get(am->fa_out_acl_on_sw_if_index, sw_if_index) != enable_disable);
1378       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1379       vnet_feature_enable_disable ("ip4-output", "acl-plugin-out-ip4-fa",
1380                                    sw_if_index, enable_disable, 0, 0);
1381       vnet_feature_enable_disable ("ip6-output", "acl-plugin-out-ip6-fa",
1382                                    sw_if_index, enable_disable, 0, 0);
1383       clib_mem_set_heap (oldheap);
1384       am->fa_out_acl_on_sw_if_index =
1385         clib_bitmap_set (am->fa_out_acl_on_sw_if_index, sw_if_index,
1386                          enable_disable);
1387     }
1388   if ((!enable_disable) && (!acl_fa_ifc_has_in_acl (am, sw_if_index))
1389       && (!acl_fa_ifc_has_out_acl (am, sw_if_index)))
1390     {
1391 #ifdef FA_NODE_VERBOSE_DEBUG
1392       clib_warning("ENABLE-DISABLE: clean the connections on interface %d", sw_if_index);
1393 #endif
1394       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1395       vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1396                                  ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX,
1397                                  sw_if_index);
1398       clib_mem_set_heap (oldheap);
1399     }
1400 }
1401
1402 void
1403 show_fa_sessions_hash(vlib_main_t * vm, u32 verbose)
1404 {
1405   acl_main_t *am = &acl_main;
1406   if (am->fa_sessions_hash_is_initialized) {
1407     vlib_cli_output(vm, "\nSession lookup hash table:\n%U\n\n",
1408                   BV (format_bihash), &am->fa_sessions_hash, verbose);
1409   } else {
1410     vlib_cli_output(vm, "\nSession lookup hash table is not allocated.\n\n");
1411   }
1412 }
1413
1414
1415 /* *INDENT-OFF* */
1416
1417 VLIB_REGISTER_NODE (acl_fa_worker_session_cleaner_process_node, static) = {
1418   .function = acl_fa_worker_conn_cleaner_process,
1419   .name = "acl-plugin-fa-worker-cleaner-process",
1420   .type = VLIB_NODE_TYPE_INPUT,
1421   .state = VLIB_NODE_STATE_INTERRUPT,
1422 };
1423
1424 VLIB_REGISTER_NODE (acl_fa_session_cleaner_process_node, static) = {
1425   .function = acl_fa_session_cleaner_process,
1426   .type = VLIB_NODE_TYPE_PROCESS,
1427   .name = "acl-plugin-fa-cleaner-process",
1428   .n_errors = ARRAY_LEN (acl_fa_cleaner_error_strings),
1429   .error_strings = acl_fa_cleaner_error_strings,
1430   .n_next_nodes = 0,
1431   .next_nodes = {},
1432 };
1433
1434
1435 VLIB_REGISTER_NODE (acl_in_l2_ip6_node) =
1436 {
1437   .function = acl_in_ip6_l2_node_fn,
1438   .name = "acl-plugin-in-ip6-l2",
1439   .vector_size = sizeof (u32),
1440   .format_trace = format_acl_fa_trace,
1441   .type = VLIB_NODE_TYPE_INTERNAL,
1442   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1443   .error_strings = acl_fa_error_strings,
1444   .n_next_nodes = ACL_FA_N_NEXT,
1445   .next_nodes =
1446   {
1447     [ACL_FA_ERROR_DROP] = "error-drop",
1448   }
1449 };
1450
1451 VLIB_REGISTER_NODE (acl_in_l2_ip4_node) =
1452 {
1453   .function = acl_in_ip4_l2_node_fn,
1454   .name = "acl-plugin-in-ip4-l2",
1455   .vector_size = sizeof (u32),
1456   .format_trace = format_acl_fa_trace,
1457   .type = VLIB_NODE_TYPE_INTERNAL,
1458   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1459   .error_strings = acl_fa_error_strings,
1460   .n_next_nodes = ACL_FA_N_NEXT,
1461   .next_nodes =
1462   {
1463     [ACL_FA_ERROR_DROP] = "error-drop",
1464   }
1465 };
1466
1467 VLIB_REGISTER_NODE (acl_out_l2_ip6_node) =
1468 {
1469   .function = acl_out_ip6_l2_node_fn,
1470   .name = "acl-plugin-out-ip6-l2",
1471   .vector_size = sizeof (u32),
1472   .format_trace = format_acl_fa_trace,
1473   .type = VLIB_NODE_TYPE_INTERNAL,
1474   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1475   .error_strings = acl_fa_error_strings,
1476   .n_next_nodes = ACL_FA_N_NEXT,
1477   .next_nodes =
1478   {
1479     [ACL_FA_ERROR_DROP] = "error-drop",
1480   }
1481 };
1482
1483 VLIB_REGISTER_NODE (acl_out_l2_ip4_node) =
1484 {
1485   .function = acl_out_ip4_l2_node_fn,
1486   .name = "acl-plugin-out-ip4-l2",
1487   .vector_size = sizeof (u32),
1488   .format_trace = format_acl_fa_trace,
1489   .type = VLIB_NODE_TYPE_INTERNAL,
1490   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1491   .error_strings = acl_fa_error_strings,
1492   .n_next_nodes = ACL_FA_N_NEXT,
1493   .next_nodes =
1494   {
1495     [ACL_FA_ERROR_DROP] = "error-drop",
1496   }
1497 };
1498
1499
1500 VLIB_REGISTER_NODE (acl_in_fa_ip6_node) =
1501 {
1502   .function = acl_in_ip6_fa_node_fn,
1503   .name = "acl-plugin-in-ip6-fa",
1504   .vector_size = sizeof (u32),
1505   .format_trace = format_acl_fa_trace,
1506   .type = VLIB_NODE_TYPE_INTERNAL,
1507   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1508   .error_strings = acl_fa_error_strings,
1509   .n_next_nodes = ACL_FA_N_NEXT,
1510   .next_nodes =
1511   {
1512     [ACL_FA_ERROR_DROP] = "error-drop",
1513   }
1514 };
1515
1516 VNET_FEATURE_INIT (acl_in_ip6_fa_feature, static) =
1517 {
1518   .arc_name = "ip6-unicast",
1519   .node_name = "acl-plugin-in-ip6-fa",
1520   .runs_before = VNET_FEATURES ("ip6-flow-classify"),
1521 };
1522
1523 VLIB_REGISTER_NODE (acl_in_fa_ip4_node) =
1524 {
1525   .function = acl_in_ip4_fa_node_fn,
1526   .name = "acl-plugin-in-ip4-fa",
1527   .vector_size = sizeof (u32),
1528   .format_trace = format_acl_fa_trace,
1529   .type = VLIB_NODE_TYPE_INTERNAL,
1530   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1531   .error_strings = acl_fa_error_strings,
1532   .n_next_nodes = ACL_FA_N_NEXT,
1533   .next_nodes =
1534   {
1535     [ACL_FA_ERROR_DROP] = "error-drop",
1536   }
1537 };
1538
1539 VNET_FEATURE_INIT (acl_in_ip4_fa_feature, static) =
1540 {
1541   .arc_name = "ip4-unicast",
1542   .node_name = "acl-plugin-in-ip4-fa",
1543   .runs_before = VNET_FEATURES ("ip4-flow-classify"),
1544 };
1545
1546
1547 VLIB_REGISTER_NODE (acl_out_fa_ip6_node) =
1548 {
1549   .function = acl_out_ip6_fa_node_fn,
1550   .name = "acl-plugin-out-ip6-fa",
1551   .vector_size = sizeof (u32),
1552   .format_trace = format_acl_fa_trace,
1553   .type = VLIB_NODE_TYPE_INTERNAL,
1554   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1555   .error_strings = acl_fa_error_strings,
1556   .n_next_nodes = ACL_FA_N_NEXT,
1557   .next_nodes =
1558   {
1559     [ACL_FA_ERROR_DROP] = "error-drop",
1560   }
1561 };
1562
1563 VNET_FEATURE_INIT (acl_out_ip6_fa_feature, static) =
1564 {
1565   .arc_name = "ip6-output",
1566   .node_name = "acl-plugin-out-ip6-fa",
1567   .runs_before = VNET_FEATURES ("interface-output"),
1568 };
1569
1570 VLIB_REGISTER_NODE (acl_out_fa_ip4_node) =
1571 {
1572   .function = acl_out_ip4_fa_node_fn,
1573   .name = "acl-plugin-out-ip4-fa",
1574   .vector_size = sizeof (u32),
1575   .format_trace = format_acl_fa_trace,
1576   .type = VLIB_NODE_TYPE_INTERNAL,
1577   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1578   .error_strings = acl_fa_error_strings,
1579   .n_next_nodes = ACL_FA_N_NEXT,
1580     /* edit / add dispositions here */
1581   .next_nodes =
1582   {
1583     [ACL_FA_ERROR_DROP] = "error-drop",
1584   }
1585 };
1586
1587 VNET_FEATURE_INIT (acl_out_ip4_fa_feature, static) =
1588 {
1589   .arc_name = "ip4-output",
1590   .node_name = "acl-plugin-out-ip4-fa",
1591   .runs_before = VNET_FEATURES ("interface-output"),
1592 };
1593
1594
1595 /* *INDENT-ON* */