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