acl-plugin: implement an optional session reclassification when ACL is (re-)applied
[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, u16 current_policy_epoch)
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   f_sess_id.intf_policy_epoch = current_policy_epoch;
607
608   kv.key[0] = pkv->key[0];
609   kv.key[1] = pkv->key[1];
610   kv.key[2] = pkv->key[2];
611   kv.key[3] = pkv->key[3];
612   kv.key[4] = pkv->key[4];
613   kv.value = f_sess_id.as_u64;
614
615   memcpy (sess, pkv, sizeof (pkv->key));
616   sess->last_active_time = now;
617   sess->sw_if_index = sw_if_index;
618   sess->tcp_flags_seen.as_u16 = 0;
619   sess->thread_index = thread_index;
620   sess->link_list_id = ~0;
621   sess->link_prev_idx = ~0;
622   sess->link_next_idx = ~0;
623
624
625
626   ASSERT(am->fa_sessions_hash_is_initialized == 1);
627   BV (clib_bihash_add_del) (&am->fa_sessions_hash,
628                             &kv, 1);
629   acl_fa_conn_list_add_session(am, f_sess_id, now);
630
631   vec_validate (pw->fa_session_adds_by_sw_if_index, sw_if_index);
632   clib_mem_set_heap (oldheap);
633   pw->fa_session_adds_by_sw_if_index[sw_if_index]++;
634   clib_smp_atomic_add(&am->fa_session_total_adds, 1);
635   return sess;
636 }
637
638 static int
639 acl_fa_find_session (acl_main_t * am, u32 sw_if_index0, fa_5tuple_t * p5tuple,
640                      clib_bihash_kv_40_8_t * pvalue_sess)
641 {
642   return (clib_bihash_search_40_8 (&am->fa_sessions_hash, &p5tuple->kv, pvalue_sess) == 0);
643 }
644
645
646 always_inline uword
647 acl_fa_node_fn (vlib_main_t * vm,
648                 vlib_node_runtime_t * node, vlib_frame_t * frame, int is_ip6,
649                 int is_input, int is_l2_path, u32 * l2_feat_next_node_index,
650                 vlib_node_registration_t * acl_fa_node)
651 {
652   u32 n_left_from, *from, *to_next;
653   acl_fa_next_t next_index;
654   u32 pkts_acl_checked = 0;
655   u32 pkts_new_session = 0;
656   u32 pkts_exist_session = 0;
657   u32 pkts_acl_permit = 0;
658   u32 pkts_restart_session_timer = 0;
659   u32 trace_bitmap = 0;
660   acl_main_t *am = &acl_main;
661   fa_5tuple_t fa_5tuple, kv_sess;
662   clib_bihash_kv_40_8_t value_sess;
663   vlib_node_runtime_t *error_node;
664   u64 now = clib_cpu_time_now ();
665   uword thread_index = os_get_thread_index ();
666   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
667
668   from = vlib_frame_vector_args (frame);
669   n_left_from = frame->n_vectors;
670   next_index = node->cached_next_index;
671
672   error_node = vlib_node_get_runtime (vm, acl_fa_node->index);
673
674   while (n_left_from > 0)
675     {
676       u32 n_left_to_next;
677
678       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
679
680       while (n_left_from > 0 && n_left_to_next > 0)
681         {
682           u32 bi0;
683           vlib_buffer_t *b0;
684           u32 next0 = 0;
685           u8 action = 0;
686           u32 sw_if_index0;
687           u32 lc_index0;
688           int acl_check_needed = 1;
689           u32 match_acl_in_index = ~0;
690           u32 match_acl_pos = ~0;
691           u32 match_rule_index = ~0;
692           u8 error0 = 0;
693           u32 valid_new_sess;
694
695           /* speculatively enqueue b0 to the current next frame */
696           bi0 = from[0];
697           to_next[0] = bi0;
698           from += 1;
699           to_next += 1;
700           n_left_from -= 1;
701           n_left_to_next -= 1;
702
703           b0 = vlib_get_buffer (vm, bi0);
704
705           if (is_input)
706             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
707           else
708             sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_TX];
709
710           if (is_input)
711             lc_index0 = am->input_lc_index_by_sw_if_index[sw_if_index0];
712           else
713             lc_index0 = am->output_lc_index_by_sw_if_index[sw_if_index0];
714
715           u32 **p_epoch_vec = is_input ? &am->input_policy_epoch_by_sw_if_index
716                                        :  &am->output_policy_epoch_by_sw_if_index;
717           u16 current_policy_epoch = sw_if_index0 < vec_len(*p_epoch_vec) ? vec_elt(*p_epoch_vec, sw_if_index0) : (is_input * FA_POLICY_EPOCH_IS_INPUT);
718           /*
719            * Extract the L3/L4 matching info into a 5-tuple structure,
720            * then create a session key whose layout is independent on forward or reverse
721            * direction of the packet.
722            */
723
724           acl_plugin_fill_5tuple_inline (lc_index0, b0, is_ip6, is_input, is_l2_path, (fa_5tuple_opaque_t *)&fa_5tuple);
725           fa_5tuple.l4.lsb_of_sw_if_index = sw_if_index0 & 0xffff;
726           fa_5tuple.pkt.lc_index = lc_index0;
727           valid_new_sess = acl_make_5tuple_session_key (am, is_input, is_ip6, sw_if_index0,  &fa_5tuple, &kv_sess);
728           fa_5tuple.pkt.is_ip6 = is_ip6;
729           // XXDEL fa_5tuple.pkt.is_input = is_input;
730           fa_5tuple.pkt.mask_type_index_lsb = ~0;
731 #ifdef FA_NODE_VERBOSE_DEBUG
732           clib_warning
733             ("ACL_FA_NODE_DBG: session 5-tuple %016llx %016llx %016llx %016llx %016llx %016llx",
734              kv_sess.kv.key[0], kv_sess.kv.key[1], kv_sess.kv.key[2],
735              kv_sess.kv.key[3], kv_sess.kv.key[4], kv_sess.kv.value);
736           clib_warning
737             ("ACL_FA_NODE_DBG: packet 5-tuple %016llx %016llx %016llx %016llx %016llx %016llx",
738              fa_5tuple.kv.key[0], fa_5tuple.kv.key[1], fa_5tuple.kv.key[2],
739              fa_5tuple.kv.key[3], fa_5tuple.kv.key[4], fa_5tuple.kv.value);
740 #endif
741
742           /* Try to match an existing session first */
743
744           if (acl_fa_ifc_has_sessions (am, sw_if_index0))
745             {
746               if (acl_fa_find_session
747                   (am, sw_if_index0, &kv_sess, &value_sess))
748                 {
749                   trace_bitmap |= 0x80000000;
750                   error0 = ACL_FA_ERROR_ACL_EXIST_SESSION;
751                   fa_full_session_id_t f_sess_id;
752
753                   f_sess_id.as_u64 = value_sess.value;
754                   ASSERT(f_sess_id.thread_index < vec_len(vlib_mains));
755
756                   fa_session_t *sess = get_session_ptr(am, f_sess_id.thread_index, f_sess_id.session_index);
757                   int old_timeout_type =
758                     fa_session_get_timeout_type (am, sess);
759                   action =
760                     acl_fa_track_session (am, is_input, sw_if_index0, now,
761                                           sess, &fa_5tuple);
762                   /* expose the session id to the tracer */
763                   match_rule_index = f_sess_id.session_index;
764                   int new_timeout_type =
765                     fa_session_get_timeout_type (am, sess);
766                   acl_check_needed = 0;
767                   pkts_exist_session += 1;
768                   /* Tracking might have changed the session timeout type, e.g. from transient to established */
769                   if (PREDICT_FALSE (old_timeout_type != new_timeout_type))
770                     {
771                       acl_fa_restart_timer_for_session (am, now, f_sess_id);
772                       pkts_restart_session_timer++;
773                       trace_bitmap |=
774                         0x00010000 + ((0xff & old_timeout_type) << 8) +
775                         (0xff & new_timeout_type);
776                     }
777                   /*
778                    * I estimate the likelihood to be very low - the VPP needs
779                    * to have >64K interfaces to start with and then on
780                    * exactly 64K indices apart needs to be exactly the same
781                    * 5-tuple... Anyway, since this probability is nonzero -
782                    * print an error and drop the unlucky packet.
783                    * If this shows up in real world, we would need to bump
784                    * the hash key length.
785                    */
786                   if (PREDICT_FALSE(sess->sw_if_index != sw_if_index0)) {
787                     clib_warning("BUG: session LSB16(sw_if_index) and 5-tuple collision!");
788                     acl_check_needed = 0;
789                     action = 0;
790                   }
791                   if (PREDICT_FALSE(am->reclassify_sessions)) {
792                    /* if the MSB of policy epoch matches but not the LSB means it is a stale session */
793                    if ( (0 == ((current_policy_epoch ^ f_sess_id.intf_policy_epoch) & FA_POLICY_EPOCH_IS_INPUT))
794                         && (current_policy_epoch != f_sess_id.intf_policy_epoch) ) {
795                       /* delete session and increment the counter */
796                       vec_validate (pw->fa_session_epoch_change_by_sw_if_index, sw_if_index0);
797                       vec_elt (pw->fa_session_epoch_change_by_sw_if_index, sw_if_index0)++;
798                       if(acl_fa_conn_list_delete_session(am, f_sess_id)) {
799                         /* delete the session only if we were able to unlink it */
800                         acl_fa_delete_session (am, sw_if_index0, f_sess_id);
801                       }
802                       acl_check_needed = 1;
803                       trace_bitmap |= 0x40000000;
804                     }
805                   }
806                 }
807             }
808
809           if (acl_check_needed)
810             {
811               action = 0; /* deny by default */
812               acl_plugin_match_5tuple_inline (lc_index0, (fa_5tuple_opaque_t *)&fa_5tuple,
813                                        is_ip6, &action, &match_acl_pos, &match_acl_in_index,
814                                        &match_rule_index, &trace_bitmap);
815               error0 = action;
816               if (1 == action)
817                 pkts_acl_permit += 1;
818               if (2 == action)
819                 {
820                   if (!acl_fa_can_add_session (am, is_input, sw_if_index0))
821                     acl_fa_try_recycle_session (am, is_input, thread_index, sw_if_index0);
822
823                   if (acl_fa_can_add_session (am, is_input, sw_if_index0))
824                     {
825                       if (PREDICT_TRUE (valid_new_sess)) {
826                         fa_session_t *sess = acl_fa_add_session (am, is_input,
827                                                                  sw_if_index0,
828                                                                  now, &kv_sess, current_policy_epoch);
829                         acl_fa_track_session (am, is_input, sw_if_index0, now,
830                                               sess, &fa_5tuple);
831                         pkts_new_session += 1;
832                       } else {
833                         /*
834                          *  ICMP packets with non-icmp_valid_new type will be
835                          *  forwared without being dropped.
836                          */
837                         action = 1;
838                         pkts_acl_permit += 1;
839                       }
840                     }
841                   else
842                     {
843                       action = 0;
844                       error0 = ACL_FA_ERROR_ACL_TOO_MANY_SESSIONS;
845                     }
846                 }
847             }
848
849
850
851           if (action > 0)
852             {
853               if (is_l2_path)
854                 next0 = vnet_l2_feature_next (b0, l2_feat_next_node_index, 0);
855               else
856                 vnet_feature_next (sw_if_index0, &next0, b0);
857             }
858 #ifdef FA_NODE_VERBOSE_DEBUG
859           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);
860 #endif
861
862           if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
863                              && (b0->flags & VLIB_BUFFER_IS_TRACED)))
864             {
865               acl_fa_trace_t *t = vlib_add_trace (vm, node, b0, sizeof (*t));
866               t->sw_if_index = sw_if_index0;
867               t->lc_index = lc_index0;
868               t->next_index = next0;
869               t->match_acl_in_index = match_acl_in_index;
870               t->match_rule_index = match_rule_index;
871               t->packet_info[0] = fa_5tuple.kv.key[0];
872               t->packet_info[1] = fa_5tuple.kv.key[1];
873               t->packet_info[2] = fa_5tuple.kv.key[2];
874               t->packet_info[3] = fa_5tuple.kv.key[3];
875               t->packet_info[4] = fa_5tuple.kv.key[4];
876               t->packet_info[5] = fa_5tuple.kv.value;
877               t->action = action;
878               t->trace_bitmap = trace_bitmap;
879             }
880
881           next0 = next0 < node->n_next_nodes ? next0 : 0;
882           if (0 == next0)
883             b0->error = error_node->errors[error0];
884
885           pkts_acl_checked += 1;
886
887           /* verify speculative enqueue, maybe switch current next frame */
888           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
889                                            to_next, n_left_to_next, bi0,
890                                            next0);
891         }
892
893       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
894     }
895
896   vlib_node_increment_counter (vm, acl_fa_node->index,
897                                ACL_FA_ERROR_ACL_CHECK, pkts_acl_checked);
898   vlib_node_increment_counter (vm, acl_fa_node->index,
899                                ACL_FA_ERROR_ACL_PERMIT, pkts_acl_permit);
900   vlib_node_increment_counter (vm, acl_fa_node->index,
901                                ACL_FA_ERROR_ACL_NEW_SESSION,
902                                pkts_new_session);
903   vlib_node_increment_counter (vm, acl_fa_node->index,
904                                ACL_FA_ERROR_ACL_EXIST_SESSION,
905                                pkts_exist_session);
906   vlib_node_increment_counter (vm, acl_fa_node->index,
907                                ACL_FA_ERROR_ACL_RESTART_SESSION_TIMER,
908                                pkts_restart_session_timer);
909   return frame->n_vectors;
910 }
911
912
913 vlib_node_registration_t acl_in_l2_ip6_node;
914 static uword
915 acl_in_ip6_l2_node_fn (vlib_main_t * vm,
916                        vlib_node_runtime_t * node, vlib_frame_t * frame)
917 {
918   acl_main_t *am = &acl_main;
919   return acl_fa_node_fn (vm, node, frame, 1, 1, 1,
920                          am->fa_acl_in_ip6_l2_node_feat_next_node_index,
921                          &acl_in_l2_ip6_node);
922 }
923
924 vlib_node_registration_t acl_in_l2_ip4_node;
925 static uword
926 acl_in_ip4_l2_node_fn (vlib_main_t * vm,
927                        vlib_node_runtime_t * node, vlib_frame_t * frame)
928 {
929   acl_main_t *am = &acl_main;
930   return acl_fa_node_fn (vm, node, frame, 0, 1, 1,
931                          am->fa_acl_in_ip4_l2_node_feat_next_node_index,
932                          &acl_in_l2_ip4_node);
933 }
934
935 vlib_node_registration_t acl_out_l2_ip6_node;
936 static uword
937 acl_out_ip6_l2_node_fn (vlib_main_t * vm,
938                         vlib_node_runtime_t * node, vlib_frame_t * frame)
939 {
940   acl_main_t *am = &acl_main;
941   return acl_fa_node_fn (vm, node, frame, 1, 0, 1,
942                          am->fa_acl_out_ip6_l2_node_feat_next_node_index,
943                          &acl_out_l2_ip6_node);
944 }
945
946 vlib_node_registration_t acl_out_l2_ip4_node;
947 static uword
948 acl_out_ip4_l2_node_fn (vlib_main_t * vm,
949                         vlib_node_runtime_t * node, vlib_frame_t * frame)
950 {
951   acl_main_t *am = &acl_main;
952   return acl_fa_node_fn (vm, node, frame, 0, 0, 1,
953                          am->fa_acl_out_ip4_l2_node_feat_next_node_index,
954                          &acl_out_l2_ip4_node);
955 }
956
957
958 /**** L3 processing path nodes ****/
959
960
961 vlib_node_registration_t acl_in_fa_ip6_node;
962 static uword
963 acl_in_ip6_fa_node_fn (vlib_main_t * vm,
964                        vlib_node_runtime_t * node, vlib_frame_t * frame)
965 {
966   return acl_fa_node_fn (vm, node, frame, 1, 1, 0, 0, &acl_in_fa_ip6_node);
967 }
968
969 vlib_node_registration_t acl_in_fa_ip4_node;
970 static uword
971 acl_in_ip4_fa_node_fn (vlib_main_t * vm,
972                        vlib_node_runtime_t * node, vlib_frame_t * frame)
973 {
974   return acl_fa_node_fn (vm, node, frame, 0, 1, 0, 0, &acl_in_fa_ip4_node);
975 }
976
977 vlib_node_registration_t acl_out_fa_ip6_node;
978 static uword
979 acl_out_ip6_fa_node_fn (vlib_main_t * vm,
980                         vlib_node_runtime_t * node, vlib_frame_t * frame)
981 {
982   return acl_fa_node_fn (vm, node, frame, 1, 0, 0, 0, &acl_out_fa_ip6_node);
983 }
984
985 vlib_node_registration_t acl_out_fa_ip4_node;
986 static uword
987 acl_out_ip4_fa_node_fn (vlib_main_t * vm,
988                         vlib_node_runtime_t * node, vlib_frame_t * frame)
989 {
990   return acl_fa_node_fn (vm, node, frame, 0, 0, 0, 0, &acl_out_fa_ip4_node);
991 }
992
993 /*
994  * This process ensures the connection cleanup happens every so often
995  * even in absence of traffic, as well as provides general orchestration
996  * for requests like connection deletion on a given sw_if_index.
997  */
998
999
1000 /* *INDENT-OFF* */
1001 #define foreach_acl_fa_cleaner_error \
1002 _(UNKNOWN_EVENT, "unknown event received")  \
1003 /* end  of errors */
1004
1005 typedef enum
1006 {
1007 #define _(sym,str) ACL_FA_CLEANER_ERROR_##sym,
1008   foreach_acl_fa_cleaner_error
1009 #undef _
1010     ACL_FA_CLEANER_N_ERROR,
1011 } acl_fa_cleaner_error_t;
1012
1013 static char *acl_fa_cleaner_error_strings[] = {
1014 #define _(sym,string) string,
1015   foreach_acl_fa_cleaner_error
1016 #undef _
1017 };
1018
1019 /* *INDENT-ON* */
1020
1021 static vlib_node_registration_t acl_fa_session_cleaner_process_node;
1022 static vlib_node_registration_t acl_fa_worker_session_cleaner_process_node;
1023
1024 /*
1025  * Per-worker thread interrupt-driven cleaner thread
1026  * to clean idle connections if there are no packets
1027  */
1028 static uword
1029 acl_fa_worker_conn_cleaner_process(vlib_main_t * vm,
1030               vlib_node_runtime_t * rt, vlib_frame_t * f)
1031 {
1032    acl_main_t *am = &acl_main;
1033    u64 now = clib_cpu_time_now ();
1034    u16 thread_index = os_get_thread_index ();
1035    acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1036    int num_expired;
1037    elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner interrupt: now %lu", "i8", now);
1038    /* allow another interrupt to be queued */
1039    pw->interrupt_is_pending = 0;
1040    if (pw->clear_in_process) {
1041      if (0 == pw->swipe_end_time) {
1042        /*
1043         * Someone has just set the flag to start clearing.
1044         * we do this by combing through the connections up to a "time T"
1045         * which is now, and requeueing everything except the expired
1046         * connections and those matching the interface(s) being cleared.
1047         */
1048
1049        /*
1050         * first filter the sw_if_index bitmap that they want from us, by
1051         * a bitmap of sw_if_index for which we actually have connections.
1052         */
1053        if ((pw->pending_clear_sw_if_index_bitmap == 0)
1054            || (pw->serviced_sw_if_index_bitmap == 0)) {
1055          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);
1056          clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1057        } else {
1058 #ifdef FA_NODE_VERBOSE_DEBUG
1059          clib_warning("WORKER-CLEAR: (before and) swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1060                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1061                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1062 #endif
1063          pw->pending_clear_sw_if_index_bitmap = clib_bitmap_and(pw->pending_clear_sw_if_index_bitmap,
1064                                                               pw->serviced_sw_if_index_bitmap);
1065        }
1066
1067        if (clib_bitmap_is_zero(pw->pending_clear_sw_if_index_bitmap)) {
1068          /* if the cross-section is a zero vector, no need to do anything. */
1069          elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, clearing done, nothing to do", "i8", now);
1070          pw->clear_in_process = 0;
1071        } else {
1072 #ifdef FA_NODE_VERBOSE_DEBUG
1073          clib_warning("WORKER-CLEAR: swiping sw-if-index bitmap: %U, my serviced bitmap %U",
1074                       format_bitmap_hex, pw->pending_clear_sw_if_index_bitmap,
1075                       format_bitmap_hex, pw->serviced_sw_if_index_bitmap);
1076 #endif
1077          elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: swiping until %lu", "i8", now);
1078          /* swipe through the connection lists until enqueue timestamps become above "now" */
1079          pw->swipe_end_time = now;
1080        }
1081      }
1082    }
1083    num_expired = acl_fa_check_idle_sessions(am, thread_index, now);
1084    // clib_warning("WORKER-CLEAR: checked %d sessions (clear_in_progress: %d)", num_expired, pw->clear_in_process);
1085    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);
1086    if (pw->clear_in_process) {
1087      if (0 == num_expired) {
1088        /* we were clearing but we could not process any more connections. time to stop. */
1089        clib_bitmap_zero(pw->pending_clear_sw_if_index_bitmap);
1090        pw->clear_in_process = 0;
1091        elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, clearing done - all done", "i8", now);
1092      } else {
1093        elog_acl_maybe_trace_X1(am, "acl_fa_worker_conn_cleaner: now %lu, more work to do - requesting interrupt", "i8", now);
1094        /* should continue clearing.. So could they please sent an interrupt again? */
1095        pw->interrupt_is_needed = 1;
1096      }
1097    } else {
1098      if (num_expired >= am->fa_max_deleted_sessions_per_interval) {
1099        /* there was too much work, we should get an interrupt ASAP */
1100        pw->interrupt_is_needed = 1;
1101        pw->interrupt_is_unwanted = 0;
1102      } else if (num_expired <= am->fa_min_deleted_sessions_per_interval) {
1103        /* signal that they should trigger us less */
1104        pw->interrupt_is_needed = 0;
1105        pw->interrupt_is_unwanted = 1;
1106      } else {
1107        /* the current rate of interrupts is ok */
1108        pw->interrupt_is_needed = 0;
1109        pw->interrupt_is_unwanted = 0;
1110      }
1111      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));
1112    }
1113    pw->interrupt_generation = am->fa_interrupt_generation;
1114    return 0;
1115 }
1116
1117 static void
1118 send_one_worker_interrupt (vlib_main_t * vm, acl_main_t *am, int thread_index)
1119 {
1120   acl_fa_per_worker_data_t *pw = &am->per_worker_data[thread_index];
1121   if (!pw->interrupt_is_pending) {
1122     pw->interrupt_is_pending = 1;
1123     vlib_node_set_interrupt_pending (vlib_mains[thread_index],
1124                   acl_fa_worker_session_cleaner_process_node.index);
1125     elog_acl_maybe_trace_X1(am, "send_one_worker_interrupt: send interrupt to worker %d", "i4", ((u32)thread_index));
1126     /* if the interrupt was requested, mark that done. */
1127     /* pw->interrupt_is_needed = 0; */
1128   }
1129 }
1130
1131 static void
1132 send_interrupts_to_workers (vlib_main_t * vm, acl_main_t *am)
1133 {
1134   int i;
1135   /* Can't use vec_len(am->per_worker_data) since the threads might not have come up yet; */
1136   int n_threads = vec_len(vlib_mains);
1137   for (i = 0; i < n_threads; i++) {
1138     send_one_worker_interrupt(vm, am, i);
1139   }
1140 }
1141
1142 /* centralized process to drive per-worker cleaners */
1143 static uword
1144 acl_fa_session_cleaner_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1145                                 vlib_frame_t * f)
1146 {
1147   acl_main_t *am = &acl_main;
1148   u64 now;
1149   f64 cpu_cps = vm->clib_time.clocks_per_second;
1150   u64 next_expire;
1151   /* We should check if there are connections to clean up - at least twice a second */
1152   u64 max_timer_wait_interval = cpu_cps / 2;
1153   uword event_type, *event_data = 0;
1154   acl_fa_per_worker_data_t *pw0;
1155
1156   am->fa_current_cleaner_timer_wait_interval = max_timer_wait_interval;
1157   am->fa_cleaner_node_index = acl_fa_session_cleaner_process_node.index;
1158   am->fa_interrupt_generation = 1;
1159   while (1)
1160     {
1161       now = clib_cpu_time_now ();
1162       next_expire = now + am->fa_current_cleaner_timer_wait_interval;
1163       int has_pending_conns = 0;
1164       u16 ti;
1165       u8 tt;
1166
1167       /*
1168        * walk over all per-thread list heads of different timeouts,
1169        * and see if there are any connections pending.
1170        * If there aren't - we do not need to wake up until the
1171        * worker code signals that it has added a connection.
1172        *
1173        * Also, while we are at it, calculate the earliest we need to wake up.
1174        */
1175       for(ti = 0; ti < vec_len(vlib_mains); ti++) {
1176         if (ti >= vec_len(am->per_worker_data)) {
1177           continue;
1178         }
1179         acl_fa_per_worker_data_t *pw = &am->per_worker_data[ti];
1180         for(tt = 0; tt < vec_len(pw->fa_conn_list_head); tt++) {
1181           u64 head_expiry = acl_fa_get_list_head_expiry_time(am, pw, now, ti, tt);
1182           if ((head_expiry < next_expire) && !pw->interrupt_is_pending) {
1183             elog_acl_maybe_trace_X3(am, "acl_fa_session_cleaner_process: now %lu, worker: %d tt: %d", "i8i2i2", now, ti, tt);
1184             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);
1185             next_expire = head_expiry;
1186           }
1187           if (~0 != pw->fa_conn_list_head[tt]) {
1188             has_pending_conns = 1;
1189           }
1190         }
1191       }
1192
1193       /* If no pending connections and no ACL applied then no point in timing out */
1194       if (!has_pending_conns && (0 == am->fa_total_enabled_count))
1195         {
1196           am->fa_cleaner_cnt_wait_without_timeout++;
1197           elog_acl_maybe_trace_X1(am, "acl_conn_cleaner: now %lu entering wait without timeout", "i8", now);
1198           (void) vlib_process_wait_for_event (vm);
1199           event_type = vlib_process_get_events (vm, &event_data);
1200         }
1201       else
1202         {
1203           f64 timeout = ((i64) next_expire - (i64) now) / cpu_cps;
1204           if (timeout <= 0)
1205             {
1206               /* skip waiting altogether */
1207               event_type = ~0;
1208             }
1209           else
1210             {
1211               am->fa_cleaner_cnt_wait_with_timeout++;
1212               elog_acl_maybe_trace_X2(am, "acl_conn_cleaner: now %lu entering wait with timeout %.6f sec", "i8f8", now, timeout);
1213               (void) vlib_process_wait_for_event_or_clock (vm, timeout);
1214               event_type = vlib_process_get_events (vm, &event_data);
1215             }
1216         }
1217
1218       switch (event_type)
1219         {
1220         case ~0:
1221           /* nothing to do */
1222           break;
1223         case ACL_FA_CLEANER_RESCHEDULE:
1224           /* Nothing to do. */
1225           break;
1226         case ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX:
1227           {
1228             uword *clear_sw_if_index_bitmap = 0;
1229             uword *sw_if_index0;
1230             int clear_all = 0;
1231             now = clib_cpu_time_now ();
1232             elog_acl_maybe_trace_X1(am, "acl_fa_session_cleaner_process: now %lu, received ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX", "i8", now);
1233             vec_foreach (sw_if_index0, event_data)
1234             {
1235               am->fa_cleaner_cnt_delete_by_sw_index++;
1236               elog_acl_maybe_trace_X1(am, "acl_fa_session_cleaner_process: ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX %d", "i4", *sw_if_index0);
1237               if (*sw_if_index0 == ~0)
1238                 {
1239                   clear_all = 1;
1240                 }
1241               else
1242                 {
1243                   if (!pool_is_free_index (am->vnet_main->interface_main.sw_interfaces, *sw_if_index0))
1244                     {
1245                       clear_sw_if_index_bitmap = clib_bitmap_set(clear_sw_if_index_bitmap, *sw_if_index0, 1);
1246                     }
1247                 }
1248             }
1249 #ifdef FA_NODE_VERBOSE_DEBUG
1250             clib_warning("ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX bitmap: %U", format_bitmap_hex, clear_sw_if_index_bitmap);
1251 #endif
1252             vec_foreach(pw0, am->per_worker_data) {
1253               CLIB_MEMORY_BARRIER ();
1254               while (pw0->clear_in_process) {
1255                 CLIB_MEMORY_BARRIER ();
1256                 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));
1257                 vlib_process_suspend(vm, 0.0001);
1258                 if (pw0->interrupt_is_needed) {
1259                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1260                 }
1261               }
1262               if (pw0->clear_in_process) {
1263                 clib_warning("ERROR-BUG! Could not initiate cleaning on worker because another cleanup in progress");
1264               } else {
1265                 if (clear_all)
1266                   {
1267                     /* if we need to clear all, then just clear the interfaces that we are servicing */
1268                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(pw0->serviced_sw_if_index_bitmap);
1269                   }
1270                 else
1271                   {
1272                     pw0->pending_clear_sw_if_index_bitmap = clib_bitmap_dup(clear_sw_if_index_bitmap);
1273                   }
1274                 pw0->clear_in_process = 1;
1275               }
1276             }
1277             /* send some interrupts so they can start working */
1278             send_interrupts_to_workers(vm, am);
1279
1280             /* now wait till they all complete */
1281 #ifdef FA_NODE_VERBOSE_DEBUG
1282             clib_warning("CLEANER mains len: %d per-worker len: %d", vec_len(vlib_mains), vec_len(am->per_worker_data));
1283 #endif
1284             vec_foreach(pw0, am->per_worker_data) {
1285               CLIB_MEMORY_BARRIER ();
1286               while (pw0->clear_in_process) {
1287                 CLIB_MEMORY_BARRIER ();
1288                 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));
1289                 vlib_process_suspend(vm, 0.0001);
1290                 if (pw0->interrupt_is_needed) {
1291                   send_one_worker_interrupt(vm, am, (pw0 - am->per_worker_data));
1292                 }
1293               }
1294             }
1295 #ifdef FA_NODE_VERBOSE_DEBUG
1296             clib_warning("ACL_FA_NODE_CLEAN: cleaning done");
1297 #endif
1298             clib_bitmap_free(clear_sw_if_index_bitmap);
1299           }
1300           break;
1301         default:
1302 #ifdef FA_NODE_VERBOSE_DEBUG
1303           clib_warning ("ACL plugin connection cleaner: unknown event %u",
1304                         event_type);
1305 #endif
1306           vlib_node_increment_counter (vm,
1307                                        acl_fa_session_cleaner_process_node.
1308                                        index,
1309                                        ACL_FA_CLEANER_ERROR_UNKNOWN_EVENT, 1);
1310           am->fa_cleaner_cnt_unknown_event++;
1311           break;
1312         }
1313
1314       send_interrupts_to_workers(vm, am);
1315
1316       if (event_data)
1317         _vec_len (event_data) = 0;
1318
1319       /*
1320        * If the interrupts were not processed yet, ensure we wait a bit,
1321        * but up to a point.
1322        */
1323       int need_more_wait = 0;
1324       int max_wait_cycles = 100;
1325       do {
1326         need_more_wait = 0;
1327         vec_foreach(pw0, am->per_worker_data) {
1328           if (pw0->interrupt_generation != am->fa_interrupt_generation) {
1329             need_more_wait = 1;
1330           }
1331         }
1332         if (need_more_wait) {
1333           vlib_process_suspend(vm, 0.0001);
1334         }
1335       } while (need_more_wait && (--max_wait_cycles > 0));
1336
1337       int interrupts_needed = 0;
1338       int interrupts_unwanted = 0;
1339
1340       vec_foreach(pw0, am->per_worker_data) {
1341         if (pw0->interrupt_is_needed) {
1342           interrupts_needed++;
1343           /* the per-worker value is reset when sending the interrupt */
1344         }
1345         if (pw0->interrupt_is_unwanted) {
1346           interrupts_unwanted++;
1347           pw0->interrupt_is_unwanted = 0;
1348         }
1349       }
1350       if (interrupts_needed) {
1351         /* they need more interrupts, do less waiting around next time */
1352         am->fa_current_cleaner_timer_wait_interval /= 2;
1353         /* never go into zero-wait either though - we need to give the space to others */
1354         am->fa_current_cleaner_timer_wait_interval += 1; 
1355       } else if (interrupts_unwanted) {
1356         /* slowly increase the amount of sleep up to a limit */
1357         if (am->fa_current_cleaner_timer_wait_interval < max_timer_wait_interval)
1358           am->fa_current_cleaner_timer_wait_interval += cpu_cps * am->fa_cleaner_wait_time_increment;
1359       }
1360       am->fa_cleaner_cnt_event_cycles++;
1361       am->fa_interrupt_generation++;
1362     }
1363   /* NOT REACHED */
1364   return 0;
1365 }
1366
1367
1368 void
1369 acl_fa_enable_disable (u32 sw_if_index, int is_input, int enable_disable)
1370 {
1371   acl_main_t *am = &acl_main;
1372   if (enable_disable) {
1373     acl_fa_verify_init_sessions(am);
1374     am->fa_total_enabled_count++;
1375     void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1376     vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1377                                  ACL_FA_CLEANER_RESCHEDULE, 0);
1378     clib_mem_set_heap (oldheap);
1379   } else {
1380     am->fa_total_enabled_count--;
1381   }
1382
1383   if (is_input)
1384     {
1385       ASSERT(clib_bitmap_get(am->fa_in_acl_on_sw_if_index, sw_if_index) != enable_disable);
1386       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1387       vnet_feature_enable_disable ("ip4-unicast", "acl-plugin-in-ip4-fa",
1388                                    sw_if_index, enable_disable, 0, 0);
1389       vnet_feature_enable_disable ("ip6-unicast", "acl-plugin-in-ip6-fa",
1390                                    sw_if_index, enable_disable, 0, 0);
1391       clib_mem_set_heap (oldheap);
1392       am->fa_in_acl_on_sw_if_index =
1393         clib_bitmap_set (am->fa_in_acl_on_sw_if_index, sw_if_index,
1394                          enable_disable);
1395     }
1396   else
1397     {
1398       ASSERT(clib_bitmap_get(am->fa_out_acl_on_sw_if_index, sw_if_index) != enable_disable);
1399       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1400       vnet_feature_enable_disable ("ip4-output", "acl-plugin-out-ip4-fa",
1401                                    sw_if_index, enable_disable, 0, 0);
1402       vnet_feature_enable_disable ("ip6-output", "acl-plugin-out-ip6-fa",
1403                                    sw_if_index, enable_disable, 0, 0);
1404       clib_mem_set_heap (oldheap);
1405       am->fa_out_acl_on_sw_if_index =
1406         clib_bitmap_set (am->fa_out_acl_on_sw_if_index, sw_if_index,
1407                          enable_disable);
1408     }
1409   if ((!enable_disable) && (!acl_fa_ifc_has_in_acl (am, sw_if_index))
1410       && (!acl_fa_ifc_has_out_acl (am, sw_if_index)))
1411     {
1412 #ifdef FA_NODE_VERBOSE_DEBUG
1413       clib_warning("ENABLE-DISABLE: clean the connections on interface %d", sw_if_index);
1414 #endif
1415       void *oldheap = clib_mem_set_heap (am->vlib_main->heap_base);
1416       vlib_process_signal_event (am->vlib_main, am->fa_cleaner_node_index,
1417                                  ACL_FA_CLEANER_DELETE_BY_SW_IF_INDEX,
1418                                  sw_if_index);
1419       clib_mem_set_heap (oldheap);
1420     }
1421 }
1422
1423 void
1424 show_fa_sessions_hash(vlib_main_t * vm, u32 verbose)
1425 {
1426   acl_main_t *am = &acl_main;
1427   if (am->fa_sessions_hash_is_initialized) {
1428     vlib_cli_output(vm, "\nSession lookup hash table:\n%U\n\n",
1429                   BV (format_bihash), &am->fa_sessions_hash, verbose);
1430   } else {
1431     vlib_cli_output(vm, "\nSession lookup hash table is not allocated.\n\n");
1432   }
1433 }
1434
1435
1436 /* *INDENT-OFF* */
1437
1438 VLIB_REGISTER_NODE (acl_fa_worker_session_cleaner_process_node, static) = {
1439   .function = acl_fa_worker_conn_cleaner_process,
1440   .name = "acl-plugin-fa-worker-cleaner-process",
1441   .type = VLIB_NODE_TYPE_INPUT,
1442   .state = VLIB_NODE_STATE_INTERRUPT,
1443 };
1444
1445 VLIB_REGISTER_NODE (acl_fa_session_cleaner_process_node, static) = {
1446   .function = acl_fa_session_cleaner_process,
1447   .type = VLIB_NODE_TYPE_PROCESS,
1448   .name = "acl-plugin-fa-cleaner-process",
1449   .n_errors = ARRAY_LEN (acl_fa_cleaner_error_strings),
1450   .error_strings = acl_fa_cleaner_error_strings,
1451   .n_next_nodes = 0,
1452   .next_nodes = {},
1453 };
1454
1455
1456 VLIB_REGISTER_NODE (acl_in_l2_ip6_node) =
1457 {
1458   .function = acl_in_ip6_l2_node_fn,
1459   .name = "acl-plugin-in-ip6-l2",
1460   .vector_size = sizeof (u32),
1461   .format_trace = format_acl_fa_trace,
1462   .type = VLIB_NODE_TYPE_INTERNAL,
1463   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1464   .error_strings = acl_fa_error_strings,
1465   .n_next_nodes = ACL_FA_N_NEXT,
1466   .next_nodes =
1467   {
1468     [ACL_FA_ERROR_DROP] = "error-drop",
1469   }
1470 };
1471
1472 VLIB_REGISTER_NODE (acl_in_l2_ip4_node) =
1473 {
1474   .function = acl_in_ip4_l2_node_fn,
1475   .name = "acl-plugin-in-ip4-l2",
1476   .vector_size = sizeof (u32),
1477   .format_trace = format_acl_fa_trace,
1478   .type = VLIB_NODE_TYPE_INTERNAL,
1479   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1480   .error_strings = acl_fa_error_strings,
1481   .n_next_nodes = ACL_FA_N_NEXT,
1482   .next_nodes =
1483   {
1484     [ACL_FA_ERROR_DROP] = "error-drop",
1485   }
1486 };
1487
1488 VLIB_REGISTER_NODE (acl_out_l2_ip6_node) =
1489 {
1490   .function = acl_out_ip6_l2_node_fn,
1491   .name = "acl-plugin-out-ip6-l2",
1492   .vector_size = sizeof (u32),
1493   .format_trace = format_acl_fa_trace,
1494   .type = VLIB_NODE_TYPE_INTERNAL,
1495   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1496   .error_strings = acl_fa_error_strings,
1497   .n_next_nodes = ACL_FA_N_NEXT,
1498   .next_nodes =
1499   {
1500     [ACL_FA_ERROR_DROP] = "error-drop",
1501   }
1502 };
1503
1504 VLIB_REGISTER_NODE (acl_out_l2_ip4_node) =
1505 {
1506   .function = acl_out_ip4_l2_node_fn,
1507   .name = "acl-plugin-out-ip4-l2",
1508   .vector_size = sizeof (u32),
1509   .format_trace = format_acl_fa_trace,
1510   .type = VLIB_NODE_TYPE_INTERNAL,
1511   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1512   .error_strings = acl_fa_error_strings,
1513   .n_next_nodes = ACL_FA_N_NEXT,
1514   .next_nodes =
1515   {
1516     [ACL_FA_ERROR_DROP] = "error-drop",
1517   }
1518 };
1519
1520
1521 VLIB_REGISTER_NODE (acl_in_fa_ip6_node) =
1522 {
1523   .function = acl_in_ip6_fa_node_fn,
1524   .name = "acl-plugin-in-ip6-fa",
1525   .vector_size = sizeof (u32),
1526   .format_trace = format_acl_fa_trace,
1527   .type = VLIB_NODE_TYPE_INTERNAL,
1528   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1529   .error_strings = acl_fa_error_strings,
1530   .n_next_nodes = ACL_FA_N_NEXT,
1531   .next_nodes =
1532   {
1533     [ACL_FA_ERROR_DROP] = "error-drop",
1534   }
1535 };
1536
1537 VNET_FEATURE_INIT (acl_in_ip6_fa_feature, static) =
1538 {
1539   .arc_name = "ip6-unicast",
1540   .node_name = "acl-plugin-in-ip6-fa",
1541   .runs_before = VNET_FEATURES ("ip6-flow-classify"),
1542 };
1543
1544 VLIB_REGISTER_NODE (acl_in_fa_ip4_node) =
1545 {
1546   .function = acl_in_ip4_fa_node_fn,
1547   .name = "acl-plugin-in-ip4-fa",
1548   .vector_size = sizeof (u32),
1549   .format_trace = format_acl_fa_trace,
1550   .type = VLIB_NODE_TYPE_INTERNAL,
1551   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1552   .error_strings = acl_fa_error_strings,
1553   .n_next_nodes = ACL_FA_N_NEXT,
1554   .next_nodes =
1555   {
1556     [ACL_FA_ERROR_DROP] = "error-drop",
1557   }
1558 };
1559
1560 VNET_FEATURE_INIT (acl_in_ip4_fa_feature, static) =
1561 {
1562   .arc_name = "ip4-unicast",
1563   .node_name = "acl-plugin-in-ip4-fa",
1564   .runs_before = VNET_FEATURES ("ip4-flow-classify"),
1565 };
1566
1567
1568 VLIB_REGISTER_NODE (acl_out_fa_ip6_node) =
1569 {
1570   .function = acl_out_ip6_fa_node_fn,
1571   .name = "acl-plugin-out-ip6-fa",
1572   .vector_size = sizeof (u32),
1573   .format_trace = format_acl_fa_trace,
1574   .type = VLIB_NODE_TYPE_INTERNAL,
1575   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1576   .error_strings = acl_fa_error_strings,
1577   .n_next_nodes = ACL_FA_N_NEXT,
1578   .next_nodes =
1579   {
1580     [ACL_FA_ERROR_DROP] = "error-drop",
1581   }
1582 };
1583
1584 VNET_FEATURE_INIT (acl_out_ip6_fa_feature, static) =
1585 {
1586   .arc_name = "ip6-output",
1587   .node_name = "acl-plugin-out-ip6-fa",
1588   .runs_before = VNET_FEATURES ("interface-output"),
1589 };
1590
1591 VLIB_REGISTER_NODE (acl_out_fa_ip4_node) =
1592 {
1593   .function = acl_out_ip4_fa_node_fn,
1594   .name = "acl-plugin-out-ip4-fa",
1595   .vector_size = sizeof (u32),
1596   .format_trace = format_acl_fa_trace,
1597   .type = VLIB_NODE_TYPE_INTERNAL,
1598   .n_errors = ARRAY_LEN (acl_fa_error_strings),
1599   .error_strings = acl_fa_error_strings,
1600   .n_next_nodes = ACL_FA_N_NEXT,
1601     /* edit / add dispositions here */
1602   .next_nodes =
1603   {
1604     [ACL_FA_ERROR_DROP] = "error-drop",
1605   }
1606 };
1607
1608 VNET_FEATURE_INIT (acl_out_ip4_fa_feature, static) =
1609 {
1610   .arc_name = "ip4-output",
1611   .node_name = "acl-plugin-out-ip4-fa",
1612   .runs_before = VNET_FEATURES ("interface-output"),
1613 };
1614
1615
1616 /* *INDENT-ON* */