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