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