acl-plugin: change the src/dst L3 info in 5tuple struct to be always contiguous with...
[vpp.git] / src / plugins / acl / hash_lookup.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2017 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17
18 #include <stddef.h>
19 #include <netinet/in.h>
20
21 #include <vlibapi/api.h>
22 #include <vlibmemory/api.h>
23
24 #include <vlib/vlib.h>
25 #include <vnet/vnet.h>
26 #include <vnet/pg/pg.h>
27 #include <vppinfra/error.h>
28 #include <vnet/plugin/plugin.h>
29 #include <acl/acl.h>
30 #include <vppinfra/bihash_48_8.h>
31
32 #include "hash_lookup.h"
33 #include "hash_lookup_private.h"
34
35
36 always_inline applied_hash_ace_entry_t **get_applied_hash_aces(acl_main_t *am, u32 lc_index)
37 {
38   applied_hash_ace_entry_t **applied_hash_aces = vec_elt_at_index(am->hash_entry_vec_by_lc_index, lc_index);
39
40 /*is_input ? vec_elt_at_index(am->input_hash_entry_vec_by_sw_if_index, sw_if_index)
41                                                           : vec_elt_at_index(am->output_hash_entry_vec_by_sw_if_index, sw_if_index);
42 */
43   return applied_hash_aces;
44 }
45
46
47 static void
48 hashtable_add_del(acl_main_t *am, clib_bihash_kv_48_8_t *kv, int is_add)
49 {
50     DBG("HASH ADD/DEL: %016llx %016llx %016llx %016llx %016llx %016llx %016llx add %d",
51                         kv->key[0], kv->key[1], kv->key[2],
52                         kv->key[3], kv->key[4], kv->key[5], kv->value, is_add);
53     BV (clib_bihash_add_del) (&am->acl_lookup_hash, kv, is_add);
54 }
55
56 static void
57 fill_applied_hash_ace_kv(acl_main_t *am,
58                             applied_hash_ace_entry_t **applied_hash_aces,
59                             u32 lc_index,
60                             u32 new_index, clib_bihash_kv_48_8_t *kv)
61 {
62   fa_5tuple_t *kv_key = (fa_5tuple_t *)kv->key;
63   hash_acl_lookup_value_t *kv_val = (hash_acl_lookup_value_t *)&kv->value;
64   applied_hash_ace_entry_t *pae = vec_elt_at_index((*applied_hash_aces), new_index);
65   hash_acl_info_t *ha = vec_elt_at_index(am->hash_acl_infos, pae->acl_index);
66
67   memcpy(kv_key, &(vec_elt_at_index(ha->rules, pae->hash_ace_info_index)->match), sizeof(*kv_key));
68   /* initialize the sw_if_index and direction */
69   kv_key->pkt.lc_index = lc_index;
70   kv_val->as_u64 = 0;
71   kv_val->applied_entry_index = new_index;
72   kv_val->need_portrange_check = vec_elt_at_index(ha->rules, pae->hash_ace_info_index)->src_portrange_not_powerof2 ||
73                                    vec_elt_at_index(ha->rules, pae->hash_ace_info_index)->dst_portrange_not_powerof2;
74   /* by default assume all values are shadowed -> check all mask types */
75   kv_val->shadowed = 1;
76 }
77
78 static void
79 add_del_hashtable_entry(acl_main_t *am,
80                             u32 lc_index,
81                             applied_hash_ace_entry_t **applied_hash_aces,
82                             u32 index, int is_add)
83 {
84   clib_bihash_kv_48_8_t kv;
85
86   fill_applied_hash_ace_kv(am, applied_hash_aces, lc_index, index, &kv);
87   hashtable_add_del(am, &kv, is_add);
88 }
89
90
91
92 static void
93 activate_applied_ace_hash_entry(acl_main_t *am,
94                             u32 lc_index,
95                             applied_hash_ace_entry_t **applied_hash_aces,
96                             u32 new_index)
97 {
98   clib_bihash_kv_48_8_t kv;
99   ASSERT(new_index != ~0);
100   applied_hash_ace_entry_t *pae = vec_elt_at_index((*applied_hash_aces), new_index);
101   DBG("activate_applied_ace_hash_entry lc_index %d new_index %d", lc_index, new_index);
102
103   fill_applied_hash_ace_kv(am, applied_hash_aces, lc_index, new_index, &kv);
104
105   DBG("APPLY ADD KY: %016llx %016llx %016llx %016llx %016llx %016llx",
106                         kv.key[0], kv.key[1], kv.key[2],
107                         kv.key[3], kv.key[4], kv.key[5]);
108
109   clib_bihash_kv_48_8_t result;
110   hash_acl_lookup_value_t *result_val = (hash_acl_lookup_value_t *)&result.value;
111   int res = BV (clib_bihash_search) (&am->acl_lookup_hash, &kv, &result);
112   ASSERT(new_index != ~0);
113   ASSERT(new_index < vec_len((*applied_hash_aces)));
114   if (res == 0) {
115     /* There already exists an entry or more. Append at the end. */
116     u32 first_index = result_val->applied_entry_index;
117     ASSERT(first_index != ~0);
118     DBG("A key already exists, with applied entry index: %d", first_index);
119     applied_hash_ace_entry_t *first_pae = vec_elt_at_index((*applied_hash_aces), first_index);
120     u32 last_index = first_pae->tail_applied_entry_index;
121     ASSERT(last_index != ~0);
122     applied_hash_ace_entry_t *last_pae = vec_elt_at_index((*applied_hash_aces), last_index);
123     DBG("...advance to chained entry index: %d", last_index);
124     /* link ourseves in */
125     last_pae->next_applied_entry_index = new_index;
126     pae->prev_applied_entry_index = last_index;
127     /* adjust the pointer to the new tail */
128     first_pae->tail_applied_entry_index = new_index;
129   } else {
130     /* It's the very first entry */
131     hashtable_add_del(am, &kv, 1);
132     ASSERT(new_index != ~0);
133     pae->tail_applied_entry_index = new_index;
134   }
135 }
136
137 static void
138 applied_hash_entries_analyze(acl_main_t *am, applied_hash_ace_entry_t **applied_hash_aces)
139 {
140   /*
141    * Go over the rules and check which ones are shadowed and which aren't.
142    * Naive approach: try to match the match value from every ACE as if it
143    * was a live packet, and see if the resulting match happens earlier in the list.
144    * if it does not match or it is later in the ACL - then the entry is not shadowed.
145    *
146    * This approach fails, an example:
147    *   deny tcp 2001:db8::/32 2001:db8::/32
148    *   permit ip 2001:db8::1/128 2001:db8::2/128
149    */
150 }
151
152 static void *
153 hash_acl_set_heap(acl_main_t *am)
154 {
155   if (0 == am->hash_lookup_mheap) {
156     am->hash_lookup_mheap = mheap_alloc (0 /* use VM */ , am->hash_lookup_mheap_size);
157     if (0 == am->hash_lookup_mheap) {
158       clib_error("ACL plugin failed to allocate hash lookup heap of %U bytes, abort", format_memory_size, am->hash_lookup_mheap_size);
159     }
160     mheap_t *h = mheap_header (am->hash_lookup_mheap);
161     h->flags |= MHEAP_FLAG_THREAD_SAFE;
162   }
163   void *oldheap = clib_mem_set_heap(am->hash_lookup_mheap);
164   return oldheap;
165 }
166
167 void
168 acl_plugin_hash_acl_set_validate_heap(int on)
169 {
170   acl_main_t *am = &acl_main;
171   clib_mem_set_heap(hash_acl_set_heap(am));
172   mheap_t *h = mheap_header (am->hash_lookup_mheap);
173   if (on) {
174     h->flags |= MHEAP_FLAG_VALIDATE;
175     h->flags &= ~MHEAP_FLAG_SMALL_OBJECT_CACHE;
176     mheap_validate(h);
177   } else {
178     h->flags &= ~MHEAP_FLAG_VALIDATE;
179     h->flags |= MHEAP_FLAG_SMALL_OBJECT_CACHE;
180   }
181 }
182
183 void
184 acl_plugin_hash_acl_set_trace_heap(int on)
185 {
186   acl_main_t *am = &acl_main;
187   clib_mem_set_heap(hash_acl_set_heap(am));
188   mheap_t *h = mheap_header (am->hash_lookup_mheap);
189   if (on) {
190     h->flags |= MHEAP_FLAG_TRACE;
191   } else {
192     h->flags &= ~MHEAP_FLAG_TRACE;
193   }
194 }
195
196 void
197 hash_acl_apply(acl_main_t *am, u32 lc_index, int acl_index, u32 acl_position)
198 {
199   int i;
200
201   DBG0("HASH ACL apply: lc_index %d acl %d", lc_index, acl_index);
202   if (!am->acl_lookup_hash_initialized) {
203     BV (clib_bihash_init) (&am->acl_lookup_hash, "ACL plugin rule lookup bihash",
204                            am->hash_lookup_hash_buckets, am->hash_lookup_hash_memory);
205     am->acl_lookup_hash_initialized = 1;
206   }
207
208   void *oldheap = hash_acl_set_heap(am);
209   vec_validate(am->hash_entry_vec_by_lc_index, lc_index);
210   vec_validate(am->hash_acl_infos, acl_index);
211   applied_hash_ace_entry_t **applied_hash_aces = get_applied_hash_aces(am, lc_index);
212
213   hash_acl_info_t *ha = vec_elt_at_index(am->hash_acl_infos, acl_index);
214   u32 **hash_acl_applied_lc_index = &ha->lc_index_list;
215
216   int base_offset = vec_len(*applied_hash_aces);
217
218   /* Update the bitmap of the mask types with which the lookup
219      needs to happen for the ACLs applied to this lc_index */
220   applied_hash_acl_info_t **applied_hash_acls = &am->applied_hash_acl_info_by_lc_index;
221   vec_validate((*applied_hash_acls), lc_index);
222   applied_hash_acl_info_t *pal = vec_elt_at_index((*applied_hash_acls), lc_index);
223
224   /* ensure the list of applied hash acls is initialized and add this acl# to it */
225   u32 index = vec_search(pal->applied_acls, acl_index);
226   if (index != ~0) {
227     clib_warning("BUG: trying to apply twice acl_index %d on lc_index %d, according to lc",
228                  acl_index, lc_index);
229     goto done;
230   }
231   vec_add1(pal->applied_acls, acl_index);
232   u32 index2 = vec_search((*hash_acl_applied_lc_index), lc_index);
233   if (index2 != ~0) {
234     clib_warning("BUG: trying to apply twice acl_index %d on lc_index %d, according to hash h-acl info",
235                  acl_index, lc_index);
236     goto done;
237   }
238   vec_add1((*hash_acl_applied_lc_index), lc_index);
239
240   pal->mask_type_index_bitmap = clib_bitmap_or(pal->mask_type_index_bitmap,
241                                      ha->mask_type_index_bitmap);
242   /*
243    * if the applied ACL is empty, the current code will cause a
244    * different behavior compared to current linear search: an empty ACL will
245    * simply fallthrough to the next ACL, or the default deny in the end.
246    *
247    * This is not a problem, because after vpp-dev discussion,
248    * the consensus was it should not be possible to apply the non-existent
249    * ACL, so the change adding this code also takes care of that.
250    */
251
252   /* expand the applied aces vector by the necessary amount */
253   vec_resize((*applied_hash_aces), vec_len(ha->rules));
254
255   /* add the rules from the ACL to the hash table for lookup and append to the vector*/
256   for(i=0; i < vec_len(ha->rules); i++) {
257     u32 new_index = base_offset + i;
258     applied_hash_ace_entry_t *pae = vec_elt_at_index((*applied_hash_aces), new_index);
259     pae->acl_index = acl_index;
260     pae->ace_index = ha->rules[i].ace_index;
261     pae->acl_position = acl_position;
262     pae->action = ha->rules[i].action;
263     pae->hitcount = 0;
264     pae->hash_ace_info_index = i;
265     /* we might link it in later */
266     pae->next_applied_entry_index = ~0;
267     pae->prev_applied_entry_index = ~0;
268     pae->tail_applied_entry_index = ~0;
269     activate_applied_ace_hash_entry(am, lc_index, applied_hash_aces, new_index);
270   }
271   applied_hash_entries_analyze(am, applied_hash_aces);
272 done:
273   clib_mem_set_heap (oldheap);
274 }
275
276 static u32
277 find_head_applied_ace_index(applied_hash_ace_entry_t **applied_hash_aces, u32 curr_index)
278 {
279   /*
280    * find back the first entry. Inefficient so might need to be a bit cleverer
281    * if this proves to be a problem..
282    */
283   u32 an_index = curr_index;
284   ASSERT(an_index != ~0);
285   applied_hash_ace_entry_t *head_pae = vec_elt_at_index((*applied_hash_aces), an_index);
286   while(head_pae->prev_applied_entry_index != ~0) {
287     an_index = head_pae->prev_applied_entry_index;
288     ASSERT(an_index != ~0);
289     head_pae = vec_elt_at_index((*applied_hash_aces), an_index);
290   }
291   return an_index;
292 }
293
294 static void
295 move_applied_ace_hash_entry(acl_main_t *am,
296                             u32 lc_index,
297                             applied_hash_ace_entry_t **applied_hash_aces,
298                             u32 old_index, u32 new_index)
299 {
300   ASSERT(old_index != ~0);
301   ASSERT(new_index != ~0);
302   /* move the entry */
303   *vec_elt_at_index((*applied_hash_aces), new_index) = *vec_elt_at_index((*applied_hash_aces), old_index);
304
305   /* update the linkage and hash table if necessary */
306   applied_hash_ace_entry_t *pae = vec_elt_at_index((*applied_hash_aces), old_index);
307
308   if (pae->prev_applied_entry_index != ~0) {
309     applied_hash_ace_entry_t *prev_pae = vec_elt_at_index((*applied_hash_aces), pae->prev_applied_entry_index);
310     ASSERT(prev_pae->next_applied_entry_index == old_index);
311     prev_pae->next_applied_entry_index = new_index;
312   } else {
313     /* first entry - so the hash points to it, update */
314     add_del_hashtable_entry(am, lc_index,
315                             applied_hash_aces, new_index, 1);
316     ASSERT(pae->tail_applied_entry_index != ~0);
317   }
318   if (pae->next_applied_entry_index != ~0) {
319     applied_hash_ace_entry_t *next_pae = vec_elt_at_index((*applied_hash_aces), pae->next_applied_entry_index);
320     ASSERT(next_pae->prev_applied_entry_index == old_index);
321     next_pae->prev_applied_entry_index = new_index;
322   } else {
323     /*
324      * Moving the very last entry, so we need to update the tail pointer in the first one.
325      */
326     u32 head_index = find_head_applied_ace_index(applied_hash_aces, old_index);
327     ASSERT(head_index != ~0);
328     applied_hash_ace_entry_t *head_pae = vec_elt_at_index((*applied_hash_aces), head_index);
329
330     ASSERT(head_pae->tail_applied_entry_index == old_index);
331     head_pae->tail_applied_entry_index = new_index;
332   }
333   /* invalidate the old entry */
334   pae->prev_applied_entry_index = ~0;
335   pae->next_applied_entry_index = ~0;
336   pae->tail_applied_entry_index = ~0;
337 }
338
339 static void
340 deactivate_applied_ace_hash_entry(acl_main_t *am,
341                             u32 lc_index,
342                             applied_hash_ace_entry_t **applied_hash_aces,
343                             u32 old_index)
344 {
345   applied_hash_ace_entry_t *pae = vec_elt_at_index((*applied_hash_aces), old_index);
346   DBG("UNAPPLY DEACTIVATE: lc_index %d applied index %d", lc_index, old_index);
347
348   if (pae->prev_applied_entry_index != ~0) {
349     DBG("UNAPPLY = index %d has prev_applied_entry_index %d", old_index, pae->prev_applied_entry_index);
350     applied_hash_ace_entry_t *prev_pae = vec_elt_at_index((*applied_hash_aces), pae->prev_applied_entry_index);
351     ASSERT(prev_pae->next_applied_entry_index == old_index);
352     prev_pae->next_applied_entry_index = pae->next_applied_entry_index;
353     if (pae->next_applied_entry_index == ~0) {
354       /* it was a last entry we removed, update the pointer on the first one */
355       u32 head_index = find_head_applied_ace_index(applied_hash_aces, old_index);
356       DBG("UNAPPLY = index %d head index to update %d", old_index, head_index);
357       ASSERT(head_index != ~0);
358       applied_hash_ace_entry_t *head_pae = vec_elt_at_index((*applied_hash_aces), head_index);
359
360       ASSERT(head_pae->tail_applied_entry_index == old_index);
361       head_pae->tail_applied_entry_index = pae->prev_applied_entry_index;
362     } else {
363       applied_hash_ace_entry_t *next_pae = vec_elt_at_index((*applied_hash_aces), pae->next_applied_entry_index);
364       next_pae->prev_applied_entry_index = pae->prev_applied_entry_index;
365     }
366   } else {
367     /* It was the first entry. We need either to reset the hash entry or delete it */
368     if (pae->next_applied_entry_index != ~0) {
369       /* the next element becomes the new first one, so needs the tail pointer to be set */
370       applied_hash_ace_entry_t *next_pae = vec_elt_at_index((*applied_hash_aces), pae->next_applied_entry_index);
371       ASSERT(pae->tail_applied_entry_index != ~0);
372       next_pae->tail_applied_entry_index = pae->tail_applied_entry_index;
373       DBG("Resetting the hash table entry from %d to %d, setting tail index to %d", old_index, pae->next_applied_entry_index, pae->tail_applied_entry_index);
374       /* unlink from the next element */
375       next_pae->prev_applied_entry_index = ~0;
376       add_del_hashtable_entry(am, lc_index,
377                               applied_hash_aces, pae->next_applied_entry_index, 1);
378     } else {
379       /* no next entry, so just delete the entry in the hash table */
380       add_del_hashtable_entry(am, lc_index,
381                               applied_hash_aces, old_index, 0);
382     }
383   }
384   /* invalidate the old entry */
385   pae->prev_applied_entry_index = ~0;
386   pae->next_applied_entry_index = ~0;
387   pae->tail_applied_entry_index = ~0;
388 }
389
390
391 static void
392 hash_acl_build_applied_lookup_bitmap(acl_main_t *am, u32 lc_index)
393 {
394   int i;
395   uword *new_lookup_bitmap = 0;
396
397   applied_hash_acl_info_t **applied_hash_acls = &am->applied_hash_acl_info_by_lc_index;
398   vec_validate((*applied_hash_acls), lc_index);
399   applied_hash_acl_info_t *pal = vec_elt_at_index((*applied_hash_acls), lc_index);
400
401   for(i=0; i < vec_len(pal->applied_acls); i++) {
402     u32 a_acl_index = *vec_elt_at_index((pal->applied_acls), i);
403     hash_acl_info_t *ha = vec_elt_at_index(am->hash_acl_infos, a_acl_index);
404     DBG("Update bitmask = %U or %U (acl_index %d)\n", format_bitmap_hex, new_lookup_bitmap,
405           format_bitmap_hex, ha->mask_type_index_bitmap, a_acl_index);
406     new_lookup_bitmap = clib_bitmap_or(new_lookup_bitmap,
407                                        ha->mask_type_index_bitmap);
408   }
409   uword *old_lookup_bitmap = pal->mask_type_index_bitmap;
410   pal->mask_type_index_bitmap = new_lookup_bitmap;
411   clib_bitmap_free(old_lookup_bitmap);
412 }
413
414 void
415 hash_acl_unapply(acl_main_t *am, u32 lc_index, int acl_index)
416 {
417   int i;
418
419   DBG0("HASH ACL unapply: lc_index %d acl %d", lc_index, acl_index);
420   applied_hash_acl_info_t **applied_hash_acls = &am->applied_hash_acl_info_by_lc_index;
421   applied_hash_acl_info_t *pal = vec_elt_at_index((*applied_hash_acls), lc_index);
422
423   hash_acl_info_t *ha = vec_elt_at_index(am->hash_acl_infos, acl_index);
424   u32 **hash_acl_applied_lc_index = &ha->lc_index_list;
425
426   /* remove this acl# from the list of applied hash acls */
427   u32 index = vec_search(pal->applied_acls, acl_index);
428   if (index == ~0) {
429     clib_warning("BUG: trying to unapply unapplied acl_index %d on lc_index %d, according to lc",
430                  acl_index, lc_index);
431     return;
432   }
433   vec_del1(pal->applied_acls, index);
434
435   u32 index2 = vec_search((*hash_acl_applied_lc_index), lc_index);
436   if (index2 == ~0) {
437     clib_warning("BUG: trying to unapply twice acl_index %d on lc_index %d, according to h-acl info",
438                  acl_index, lc_index);
439     return;
440   }
441   vec_del1((*hash_acl_applied_lc_index), index2);
442
443   applied_hash_ace_entry_t **applied_hash_aces = get_applied_hash_aces(am, lc_index);
444
445   for(i=0; i < vec_len((*applied_hash_aces)); i++) {
446     if (vec_elt_at_index(*applied_hash_aces,i)->acl_index == acl_index) {
447       DBG("Found applied ACL#%d at applied index %d", acl_index, i);
448       break;
449     }
450   }
451   if (vec_len((*applied_hash_aces)) <= i) {
452     DBG("Did not find applied ACL#%d at lc_index %d", acl_index, lc_index);
453     /* we went all the way without finding any entries. Probably a list was empty. */
454     return;
455   }
456
457   void *oldheap = hash_acl_set_heap(am);
458   int base_offset = i;
459   int tail_offset = base_offset + vec_len(ha->rules);
460   int tail_len = vec_len((*applied_hash_aces)) - tail_offset;
461   DBG("base_offset: %d, tail_offset: %d, tail_len: %d", base_offset, tail_offset, tail_len);
462
463   for(i=0; i < vec_len(ha->rules); i ++) {
464     deactivate_applied_ace_hash_entry(am, lc_index,
465                                       applied_hash_aces, base_offset + i);
466   }
467   for(i=0; i < tail_len; i ++) {
468     /* move the entry at tail offset to base offset */
469     /* that is, from (tail_offset+i) -> (base_offset+i) */
470     DBG("UNAPPLY MOVE: lc_index %d, applied index %d -> %d", lc_index, tail_offset+i, base_offset + i);
471     move_applied_ace_hash_entry(am, lc_index, applied_hash_aces, tail_offset + i, base_offset + i);
472   }
473   /* trim the end of the vector */
474   _vec_len((*applied_hash_aces)) -= vec_len(ha->rules);
475
476   applied_hash_entries_analyze(am, applied_hash_aces);
477
478   /* After deletion we might not need some of the mask-types anymore... */
479   hash_acl_build_applied_lookup_bitmap(am, lc_index);
480   clib_mem_set_heap (oldheap);
481 }
482
483 /*
484  * Create the applied ACEs and update the hash table,
485  * taking into account that the ACL may not be the last
486  * in the vector of applied ACLs.
487  *
488  * For now, walk from the end of the vector and unapply the ACLs,
489  * then apply the one in question and reapply the rest.
490  */
491
492 void
493 hash_acl_reapply(acl_main_t *am, u32 lc_index, int acl_index)
494 {
495   acl_lookup_context_t *acontext = pool_elt_at_index(am->acl_lookup_contexts, lc_index);
496   u32 **applied_acls = &acontext->acl_indices;
497   int i;
498   int start_index = vec_search((*applied_acls), acl_index);
499
500   DBG0("Start index for acl %d in lc_index %d is %d", acl_index, lc_index, start_index);
501   /*
502    * This function is called after we find out the sw_if_index where ACL is applied.
503    * If the by-sw_if_index vector does not have the ACL#, then it's a bug.
504    */
505   ASSERT(start_index < vec_len(*applied_acls));
506
507   /* unapply all the ACLs at the tail side, up to the current one */
508   for(i = vec_len(*applied_acls) - 1; i > start_index; i--) {
509     hash_acl_unapply(am, lc_index, *vec_elt_at_index(*applied_acls, i));
510   }
511   for(i = start_index; i < vec_len(*applied_acls); i++) {
512     hash_acl_apply(am, lc_index, *vec_elt_at_index(*applied_acls, i), i);
513   }
514 }
515
516 static void
517 make_ip6_address_mask(ip6_address_t *addr, u8 prefix_len)
518 {
519   ip6_address_mask_from_width(addr, prefix_len);
520 }
521
522
523 /* Maybe should be moved into the core somewhere */
524 always_inline void
525 ip4_address_mask_from_width (ip4_address_t * a, u32 width)
526 {
527   int i, byte, bit, bitnum;
528   ASSERT (width <= 32);
529   memset (a, 0, sizeof (a[0]));
530   for (i = 0; i < width; i++)
531     {
532       bitnum = (7 - (i & 7));
533       byte = i / 8;
534       bit = 1 << bitnum;
535       a->as_u8[byte] |= bit;
536     }
537 }
538
539
540 static void
541 make_ip4_address_mask(ip4_address_t *addr, u8 prefix_len)
542 {
543   ip4_address_mask_from_width(addr, prefix_len);
544 }
545
546 static u8
547 make_port_mask(u16 *portmask, u16 port_first, u16 port_last)
548 {
549   if (port_first == port_last) {
550     *portmask = 0xffff;
551     /* single port is representable by masked value */
552     return 0;
553   }
554   if ((port_first == 0) && (port_last == 65535)) {
555     *portmask = 0;
556     /* wildcard port is representable by a masked value */
557     return 0;
558   }
559
560   /*
561    * For now match all the ports, later
562    * here might be a better optimization which would
563    * pick out bitmaskable portranges.
564    *
565    * However, adding a new mask type potentially
566    * adds a per-packet extra lookup, so the benefit is not clear.
567    */
568   *portmask = 0;
569   /* This port range can't be represented via bitmask exactly. */
570   return 1;
571 }
572
573 static void
574 make_mask_and_match_from_rule(fa_5tuple_t *mask, acl_rule_t *r, hash_ace_info_t *hi, int match_nonfirst_fragment)
575 {
576   memset(mask, 0, sizeof(*mask));
577   memset(&hi->match, 0, sizeof(hi->match));
578   hi->action = r->is_permit;
579
580   /* we will need to be matching based on lc_index and mask_type_index when applied */
581   mask->pkt.lc_index = ~0;
582   /* we will assign the match of mask_type_index later when we find it*/
583   mask->pkt.mask_type_index_lsb = ~0;
584
585   mask->pkt.is_ip6 = 1;
586   hi->match.pkt.is_ip6 = r->is_ipv6;
587   if (r->is_ipv6) {
588     make_ip6_address_mask(&mask->ip6_addr[0], r->src_prefixlen);
589     hi->match.ip6_addr[0] = r->src.ip6;
590     make_ip6_address_mask(&mask->ip6_addr[1], r->dst_prefixlen);
591     hi->match.ip6_addr[1] = r->dst.ip6;
592   } else {
593     memset(hi->match.l3_zero_pad, 0, sizeof(hi->match.l3_zero_pad));
594     make_ip4_address_mask(&mask->ip4_addr[0], r->src_prefixlen);
595     hi->match.ip4_addr[0] = r->src.ip4;
596     make_ip4_address_mask(&mask->ip4_addr[1], r->dst_prefixlen);
597     hi->match.ip4_addr[1] = r->dst.ip4;
598   }
599
600   if (r->proto != 0) {
601     mask->l4.proto = ~0; /* L4 proto needs to be matched */
602     hi->match.l4.proto = r->proto;
603     if (match_nonfirst_fragment) {
604       /* match the non-first fragments only */
605       mask->pkt.is_nonfirst_fragment = 1;
606       hi->match.pkt.is_nonfirst_fragment = 1;
607     } else {
608       /* Calculate the src/dst port masks and make the src/dst port matches accordingly */
609       hi->src_portrange_not_powerof2 = make_port_mask(&mask->l4.port[0], r->src_port_or_type_first, r->src_port_or_type_last);
610       hi->match.l4.port[0] = r->src_port_or_type_first & mask->l4.port[0];
611       hi->dst_portrange_not_powerof2 = make_port_mask(&mask->l4.port[1], r->dst_port_or_code_first, r->dst_port_or_code_last);
612       hi->match.l4.port[1] = r->dst_port_or_code_first & mask->l4.port[1];
613       /* L4 info must be valid in order to match */
614       mask->pkt.l4_valid = 1;
615       hi->match.pkt.l4_valid = 1;
616       /* And we must set the mask to check that it is an initial fragment */
617       mask->pkt.is_nonfirst_fragment = 1;
618       hi->match.pkt.is_nonfirst_fragment = 0;
619       if ((r->proto == IPPROTO_TCP) && (r->tcp_flags_mask != 0)) {
620         /* if we want to match on TCP flags, they must be masked off as well */
621         mask->pkt.tcp_flags = r->tcp_flags_mask;
622         hi->match.pkt.tcp_flags = r->tcp_flags_value;
623         /* and the flags need to be present within the packet being matched */
624         mask->pkt.tcp_flags_valid = 1;
625         hi->match.pkt.tcp_flags_valid = 1;
626       }
627     }
628   }
629   /* Sanitize the mask and the match */
630   u64 *pmask = (u64 *)mask;
631   u64 *pmatch = (u64 *)&hi->match;
632   int j;
633   for(j=0; j<6; j++) {
634     pmatch[j] = pmatch[j] & pmask[j];
635   }
636 }
637
638 static u32
639 find_mask_type_index(acl_main_t *am, fa_5tuple_t *mask)
640 {
641   ace_mask_type_entry_t *mte;
642   /* *INDENT-OFF* */
643   pool_foreach(mte, am->ace_mask_type_pool,
644   ({
645     if(memcmp(&mte->mask, mask, sizeof(*mask)) == 0)
646       return (mte - am->ace_mask_type_pool);
647   }));
648   /* *INDENT-ON* */
649   return ~0;
650 }
651
652 static u32
653 assign_mask_type_index(acl_main_t *am, fa_5tuple_t *mask)
654 {
655   u32 mask_type_index = find_mask_type_index(am, mask);
656   ace_mask_type_entry_t *mte;
657   if(~0 == mask_type_index) {
658     pool_get_aligned (am->ace_mask_type_pool, mte, CLIB_CACHE_LINE_BYTES);
659     mask_type_index = mte - am->ace_mask_type_pool;
660     clib_memcpy(&mte->mask, mask, sizeof(mte->mask));
661     mte->refcount = 0;
662     /*
663      * We can use only 16 bits, since in the match there is only u16 field.
664      * Realistically, once you go to 64K of mask types, it is a huge
665      * problem anyway, so we might as well stop half way.
666      */
667     ASSERT(mask_type_index < 32768);
668   }
669   mte = am->ace_mask_type_pool + mask_type_index;
670   mte->refcount++;
671   return mask_type_index;
672 }
673
674 static void
675 release_mask_type_index(acl_main_t *am, u32 mask_type_index)
676 {
677   ace_mask_type_entry_t *mte = pool_elt_at_index(am->ace_mask_type_pool, mask_type_index);
678   mte->refcount--;
679   if (mte->refcount == 0) {
680     /* we are not using this entry anymore */
681     pool_put(am->ace_mask_type_pool, mte);
682   }
683 }
684
685 int hash_acl_exists(acl_main_t *am, int acl_index)
686 {
687   if (acl_index >= vec_len(am->hash_acl_infos))
688     return 0;
689
690   hash_acl_info_t *ha = vec_elt_at_index(am->hash_acl_infos, acl_index);
691   return ha->hash_acl_exists;
692 }
693
694 void hash_acl_add(acl_main_t *am, int acl_index)
695 {
696   void *oldheap = hash_acl_set_heap(am);
697   DBG("HASH ACL add : %d", acl_index);
698   int i;
699   acl_list_t *a = &am->acls[acl_index];
700   vec_validate(am->hash_acl_infos, acl_index);
701   hash_acl_info_t *ha = vec_elt_at_index(am->hash_acl_infos, acl_index);
702   memset(ha, 0, sizeof(*ha));
703   ha->hash_acl_exists = 1;
704
705   /* walk the newly added ACL entries and ensure that for each of them there
706      is a mask type, increment a reference count for that mask type */
707   for(i=0; i < a->count; i++) {
708     hash_ace_info_t ace_info;
709     fa_5tuple_t mask;
710     memset(&ace_info, 0, sizeof(ace_info));
711     ace_info.acl_index = acl_index;
712     ace_info.ace_index = i;
713
714     make_mask_and_match_from_rule(&mask, &a->rules[i], &ace_info, 0);
715     ace_info.mask_type_index = assign_mask_type_index(am, &mask);
716     /* assign the mask type index for matching itself */
717     ace_info.match.pkt.mask_type_index_lsb = ace_info.mask_type_index;
718     DBG("ACE: %d mask_type_index: %d", i, ace_info.mask_type_index);
719     /* Ensure a given index is set in the mask type index bitmap for this ACL */
720     ha->mask_type_index_bitmap = clib_bitmap_set(ha->mask_type_index_bitmap, ace_info.mask_type_index, 1);
721     vec_add1(ha->rules, ace_info);
722     if (am->l4_match_nonfirst_fragment) {
723       /* add the second rule which matches the noninitial fragments with the respective mask */
724       make_mask_and_match_from_rule(&mask, &a->rules[i], &ace_info, 1);
725       ace_info.mask_type_index = assign_mask_type_index(am, &mask);
726       ace_info.match.pkt.mask_type_index_lsb = ace_info.mask_type_index;
727       DBG("ACE: %d (non-initial frags) mask_type_index: %d", i, ace_info.mask_type_index);
728       /* Ensure a given index is set in the mask type index bitmap for this ACL */
729       ha->mask_type_index_bitmap = clib_bitmap_set(ha->mask_type_index_bitmap, ace_info.mask_type_index, 1);
730       vec_add1(ha->rules, ace_info);
731     }
732   }
733   /*
734    * if an ACL is applied somewhere, fill the corresponding lookup data structures.
735    * We need to take care if the ACL is not the last one in the vector of ACLs applied to the interface.
736    */
737   if (acl_index < vec_len(am->lc_index_vec_by_acl)) {
738     u32 *lc_index;
739     vec_foreach(lc_index, am->lc_index_vec_by_acl[acl_index]) {
740       hash_acl_reapply(am, *lc_index, acl_index);
741     }
742   }
743   clib_mem_set_heap (oldheap);
744 }
745
746 void hash_acl_delete(acl_main_t *am, int acl_index)
747 {
748   void *oldheap = hash_acl_set_heap(am);
749   DBG0("HASH ACL delete : %d", acl_index);
750   /*
751    * If the ACL is applied somewhere, remove the references of it (call hash_acl_unapply)
752    * this is a different behavior from the linear lookup where an empty ACL is "deny all",
753    *
754    * However, following vpp-dev discussion the ACL that is referenced elsewhere
755    * should not be possible to delete, and the change adding this also adds
756    * the safeguards to that respect, so this is not a problem.
757    *
758    * The part to rememeber is that this routine is called in process of reapplication
759    * during the acl_add_replace() API call - the old acl ruleset is deleted, then
760    * the new one is added, without the change in the applied ACLs - so this case
761    * has to be handled.
762    */
763   hash_acl_info_t *ha = vec_elt_at_index(am->hash_acl_infos, acl_index);
764   u32 *lc_list_copy = 0;
765   {
766     u32 *lc_index;
767     lc_list_copy = vec_dup(ha->lc_index_list);
768     vec_foreach(lc_index, lc_list_copy) {
769       hash_acl_unapply(am, *lc_index, acl_index);
770     }
771     vec_free(lc_list_copy);
772   }
773
774   /* walk the mask types for the ACL about-to-be-deleted, and decrease
775    * the reference count, possibly freeing up some of them */
776   int i;
777   for(i=0; i < vec_len(ha->rules); i++) {
778     release_mask_type_index(am, ha->rules[i].mask_type_index);
779   }
780   clib_bitmap_free(ha->mask_type_index_bitmap);
781   ha->hash_acl_exists = 0;
782   vec_free(ha->rules);
783   clib_mem_set_heap (oldheap);
784 }
785
786
787 void
788 show_hash_acl_hash (vlib_main_t * vm, acl_main_t *am, u32 verbose)
789 {
790   vlib_cli_output(vm, "\nACL lookup hash table:\n%U\n",
791                   BV (format_bihash), &am->acl_lookup_hash, verbose);
792 }
793
794 void
795 acl_plugin_show_tables_mask_type (void)
796 {
797   acl_main_t *am = &acl_main;
798   vlib_main_t *vm = am->vlib_main;
799   ace_mask_type_entry_t *mte;
800
801   vlib_cli_output (vm, "Mask-type entries:");
802     /* *INDENT-OFF* */
803     pool_foreach(mte, am->ace_mask_type_pool,
804     ({
805       vlib_cli_output(vm, "     %3d: %016llx %016llx %016llx %016llx %016llx %016llx  refcount %d",
806                     mte - am->ace_mask_type_pool,
807                     mte->mask.kv.key[0], mte->mask.kv.key[1], mte->mask.kv.key[2],
808                     mte->mask.kv.key[3], mte->mask.kv.key[4], mte->mask.kv.value, mte->refcount);
809     }));
810     /* *INDENT-ON* */
811 }
812
813 void
814 acl_plugin_show_tables_acl_hash_info (u32 acl_index)
815 {
816   acl_main_t *am = &acl_main;
817   vlib_main_t *vm = am->vlib_main;
818   u32 i, j;
819   u64 *m;
820   vlib_cli_output (vm, "Mask-ready ACL representations\n");
821   for (i = 0; i < vec_len (am->hash_acl_infos); i++)
822     {
823       if ((acl_index != ~0) && (acl_index != i))
824         {
825           continue;
826         }
827       hash_acl_info_t *ha = &am->hash_acl_infos[i];
828       vlib_cli_output (vm, "acl-index %u bitmask-ready layout\n", i);
829       vlib_cli_output (vm, "  applied lc_index list: %U\n",
830                        format_vec32, ha->lc_index_list, "%d");
831       vlib_cli_output (vm, "  mask type index bitmap: %U\n",
832                        format_bitmap_hex, ha->mask_type_index_bitmap);
833       for (j = 0; j < vec_len (ha->rules); j++)
834         {
835           hash_ace_info_t *pa = &ha->rules[j];
836           m = (u64 *) & pa->match;
837           vlib_cli_output (vm,
838                            "    %4d: %016llx %016llx %016llx %016llx %016llx %016llx mask index %d acl %d rule %d action %d src/dst portrange not ^2: %d,%d\n",
839                            j, m[0], m[1], m[2], m[3], m[4], m[5],
840                            pa->mask_type_index, pa->acl_index, pa->ace_index,
841                            pa->action, pa->src_portrange_not_powerof2,
842                            pa->dst_portrange_not_powerof2);
843         }
844     }
845 }
846
847 void
848 acl_plugin_print_pae (vlib_main_t * vm, int j, applied_hash_ace_entry_t * pae)
849 {
850   vlib_cli_output (vm,
851                    "    %4d: acl %d rule %d action %d bitmask-ready rule %d next %d prev %d tail %d hitcount %lld",
852                    j, pae->acl_index, pae->ace_index, pae->action,
853                    pae->hash_ace_info_index, pae->next_applied_entry_index,
854                    pae->prev_applied_entry_index,
855                    pae->tail_applied_entry_index, pae->hitcount);
856 }
857
858 void
859 acl_plugin_show_tables_applied_info (u32 lc_index)
860 {
861   acl_main_t *am = &acl_main;
862   vlib_main_t *vm = am->vlib_main;
863   u32 lci, j;
864   vlib_cli_output (vm, "Applied lookup entries for lookup contexts");
865
866   for (lci = 0;
867        (lci < vec_len(am->applied_hash_acl_info_by_lc_index)); lci++)
868     {
869       if ((lc_index != ~0) && (lc_index != lci))
870         {
871           continue;
872         }
873       vlib_cli_output (vm, "lc_index %d:", lci);
874       if (lci < vec_len (am->applied_hash_acl_info_by_lc_index))
875         {
876           applied_hash_acl_info_t *pal =
877             &am->applied_hash_acl_info_by_lc_index[lci];
878           vlib_cli_output (vm, "  lookup mask_type_index_bitmap: %U",
879                            format_bitmap_hex, pal->mask_type_index_bitmap);
880           vlib_cli_output (vm, "  applied acls: %U", format_vec32,
881                            pal->applied_acls, "%d");
882         }
883       if (lci < vec_len (am->hash_entry_vec_by_lc_index))
884         {
885           vlib_cli_output (vm, "  lookup applied entries:");
886           for (j = 0;
887                j < vec_len (am->hash_entry_vec_by_lc_index[lci]);
888                j++)
889             {
890               acl_plugin_print_pae (vm, j,
891                                     &am->hash_entry_vec_by_lc_index
892                                     [lci][j]);
893             }
894         }
895     }
896 }
897
898 void
899 acl_plugin_show_tables_bihash (u32 show_bihash_verbose)
900 {
901   acl_main_t *am = &acl_main;
902   vlib_main_t *vm = am->vlib_main;
903   show_hash_acl_hash (vm, am, show_bihash_verbose);
904 }
905