027dabd0e6a083eb1663c75587e9b1a360de3848
[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     if (pae->next_applied_entry_index == ~0) {
386       /* it was a last entry we removed, update the pointer on the first one */
387       u32 an_index = pae->prev_applied_entry_index;
388       applied_hash_ace_entry_t *head_pae = &((*applied_hash_aces)[pae->prev_applied_entry_index]);
389       while(!head_pae->is_first_entry) {
390         an_index = head_pae->prev_applied_entry_index;
391         head_pae = &((*applied_hash_aces)[an_index]);
392       }
393       ASSERT(head_pae->prev_applied_entry_index == old_index);
394       head_pae->prev_applied_entry_index = pae->prev_applied_entry_index;
395     }
396   } else {
397     /* It was the first entry. We need either to reset the hash entry or delete it */
398     pae->is_first_entry = 0;
399     if (pae->next_applied_entry_index != ~0) {
400       /* a custom case of relinking for the first node, with the tail not forward linked to it */
401       applied_hash_ace_entry_t *next_pae = &((*applied_hash_aces)[pae->next_applied_entry_index]);
402       /* this is the tail the new head should be aware of */
403       next_pae->prev_applied_entry_index = pae->prev_applied_entry_index;
404       next_pae->is_first_entry = 1;
405
406       add_del_hashtable_entry(am, sw_if_index, is_input,
407                               applied_hash_aces, pae->next_applied_entry_index, 1);
408     } else {
409       /* no next entry, so just delete the entry in the hash table */
410       add_del_hashtable_entry(am, sw_if_index, is_input,
411                               applied_hash_aces, old_index, 0);
412     }
413   }
414 }
415
416
417 static void
418 hash_acl_build_applied_lookup_bitmap(acl_main_t *am, u32 sw_if_index, u8 is_input)
419 {
420   int i;
421   uword *new_lookup_bitmap = 0;
422   u32 **applied_acls = is_input ? &am->input_acl_vec_by_sw_if_index[sw_if_index] :
423                                   &am->output_acl_vec_by_sw_if_index[sw_if_index];
424   applied_hash_acl_info_t **applied_hash_acls = is_input ? &am->input_applied_hash_acl_info_by_sw_if_index :
425                                                     &am->output_applied_hash_acl_info_by_sw_if_index;
426   applied_hash_acl_info_t *pal = &(*applied_hash_acls)[sw_if_index];
427   for(i=0; i < vec_len(*applied_acls); i++) {
428     u32 a_acl_index = (*applied_acls)[i];
429     hash_acl_info_t *ha = &am->hash_acl_infos[a_acl_index];
430     new_lookup_bitmap = clib_bitmap_or(new_lookup_bitmap,
431                                        ha->mask_type_index_bitmap);
432   }
433   uword *old_lookup_bitmap = pal->mask_type_index_bitmap;
434   pal->mask_type_index_bitmap = new_lookup_bitmap;
435   clib_bitmap_free(old_lookup_bitmap);
436 }
437
438 void
439 hash_acl_unapply(acl_main_t *am, u32 sw_if_index, u8 is_input, int acl_index)
440 {
441   int i;
442
443   DBG("HASH ACL unapply: sw_if_index %d is_input %d acl %d", sw_if_index, is_input, acl_index);
444   hash_acl_info_t *ha = &am->hash_acl_infos[acl_index];
445   applied_hash_ace_entry_t **applied_hash_aces = is_input ? &am->input_hash_entry_vec_by_sw_if_index[sw_if_index] :
446                                                     &am->output_hash_entry_vec_by_sw_if_index[sw_if_index];
447
448   for(i=0; i < vec_len((*applied_hash_aces)); i++) {
449     if ((*applied_hash_aces)[i].acl_index == acl_index) {
450       DBG("Found applied ACL#%d at applied index %d", acl_index, i);
451       break;
452     }
453   }
454   if (vec_len((*applied_hash_aces)) <= i) {
455     DBG("Did not find applied ACL#%d at sw_if_index %d", acl_index, sw_if_index);
456     /* we went all the way without finding any entries. Probably a list was empty. */
457     return;
458   }
459   int base_offset = i;
460   int tail_offset = base_offset + vec_len(ha->rules);
461   int tail_len = vec_len((*applied_hash_aces)) - tail_offset;
462   DBG("base_offset: %d, tail_offset: %d, tail_len: %d", base_offset, tail_offset, tail_len);
463
464   for(i=0; i < vec_len(ha->rules); i ++) {
465     DBG("UNAPPLY DEACTIVATE: sw_if_index %d is_input %d, applied index %d", sw_if_index, is_input, base_offset + i);
466     deactivate_applied_ace_hash_entry(am, sw_if_index, is_input,
467                                       applied_hash_aces, base_offset + i);
468   }
469   for(i=0; i < tail_len; i ++) {
470     /* move the entry at tail offset to base offset */
471     /* that is, from (tail_offset+i) -> (base_offset+i) */
472     DBG("UNAPPLY MOVE: sw_if_index %d is_input %d, applied index %d ->", sw_if_index, is_input, tail_offset+i, base_offset + i);
473     move_applied_ace_hash_entry(am, sw_if_index, is_input, applied_hash_aces, tail_offset + i, base_offset + i);
474   }
475   /* trim the end of the vector */
476   _vec_len((*applied_hash_aces)) -= vec_len(ha->rules);
477
478   applied_hash_entries_analyze(am, applied_hash_aces);
479
480   /* After deletion we might not need some of the mask-types anymore... */
481   hash_acl_build_applied_lookup_bitmap(am, sw_if_index, is_input);
482 }
483
484 /*
485  * Create the applied ACEs and update the hash table,
486  * taking into account that the ACL may not be the last
487  * in the vector of applied ACLs.
488  *
489  * For now, walk from the end of the vector and unapply the ACLs,
490  * then apply the one in question and reapply the rest.
491  */
492
493 void
494 hash_acl_reapply(acl_main_t *am, u32 sw_if_index, u8 is_input, int acl_index)
495 {
496   u32 **applied_acls = is_input ? &am->input_acl_vec_by_sw_if_index[sw_if_index] :
497                                   &am->output_acl_vec_by_sw_if_index[sw_if_index];
498   int i;
499   int start_index = vec_search((*applied_acls), acl_index);
500   /*
501    * This function is called after we find out the sw_if_index where ACL is applied.
502    * If the by-sw_if_index vector does not have the ACL#, then it's a bug.
503    */
504   ASSERT(start_index < vec_len(*applied_acls));
505
506   /* unapply all the ACLs till the current one */
507   for(i = vec_len(*applied_acls) - 1; i >= start_index; i--) {
508     hash_acl_unapply(am, sw_if_index, is_input, (*applied_acls)[i]);
509   }
510   for(i = start_index; i < vec_len(*applied_acls); i++) {
511     hash_acl_apply(am, sw_if_index, is_input, (*applied_acls)[i]);
512   }
513 }
514
515 static void
516 make_address_mask(ip46_address_t *addr, u8 is_ipv6, u8 prefix_len)
517 {
518   if (is_ipv6) {
519     ip6_address_mask_from_width(&addr->ip6, prefix_len);
520   } else {
521     /* FIXME: this may not be correct way */
522     ip6_address_mask_from_width(&addr->ip6, prefix_len + 3*32);
523     ip46_address_mask_ip4(addr);
524   }
525 }
526
527 static u8
528 make_port_mask(u16 *portmask, u16 port_first, u16 port_last)
529 {
530   if (port_first == port_last) {
531     *portmask = 0xffff;
532     /* single port is representable by masked value */
533     return 0;
534   }
535   if ((port_first == 0) && (port_last == 65535)) {
536     *portmask = 0;
537     /* wildcard port is representable by a masked value */
538     return 0;
539   }
540
541   /*
542    * For now match all the ports, later
543    * here might be a better optimization which would
544    * pick out bitmaskable portranges.
545    *
546    * However, adding a new mask type potentially
547    * adds a per-packet extra lookup, so the benefit is not clear.
548    */
549   *portmask = 0;
550   /* This port range can't be represented via bitmask exactly. */
551   return 1;
552 }
553
554 static void
555 make_mask_and_match_from_rule(fa_5tuple_t *mask, acl_rule_t *r, hash_ace_info_t *hi, int match_nonfirst_fragment)
556 {
557   memset(mask, 0, sizeof(*mask));
558   memset(&hi->match, 0, sizeof(hi->match));
559   hi->action = r->is_permit;
560
561   /* we will need to be matching based on sw_if_index, direction, and mask_type_index when applied */
562   mask->pkt.sw_if_index = ~0;
563   mask->pkt.is_input = 1;
564   /* we will assign the match of mask_type_index later when we find it*/
565   mask->pkt.mask_type_index_lsb = ~0;
566
567   mask->pkt.is_ip6 = 1;
568   hi->match.pkt.is_ip6 = r->is_ipv6;
569
570   make_address_mask(&mask->addr[0], r->is_ipv6, r->src_prefixlen);
571   hi->match.addr[0] = r->src;
572   make_address_mask(&mask->addr[1], r->is_ipv6, r->dst_prefixlen);
573   hi->match.addr[1] = r->dst;
574
575   if (r->proto != 0) {
576     mask->l4.proto = ~0; /* L4 proto needs to be matched */
577     hi->match.l4.proto = r->proto;
578     if (match_nonfirst_fragment) {
579       /* match the non-first fragments only */
580       mask->pkt.is_nonfirst_fragment = 1;
581       hi->match.pkt.is_nonfirst_fragment = 1;
582     } else {
583       /* Calculate the src/dst port masks and make the src/dst port matches accordingly */
584       hi->src_portrange_not_powerof2 = make_port_mask(&mask->l4.port[0], r->src_port_or_type_first, r->src_port_or_type_last);
585       hi->match.l4.port[0] = r->src_port_or_type_first & mask->l4.port[0];
586       hi->dst_portrange_not_powerof2 = make_port_mask(&mask->l4.port[1], r->dst_port_or_code_first, r->dst_port_or_code_last);
587       hi->match.l4.port[1] = r->dst_port_or_code_first & mask->l4.port[1];
588       /* L4 info must be valid in order to match */
589       mask->pkt.l4_valid = 1;
590       hi->match.pkt.l4_valid = 1;
591       /* And we must set the mask to check that it is an initial fragment */
592       mask->pkt.is_nonfirst_fragment = 1;
593       hi->match.pkt.is_nonfirst_fragment = 0;
594       if ((r->proto == IPPROTO_TCP) && (r->tcp_flags_mask != 0)) {
595         /* if we want to match on TCP flags, they must be masked off as well */
596         mask->pkt.tcp_flags = r->tcp_flags_mask;
597         hi->match.pkt.tcp_flags = r->tcp_flags_value;
598         /* and the flags need to be present within the packet being matched */
599         mask->pkt.tcp_flags_valid = 1;
600         hi->match.pkt.tcp_flags_valid = 1;
601       }
602     }
603   }
604   /* Sanitize the mask and the match */
605   u64 *pmask = (u64 *)mask;
606   u64 *pmatch = (u64 *)&hi->match;
607   int j;
608   for(j=0; j<6; j++) {
609     pmatch[j] = pmatch[j] & pmask[j];
610   }
611 }
612
613 static u32
614 find_mask_type_index(acl_main_t *am, fa_5tuple_t *mask)
615 {
616   ace_mask_type_entry_t *mte;
617   /* *INDENT-OFF* */
618   pool_foreach(mte, am->ace_mask_type_pool,
619   ({
620     if(memcmp(&mte->mask, mask, sizeof(*mask)) == 0)
621       return (mte - am->ace_mask_type_pool);
622   }));
623   /* *INDENT-ON* */
624   return ~0;
625 }
626
627 static u32
628 assign_mask_type_index(acl_main_t *am, fa_5tuple_t *mask)
629 {
630   u32 mask_type_index = find_mask_type_index(am, mask);
631   ace_mask_type_entry_t *mte;
632   if(~0 == mask_type_index) {
633     pool_get_aligned (am->ace_mask_type_pool, mte, CLIB_CACHE_LINE_BYTES);
634     mask_type_index = mte - am->ace_mask_type_pool;
635     clib_memcpy(&mte->mask, mask, sizeof(mte->mask));
636     mte->refcount = 0;
637     /*
638      * We can use only 16 bits, since in the match there is only u16 field.
639      * Realistically, once you go to 64K of mask types, it is a huge
640      * problem anyway, so we might as well stop half way.
641      */
642     ASSERT(mask_type_index < 32768);
643   }
644   mte = am->ace_mask_type_pool + mask_type_index;
645   mte->refcount++;
646   return mask_type_index;
647 }
648
649 static void
650 release_mask_type_index(acl_main_t *am, u32 mask_type_index)
651 {
652   ace_mask_type_entry_t *mte = &am->ace_mask_type_pool[mask_type_index];
653   mte->refcount--;
654   if (mte->refcount == 0) {
655     /* we are not using this entry anymore */
656     pool_put(am->ace_mask_type_pool, mte);
657   }
658 }
659
660 void hash_acl_add(acl_main_t *am, int acl_index)
661 {
662   DBG("HASH ACL add : %d", acl_index);
663   int i;
664   acl_list_t *a = &am->acls[acl_index];
665   vec_validate(am->hash_acl_infos, acl_index);
666   hash_acl_info_t *ha = &am->hash_acl_infos[acl_index];
667   memset(ha, 0, sizeof(*ha));
668
669   /* walk the newly added ACL entries and ensure that for each of them there
670      is a mask type, increment a reference count for that mask type */
671   for(i=0; i < a->count; i++) {
672     hash_ace_info_t ace_info;
673     fa_5tuple_t mask;
674     memset(&ace_info, 0, sizeof(ace_info));
675     ace_info.acl_index = acl_index;
676     ace_info.ace_index = i;
677
678     make_mask_and_match_from_rule(&mask, &a->rules[i], &ace_info, 0);
679     ace_info.mask_type_index = assign_mask_type_index(am, &mask);
680     /* assign the mask type index for matching itself */
681     ace_info.match.pkt.mask_type_index_lsb = ace_info.mask_type_index;
682     DBG("ACE: %d mask_type_index: %d", i, ace_info.mask_type_index);
683     /* Ensure a given index is set in the mask type index bitmap for this ACL */
684     ha->mask_type_index_bitmap = clib_bitmap_set(ha->mask_type_index_bitmap, ace_info.mask_type_index, 1);
685     vec_add1(ha->rules, ace_info);
686     if (am->l4_match_nonfirst_fragment) {
687       /* add the second rule which matches the noninitial fragments with the respective mask */
688       make_mask_and_match_from_rule(&mask, &a->rules[i], &ace_info, 1);
689       ace_info.mask_type_index = assign_mask_type_index(am, &mask);
690       ace_info.match.pkt.mask_type_index_lsb = ace_info.mask_type_index;
691       DBG("ACE: %d (non-initial frags) mask_type_index: %d", i, ace_info.mask_type_index);
692       /* Ensure a given index is set in the mask type index bitmap for this ACL */
693       ha->mask_type_index_bitmap = clib_bitmap_set(ha->mask_type_index_bitmap, ace_info.mask_type_index, 1);
694       vec_add1(ha->rules, ace_info);
695     }
696   }
697   /*
698    * if an ACL is applied somewhere, fill the corresponding lookup data structures.
699    * We need to take care if the ACL is not the last one in the vector of ACLs applied to the interface.
700    */
701   if (acl_index < vec_len(am->input_sw_if_index_vec_by_acl)) {
702     u32 *sw_if_index;
703     vec_foreach(sw_if_index, am->input_sw_if_index_vec_by_acl[acl_index]) {
704       hash_acl_reapply(am, *sw_if_index, 1, acl_index);
705     }
706   }
707   if (acl_index < vec_len(am->output_sw_if_index_vec_by_acl)) {
708     u32 *sw_if_index;
709     vec_foreach(sw_if_index, am->output_sw_if_index_vec_by_acl[acl_index]) {
710       hash_acl_reapply(am, *sw_if_index, 0, acl_index);
711     }
712   }
713 }
714
715 void hash_acl_delete(acl_main_t *am, int acl_index)
716 {
717   DBG("HASH ACL delete : %d", acl_index);
718   /*
719    * If the ACL is applied somewhere, remove the references of it (call hash_acl_unapply)
720    * this is a different behavior from the linear lookup where an empty ACL is "deny all",
721    *
722    * However, following vpp-dev discussion the ACL that is referenced elsewhere
723    * should not be possible to delete, and the change adding this also adds
724    * the safeguards to that respect, so this is not a problem.
725    */
726   if (acl_index < vec_len(am->input_sw_if_index_vec_by_acl)) {
727     u32 *sw_if_index;
728     vec_foreach(sw_if_index, am->input_sw_if_index_vec_by_acl[acl_index]) {
729       hash_acl_unapply(am, *sw_if_index, 1, acl_index);
730     }
731   }
732   if (acl_index < vec_len(am->output_sw_if_index_vec_by_acl)) {
733     u32 *sw_if_index;
734     vec_foreach(sw_if_index, am->output_sw_if_index_vec_by_acl[acl_index]) {
735       hash_acl_unapply(am, *sw_if_index, 0, acl_index);
736     }
737   }
738
739   /* walk the mask types for the ACL about-to-be-deleted, and decrease
740    * the reference count, possibly freeing up some of them */
741   int i;
742   hash_acl_info_t *ha = &am->hash_acl_infos[acl_index];
743   for(i=0; i < vec_len(ha->rules); i++) {
744     release_mask_type_index(am, ha->rules[i].mask_type_index);
745   }
746   clib_bitmap_free(ha->mask_type_index_bitmap);
747   vec_free(ha->rules);
748 }
749
750 u8
751 hash_multi_acl_match_5tuple (u32 sw_if_index, fa_5tuple_t * pkt_5tuple, int is_l2,
752                        int is_ip6, int is_input, u32 * acl_match_p,
753                        u32 * rule_match_p, u32 * trace_bitmap)
754 {
755   acl_main_t *am = &acl_main;
756   applied_hash_ace_entry_t **applied_hash_aces = is_input ? &am->input_hash_entry_vec_by_sw_if_index[sw_if_index] :
757                                                     &am->output_hash_entry_vec_by_sw_if_index[sw_if_index];
758   u32 match_index = multi_acl_match_get_applied_ace_index(am, pkt_5tuple);
759   if (match_index < vec_len((*applied_hash_aces))) {
760     applied_hash_ace_entry_t *pae = &((*applied_hash_aces)[match_index]);
761     *acl_match_p = pae->acl_index;
762     *rule_match_p = pae->ace_index;
763     return pae->action;
764   }
765   return 0;
766 }
767
768
769 void
770 show_hash_acl_hash (vlib_main_t * vm, acl_main_t *am, u32 verbose)
771 {
772   vlib_cli_output(vm, "\nACL lookup hash table:\n%U\n",
773                   BV (format_bihash), &am->acl_lookup_hash, verbose);
774 }