vppinfra: bihash improvements
[vpp.git] / src / vnet / l2 / l2_fib.c
1 /*
2  * l2_fib.c : layer 2 forwarding table (aka mac table)
3  *
4  * Copyright (c) 2013 Cisco and/or its affiliates.
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18
19 #include <vlib/vlib.h>
20 #include <vnet/vnet.h>
21 #include <vnet/pg/pg.h>
22 #include <vnet/ethernet/ethernet.h>
23 #include <vlib/cli.h>
24
25 #include <vppinfra/error.h>
26 #include <vppinfra/hash.h>
27 #include <vnet/l2/l2_input.h>
28 #include <vnet/l2/l2_fib.h>
29 #include <vnet/l2/l2_learn.h>
30 #include <vnet/l2/l2_bd.h>
31
32 #include <vppinfra/bihash_template.c>
33
34 #include <vlibmemory/api.h>
35 #include <vnet/vnet_msg_enum.h>
36
37 #define vl_typedefs             /* define message structures */
38 #include <vnet/vnet_all_api_h.h>
39 #undef vl_typedefs
40
41 #define vl_endianfun            /* define message structures */
42 #include <vnet/vnet_all_api_h.h>
43 #undef vl_endianfun
44
45 /**
46  * @file
47  * @brief Ethernet MAC Address FIB Table Management.
48  *
49  * The MAC Address forwarding table for bridge-domains is called the l2fib.
50  * Entries are added automatically as part of mac learning, but MAC Addresses
51  * entries can also be added manually.
52  *
53  */
54
55 l2fib_main_t l2fib_main;
56
57 u8 *
58 format_l2fib_entry_result_flags (u8 * s, va_list * args)
59 {
60   l2fib_entry_result_flags_t flags = va_arg (*args, int);
61
62   if (L2FIB_ENTRY_RESULT_FLAG_NONE == flags)
63     {
64       s = format (s, "none");
65     }
66   else
67     {
68 #define _(a,v,t) {                              \
69       if (flags & L2FIB_ENTRY_RESULT_FLAG_##a)  \
70         s = format (s, "%s ", t);               \
71     }
72       foreach_l2fib_entry_result_attr
73 #undef _
74     }
75   return (s);
76 }
77
78 static void
79 incr_mac_address (u8 * mac)
80 {
81   u64 tmp = *((u64 *) mac);
82   tmp = clib_net_to_host_u64 (tmp);
83   tmp += 1 << 16;               /* skip unused (least significant) octets */
84   tmp = clib_host_to_net_u64 (tmp);
85
86   clib_memcpy_fast (mac, &tmp, 6);
87 }
88
89 /** Format sw_if_index. If the value is ~0, use the text "N/A" */
90 u8 *
91 format_vnet_sw_if_index_name_with_NA (u8 * s, va_list * args)
92 {
93   vnet_main_t *vnm = va_arg (*args, vnet_main_t *);
94   u32 sw_if_index = va_arg (*args, u32);
95   if (sw_if_index == ~0)
96     return format (s, "N/A");
97
98   vnet_sw_interface_t *swif =
99     vnet_get_sw_interface_or_null (vnm, sw_if_index);
100   if (!swif)
101     return format (s, "Stale");
102
103   return format (s, "%U", format_vnet_sw_interface_name, vnm,
104                  vnet_get_sw_interface_or_null (vnm, sw_if_index));
105 }
106
107 typedef struct l2fib_dump_walk_ctx_t_
108 {
109   u32 bd_index;
110   l2fib_entry_key_t *l2fe_key;
111   l2fib_entry_result_t *l2fe_res;
112 } l2fib_dump_walk_ctx_t;
113
114 static int
115 l2fib_dump_walk_cb (BVT (clib_bihash_kv) * kvp, void *arg)
116 {
117   l2fib_dump_walk_ctx_t *ctx = arg;
118   l2fib_entry_result_t result;
119   l2fib_entry_key_t key;
120
121   key.raw = kvp->key;
122   result.raw = kvp->value;
123
124   if ((ctx->bd_index == ~0) || (ctx->bd_index == key.fields.bd_index))
125     {
126       vec_add1 (ctx->l2fe_key, key);
127       vec_add1 (ctx->l2fe_res, result);
128     }
129
130   return (BIHASH_WALK_CONTINUE);
131 }
132
133 void
134 l2fib_table_dump (u32 bd_index,
135                   l2fib_entry_key_t ** l2fe_key,
136                   l2fib_entry_result_t ** l2fe_res)
137 {
138   l2fib_main_t *msm = &l2fib_main;
139   l2fib_dump_walk_ctx_t ctx = {
140     .bd_index = bd_index,
141   };
142
143   BV (clib_bihash_foreach_key_value_pair)
144     (&msm->mac_table, l2fib_dump_walk_cb, &ctx);
145
146   *l2fe_key = ctx.l2fe_key;
147   *l2fe_res = ctx.l2fe_res;
148 }
149
150 typedef struct l2fib_show_walk_ctx_t_
151 {
152   u8 first_entry;
153   u8 verbose;
154   vlib_main_t *vm;
155   vnet_main_t *vnm;
156   u32 total_entries;
157   u32 bd_index;
158   u8 learn;
159   u8 add;
160   u8 now;
161 } l2fib_show_walk_ctx_t;
162
163 static int
164 l2fib_show_walk_cb (BVT (clib_bihash_kv) * kvp, void *arg)
165 {
166   l2fib_show_walk_ctx_t *ctx = arg;
167   l2_bridge_domain_t *bd_config;
168   l2fib_entry_result_t result;
169   l2fib_entry_key_t key;
170
171   if (ctx->verbose && ctx->first_entry)
172     {
173       ctx->first_entry = 0;
174       vlib_cli_output (ctx->vm,
175                        "%=19s%=7s%=7s%=8s%=9s%=7s%=7s%=5s%=30s",
176                        "Mac-Address", "BD-Idx", "If-Idx",
177                        "BSN-ISN", "Age(min)", "static", "filter",
178                        "bvi", "Interface-Name");
179     }
180
181   key.raw = kvp->key;
182   result.raw = kvp->value;
183   ctx->total_entries++;
184
185   if (ctx->verbose &&
186       ((ctx->bd_index >> 31) || (ctx->bd_index == key.fields.bd_index)))
187     {
188       u8 *s = NULL;
189
190       if (ctx->learn && l2fib_entry_result_is_set_AGE_NOT (&result))
191         return (BIHASH_WALK_CONTINUE);  /* skip provisioned macs */
192
193       if (ctx->add && !l2fib_entry_result_is_set_AGE_NOT (&result))
194         return (BIHASH_WALK_CONTINUE);  /* skip learned macs */
195
196       bd_config = vec_elt_at_index (l2input_main.bd_configs,
197                                     key.fields.bd_index);
198
199       if (l2fib_entry_result_is_set_AGE_NOT (&result))
200         s = format (s, "no");
201       else if (bd_config->mac_age == 0)
202         s = format (s, "-");
203       else
204         {
205           i16 delta = ctx->now - result.fields.timestamp;
206           delta += delta < 0 ? 256 : 0;
207           s = format (s, "%d", delta);
208         }
209
210       vlib_cli_output (ctx->vm,
211                        "%=19U%=7d%=7d %3d/%-3d%=9v%=7s%=7s%=5s%=30U",
212                        format_ethernet_address, key.fields.mac,
213                        key.fields.bd_index,
214                        result.fields.sw_if_index == ~0
215                        ? -1 : result.fields.sw_if_index,
216                        result.fields.sn.bd, result.fields.sn.swif, s,
217                        l2fib_entry_result_is_set_STATIC (&result) ? "*" : "-",
218                        l2fib_entry_result_is_set_FILTER (&result) ? "*" : "-",
219                        l2fib_entry_result_is_set_BVI (&result) ? "*" : "-",
220                        format_vnet_sw_if_index_name_with_NA,
221                        ctx->vnm, result.fields.sw_if_index);
222       vec_free (s);
223     }
224
225   return (BIHASH_WALK_CONTINUE);
226 }
227
228 /** Display the contents of the l2fib. */
229 static clib_error_t *
230 show_l2fib (vlib_main_t * vm,
231             unformat_input_t * input, vlib_cli_command_t * cmd)
232 {
233   bd_main_t *bdm = &bd_main;
234   l2fib_main_t *msm = &l2fib_main;
235   u8 raw = 0;
236   u32 bd_id;
237   l2fib_show_walk_ctx_t ctx = {
238     .first_entry = 1,
239     .bd_index = ~0,
240     .now = (u8) (vlib_time_now (vm) / 60),
241     .vm = vm,
242     .vnm = msm->vnet_main,
243   };
244
245   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
246     {
247       if (unformat (input, "raw"))
248         {
249           raw = 1;
250           ctx.verbose = 0;
251           break;
252         }
253       else if (unformat (input, "verbose"))
254         ctx.verbose = 1;
255       else if (unformat (input, "all"))
256         ctx.verbose = 1;
257       else if (unformat (input, "bd_index %d", &ctx.bd_index))
258         ctx.verbose = 1;
259       else if (unformat (input, "learn"))
260         {
261           ctx.add = 0;
262           ctx.learn = 1;
263           ctx.verbose = 1;
264         }
265       else if (unformat (input, "add"))
266         {
267           ctx.learn = 0;
268           ctx.add = 1;
269           ctx.verbose = 1;
270         }
271       else if (unformat (input, "bd_id %d", &bd_id))
272         {
273           uword *p = hash_get (bdm->bd_index_by_bd_id, bd_id);
274           if (p)
275             {
276               ctx.verbose = 1;
277               ctx.bd_index = p[0];
278             }
279           else
280             return clib_error_return (0,
281                                       "bridge domain id %d doesn't exist\n",
282                                       bd_id);
283         }
284       else
285         break;
286     }
287
288   BV (clib_bihash_foreach_key_value_pair)
289     (&msm->mac_table, l2fib_show_walk_cb, &ctx);
290
291   if (ctx.total_entries == 0)
292     vlib_cli_output (vm, "no l2fib entries");
293   else
294     {
295       l2learn_main_t *lm = &l2learn_main;
296       vlib_cli_output (vm, "L2FIB total/learned entries: %d/%d  "
297                        "Last scan time: %.4esec  Learn limit: %d ",
298                        ctx.total_entries, lm->global_learn_count,
299                        msm->age_scan_duration, lm->global_learn_limit);
300       if (lm->client_pid)
301         vlib_cli_output (vm, "L2MAC events client PID: %d  "
302                          "Last e-scan time: %.4esec  Delay: %.2esec  "
303                          "Max macs in event: %d",
304                          lm->client_pid, msm->evt_scan_duration,
305                          msm->event_scan_delay, msm->max_macs_in_event);
306     }
307
308   if (raw)
309     vlib_cli_output (vm, "Raw Hash Table:\n%U\n",
310                      BV (format_bihash), &msm->mac_table, 1 /* verbose */ );
311
312   return 0;
313 }
314
315 /*?
316  * This command displays the MAC Address entries of the L2 FIB table.
317  * Output can be filtered to just get the number of MAC Addresses or display
318  * each MAC Address for all bridge domains or just a single bridge domain.
319  *
320  * @cliexpar
321  * Example of how to display the number of MAC Address entries in the L2
322  * FIB table:
323  * @cliexstart{show l2fib}
324  * 3 l2fib entries
325  * @cliexend
326  * Example of how to display all the MAC Address entries in the L2
327  * FIB table:
328  * @cliexstart{show l2fib all}
329  *     Mac Address     BD Idx           Interface           Index  static  filter  bvi  refresh  timestamp
330  *  52:54:00:53:18:33    1      GigabitEthernet0/8/0.200      3       0       0     0      0         0
331  *  52:54:00:53:18:55    1      GigabitEthernet0/8/0.200      3       1       0     0      0         0
332  *  52:54:00:53:18:77    1                 N/A                -1      1       1     0      0         0
333  * 3 l2fib entries
334  * @cliexend
335 ?*/
336 /* *INDENT-OFF* */
337 VLIB_CLI_COMMAND (show_l2fib_cli, static) = {
338   .path = "show l2fib",
339   .short_help = "show l2fib [all] | [bd_id <nn> | bd_index <nn>] [learn | add] | [raw]",
340   .function = show_l2fib,
341 };
342 /* *INDENT-ON* */
343
344
345 /* Remove all entries from the l2fib */
346 void
347 l2fib_clear_table (void)
348 {
349   l2fib_main_t *mp = &l2fib_main;
350
351   /* Remove all entries */
352   BV (clib_bihash_free) (&mp->mac_table);
353   BV (clib_bihash_init) (&mp->mac_table, "l2fib mac table",
354                          L2FIB_NUM_BUCKETS, L2FIB_MEMORY_SIZE);
355   l2learn_main.global_learn_count = 0;
356 }
357
358 /** Clear all entries in L2FIB.
359  * @TODO: Later we may want a way to remove only the non-static entries
360  */
361 static clib_error_t *
362 clear_l2fib (vlib_main_t * vm,
363              unformat_input_t * input, vlib_cli_command_t * cmd)
364 {
365   l2fib_clear_table ();
366   return 0;
367 }
368
369 /*?
370  * This command clears all the MAC Address entries from the L2 FIB table.
371  *
372  * @cliexpar
373  * Example of how to clear the L2 FIB Table:
374  * @cliexcmd{clear l2fib}
375  * Example to show the L2 FIB Table has been cleared:
376  * @cliexstart{show l2fib verbose}
377  * no l2fib entries
378  * @cliexend
379 ?*/
380 /* *INDENT-OFF* */
381 VLIB_CLI_COMMAND (clear_l2fib_cli, static) = {
382   .path = "clear l2fib",
383   .short_help = "clear l2fib",
384   .function = clear_l2fib,
385 };
386 /* *INDENT-ON* */
387
388 static inline l2fib_seq_num_t
389 l2fib_cur_seq_num (u32 bd_index, u32 sw_if_index)
390 {
391   l2_bridge_domain_t *bd_config = l2input_bd_config (bd_index);
392   /* *INDENT-OFF* */
393   return (l2fib_seq_num_t) {
394     .swif = *l2fib_swif_seq_num (sw_if_index),
395     .bd = bd_config->seq_num,
396   };
397   /* *INDENT-ON* */
398 }
399
400 /**
401  * Add an entry to the l2fib.
402  * If the entry already exists then overwrite it
403  */
404 void
405 l2fib_add_entry (const u8 * mac, u32 bd_index,
406                  u32 sw_if_index, l2fib_entry_result_flags_t flags)
407 {
408   l2fib_entry_key_t key;
409   l2fib_entry_result_t result;
410   __attribute__ ((unused)) u32 bucket_contents;
411   l2fib_main_t *fm = &l2fib_main;
412   l2learn_main_t *lm = &l2learn_main;
413   BVT (clib_bihash_kv) kv;
414
415   /* set up key */
416   key.raw = l2fib_make_key (mac, bd_index);
417   kv.key = key.raw;
418
419   /* check if entry already exist */
420   if (BV (clib_bihash_search) (&fm->mac_table, &kv, &kv))
421     {
422       /* decrement counter if overwriting a learned mac  */
423       result.raw = kv.value;
424       if ((!l2fib_entry_result_is_set_AGE_NOT (&result))
425           && (lm->global_learn_count))
426         lm->global_learn_count--;
427     }
428
429   /* set up result */
430   result.raw = 0;               /* clear all fields */
431   result.fields.sw_if_index = sw_if_index;
432   result.fields.flags = flags;
433
434   /* no aging for provisioned entry */
435   l2fib_entry_result_set_AGE_NOT (&result);
436
437   kv.value = result.raw;
438
439   BV (clib_bihash_add_del) (&fm->mac_table, &kv, 1 /* is_add */ );
440 }
441
442 /**
443  * Add an entry to the L2FIB.
444  * The CLI format is:
445  *    l2fib add <mac> <bd> <intf> [static] [bvi]
446  *    l2fib add <mac> <bd> filter
447  * Note that filter and bvi entries are always static
448  */
449 static clib_error_t *
450 l2fib_add (vlib_main_t * vm,
451            unformat_input_t * input, vlib_cli_command_t * cmd)
452 {
453   bd_main_t *bdm = &bd_main;
454   vnet_main_t *vnm = vnet_get_main ();
455   clib_error_t *error = 0;
456   u8 mac[6];
457   u32 bd_id;
458   u32 bd_index;
459   u32 sw_if_index = ~0;
460   uword *p;
461   l2fib_entry_result_flags_t flags;
462
463   flags = L2FIB_ENTRY_RESULT_FLAG_NONE;
464
465   if (!unformat (input, "%U", unformat_ethernet_address, mac))
466     {
467       error = clib_error_return (0, "expected mac address `%U'",
468                                  format_unformat_error, input);
469       goto done;
470     }
471
472   if (!unformat (input, "%d", &bd_id))
473     {
474       error = clib_error_return (0, "expected bridge domain ID `%U'",
475                                  format_unformat_error, input);
476       goto done;
477     }
478
479   p = hash_get (bdm->bd_index_by_bd_id, bd_id);
480   if (!p)
481     {
482       error = clib_error_return (0, "bridge domain ID %d invalid", bd_id);
483       goto done;
484     }
485   bd_index = p[0];
486
487   if (unformat (input, "filter"))
488     {
489       l2fib_add_filter_entry (mac, bd_index);
490       return 0;
491     }
492
493   if (!unformat_user (input, unformat_vnet_sw_interface, vnm, &sw_if_index))
494     {
495       error = clib_error_return (0, "unknown interface `%U'",
496                                  format_unformat_error, input);
497       goto done;
498     }
499
500   if (unformat (input, "static"))
501     flags |= L2FIB_ENTRY_RESULT_FLAG_STATIC;
502   else if (unformat (input, "bvi"))
503     flags |= (L2FIB_ENTRY_RESULT_FLAG_STATIC | L2FIB_ENTRY_RESULT_FLAG_BVI);
504
505   if (vec_len (l2input_main.configs) <= sw_if_index)
506     {
507       error = clib_error_return (0, "Interface sw_if_index %d not in L2 mode",
508                                  sw_if_index);
509       goto done;
510     }
511
512   l2fib_add_entry (mac, bd_index, sw_if_index, flags);
513
514 done:
515   return error;
516 }
517
518 /*?
519  * This command adds a MAC Address entry to the L2 FIB table
520  * of an existing bridge-domain. The MAC Address can be static
521  * or dynamic. This command also allows a filter to be added,
522  * such that packets with given MAC Addresses (source mac or
523  * destination mac match) are dropped.
524  *
525  * @cliexpar
526  * Example of how to add a dynamic MAC Address entry to the L2 FIB table
527  * of a bridge-domain (where 200 is the bridge-domain-id):
528  * @cliexcmd{l2fib add 52:54:00:53:18:33 200 GigabitEthernet0/8/0.200}
529  * Example of how to add a static MAC Address entry to the L2 FIB table
530  * of a bridge-domain (where 200 is the bridge-domain-id):
531  * @cliexcmd{l2fib add 52:54:00:53:18:55 200 GigabitEthernet0/8/0.200 static}
532  * Example of how to add a filter such that a packet with the given MAC
533  * Address will be dropped in a given bridge-domain (where 200 is the
534  * bridge-domain-id):
535  * @cliexcmd{l2fib add 52:54:00:53:18:77 200 filter}
536  * Example of show command of the provisioned MAC Addresses and filters:
537  * @cliexstart{show l2fib verbose}
538  *     Mac Address     BD Idx           Interface           Index  static  filter  bvi  refresh  timestamp
539  *  52:54:00:53:18:33    1      GigabitEthernet0/8/0.200      3       0       0     0      0         0
540  *  52:54:00:53:18:55    1      GigabitEthernet0/8/0.200      3       1       0     0      0         0
541  *  52:54:00:53:18:77    1                 N/A                -1      1       1     0      0         0
542  * 3 l2fib entries
543  * @cliexend
544 ?*/
545 /* *INDENT-OFF* */
546 VLIB_CLI_COMMAND (l2fib_add_cli, static) = {
547   .path = "l2fib add",
548   .short_help = "l2fib add <mac> <bridge-domain-id> filter | <intf> [static | bvi]",
549   .function = l2fib_add,
550 };
551 /* *INDENT-ON* */
552
553
554 static clib_error_t *
555 l2fib_test_command_fn (vlib_main_t * vm,
556                        unformat_input_t * input, vlib_cli_command_t * cmd)
557 {
558   clib_error_t *error = 0;
559   u8 mac[6], save_mac[6];
560   u32 bd_index = 0;
561   u32 sw_if_index = 8;
562   u32 is_add = 0;
563   u32 is_del = 0;
564   u32 is_check = 0;
565   u32 count = 1;
566   int mac_set = 0;
567   int i;
568
569   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
570     {
571       if (unformat (input, "mac %U", unformat_ethernet_address, mac))
572         mac_set = 1;
573       else if (unformat (input, "add"))
574         is_add = 1;
575       else if (unformat (input, "del"))
576         is_del = 1;
577       else if (unformat (input, "check"))
578         is_check = 1;
579       else if (unformat (input, "count %d", &count))
580         ;
581       else
582         break;
583     }
584
585   if (mac_set == 0)
586     return clib_error_return (0, "mac not set");
587
588   if (is_add == 0 && is_del == 0 && is_check == 0)
589     return clib_error_return (0,
590                               "noop: pick at least one of (add,del,check)");
591
592   clib_memcpy_fast (save_mac, mac, 6);
593
594   if (is_add)
595     {
596       for (i = 0; i < count; i++)
597         {
598           l2fib_add_entry (mac, bd_index, sw_if_index,
599                            L2FIB_ENTRY_RESULT_FLAG_NONE);
600           incr_mac_address (mac);
601         }
602     }
603
604   if (is_check)
605     {
606       BVT (clib_bihash_kv) kv;
607       l2fib_main_t *mp = &l2fib_main;
608
609       clib_memcpy_fast (mac, save_mac, 6);
610
611       for (i = 0; i < count; i++)
612         {
613           kv.key = l2fib_make_key (mac, bd_index);
614           if (BV (clib_bihash_search) (&mp->mac_table, &kv, &kv))
615             {
616               clib_warning ("key %U AWOL", format_ethernet_address, mac);
617               break;
618             }
619           incr_mac_address (mac);
620         }
621     }
622
623   if (is_del)
624     {
625       clib_memcpy_fast (mac, save_mac, 6);
626
627       for (i = 0; i < count; i++)
628         {
629           l2fib_del_entry (mac, bd_index, 0);
630           incr_mac_address (mac);
631         }
632     }
633
634   return error;
635 }
636
637 /*?
638  * The set of '<em>test l2fib</em>' commands allow the L2 FIB table of the default
639  * bridge domain (bridge-domain-id of 0) to be modified.
640  *
641  * @cliexpar
642  * @parblock
643  * Example of how to add a set of 4 sequential MAC Address entries to L2
644  * FIB table of the default bridge-domain:
645  * @cliexcmd{test l2fib add mac 52:54:00:53:00:00 count 4}
646  *
647  * Show the set of 4 sequential MAC Address entries that were added:
648  * @cliexstart{show l2fib verbose}
649  *     Mac Address     BD Idx           Interface           Index  static  filter  bvi  refresh  timestamp
650  * 52:54:00:53:00:00    0       GigabitEthernet0/8/0.300     8       0       0     0      0         0
651  * 52:54:00:53:00:01    0       GigabitEthernet0/8/0.300     8       0       0     0      0         0
652  * 52:54:00:53:00:03    0       GigabitEthernet0/8/0.300     8       0       0     0      0         0
653  * 52:54:00:53:00:02    0       GigabitEthernet0/8/0.300     8       0       0     0      0         0
654  * 4 l2fib entries
655  * @cliexend
656  *
657  * Example of how to check that the set of 4 sequential MAC Address
658  * entries were added to L2 FIB table of the default
659  * bridge-domain. Used a count of 5 to produce an error:
660  *
661  * @cliexcmd{test l2fib check mac 52:54:00:53:00:00 count 5}
662  * The output of the check command is in the log files. Log file
663  * location may vary based on your OS and Version:
664  *
665  * <b><em># tail -f /var/log/messages | grep l2fib_test_command_fn</em></b>
666  *
667  * Sep  7 17:15:24 localhost vnet[4952]: l2fib_test_command_fn:446: key 52:54:00:53:00:04 AWOL
668  *
669  * Example of how to delete a set of 4 sequential MAC Address entries
670  * from L2 FIB table of the default bridge-domain:
671  * @cliexcmd{test l2fib del mac 52:54:00:53:00:00 count 4}
672  * @endparblock
673 ?*/
674 /* *INDENT-OFF* */
675 VLIB_CLI_COMMAND (l2fib_test_command, static) = {
676   .path = "test l2fib",
677   .short_help = "test l2fib [add|del|check] mac <base-addr> count <nn>",
678   .function = l2fib_test_command_fn,
679 };
680 /* *INDENT-ON* */
681
682
683 /**
684  * Delete an entry from the l2fib.
685  * Return 0 if the entry was deleted, or 1 it was not found or if
686  * sw_if_index is non-zero and does not match that in the entry.
687  */
688 u32
689 l2fib_del_entry (const u8 * mac, u32 bd_index, u32 sw_if_index)
690 {
691   l2fib_entry_result_t result;
692   l2fib_main_t *mp = &l2fib_main;
693   BVT (clib_bihash_kv) kv;
694
695   /* set up key */
696   kv.key = l2fib_make_key (mac, bd_index);
697
698   if (BV (clib_bihash_search) (&mp->mac_table, &kv, &kv))
699     return 1;
700
701   result.raw = kv.value;
702
703   /*  check if sw_if_index of entry match */
704   if ((sw_if_index != 0) && (sw_if_index != result.fields.sw_if_index))
705     return 1;
706
707   /* decrement counter if dynamically learned mac */
708   if ((!l2fib_entry_result_is_set_AGE_NOT (&result)) &&
709       (l2learn_main.global_learn_count))
710     l2learn_main.global_learn_count--;
711
712   /* Remove entry from hash table */
713   BV (clib_bihash_add_del) (&mp->mac_table, &kv, 0 /* is_add */ );
714   return 0;
715 }
716
717 /**
718  * Delete an entry from the L2FIB.
719  * The CLI format is:
720  *    l2fib del <mac> <bd-id>
721  */
722 static clib_error_t *
723 l2fib_del (vlib_main_t * vm,
724            unformat_input_t * input, vlib_cli_command_t * cmd)
725 {
726   bd_main_t *bdm = &bd_main;
727   clib_error_t *error = 0;
728   u8 mac[6];
729   u32 bd_id;
730   u32 bd_index;
731   uword *p;
732
733   if (!unformat (input, "%U", unformat_ethernet_address, mac))
734     {
735       error = clib_error_return (0, "expected mac address `%U'",
736                                  format_unformat_error, input);
737       goto done;
738     }
739
740   if (!unformat (input, "%d", &bd_id))
741     {
742       error = clib_error_return (0, "expected bridge domain ID `%U'",
743                                  format_unformat_error, input);
744       goto done;
745     }
746
747   p = hash_get (bdm->bd_index_by_bd_id, bd_id);
748   if (!p)
749     {
750       error = clib_error_return (0, "bridge domain ID %d invalid", bd_id);
751       goto done;
752     }
753   bd_index = p[0];
754
755   /* Delete the entry */
756   if (l2fib_del_entry (mac, bd_index, 0))
757     {
758       error = clib_error_return (0, "mac entry not found");
759       goto done;
760     }
761
762 done:
763   return error;
764 }
765
766 /*?
767  * This command deletes an existing MAC Address entry from the L2 FIB
768  * table of an existing bridge-domain.
769  *
770  * @cliexpar
771  * Example of how to delete a MAC Address entry from the L2 FIB table of a bridge-domain (where 200 is the bridge-domain-id):
772  * @cliexcmd{l2fib del 52:54:00:53:18:33 200}
773 ?*/
774 /* *INDENT-OFF* */
775 VLIB_CLI_COMMAND (l2fib_del_cli, static) = {
776   .path = "l2fib del",
777   .short_help = "l2fib del <mac> <bridge-domain-id> []",
778   .function = l2fib_del,
779 };
780 /* *INDENT-ON* */
781
782 /**
783     Kick off ager to scan MACs to age/delete MAC entries
784 */
785 void
786 l2fib_start_ager_scan (vlib_main_t * vm)
787 {
788   uword evt = L2_MAC_AGE_PROCESS_EVENT_ONE_PASS;
789
790   /* check if there is at least one bd with mac aging enabled */
791   l2_bridge_domain_t *bd_config;
792   vec_foreach (bd_config, l2input_main.bd_configs)
793   {
794     if (bd_config->bd_id != ~0 && bd_config->mac_age != 0)
795       {
796         evt = L2_MAC_AGE_PROCESS_EVENT_START;
797         break;
798       }
799   }
800
801   vlib_process_signal_event (vm, l2fib_mac_age_scanner_process_node.index,
802                              evt, 0);
803 }
804
805 /**
806     Flush all non static MACs from an interface
807 */
808 void
809 l2fib_flush_int_mac (vlib_main_t * vm, u32 sw_if_index)
810 {
811   *l2fib_swif_seq_num (sw_if_index) += 1;
812   l2fib_start_ager_scan (vm);
813 }
814
815 /**
816     Flush all non static MACs in a bridge domain
817 */
818 void
819 l2fib_flush_bd_mac (vlib_main_t * vm, u32 bd_index)
820 {
821   l2_bridge_domain_t *bd_config = l2input_bd_config (bd_index);
822   bd_config->seq_num += 1;
823   l2fib_start_ager_scan (vm);
824 }
825
826 /**
827     Flush all non static MACs - flushes all valid BDs
828 */
829 void
830 l2fib_flush_all_mac (vlib_main_t * vm)
831 {
832   l2_bridge_domain_t *bd_config;
833   vec_foreach (bd_config, l2input_main.bd_configs)
834     if (bd_is_valid (bd_config))
835     bd_config->seq_num += 1;
836
837   l2fib_start_ager_scan (vm);
838 }
839
840
841 /**
842     Flush MACs, except static ones, associated with an interface
843     The CLI format is:
844     l2fib flush-mac interface <if-name>
845 */
846 static clib_error_t *
847 l2fib_flush_mac_int (vlib_main_t * vm,
848                      unformat_input_t * input, vlib_cli_command_t * cmd)
849 {
850   vnet_main_t *vnm = vnet_get_main ();
851   clib_error_t *error = 0;
852   u32 sw_if_index;
853
854   if (!unformat_user (input, unformat_vnet_sw_interface, vnm, &sw_if_index))
855     {
856       error = clib_error_return (0, "unknown interface `%U'",
857                                  format_unformat_error, input);
858       goto done;
859     }
860
861   l2fib_flush_int_mac (vm, sw_if_index);
862
863 done:
864   return error;
865 }
866
867 /**
868     Flush all MACs, except static ones
869     The CLI format is:
870     l2fib flush-mac all
871 */
872 static clib_error_t *
873 l2fib_flush_mac_all (vlib_main_t * vm,
874                      unformat_input_t * input, vlib_cli_command_t * cmd)
875 {
876   l2fib_flush_all_mac (vm);
877   return 0;
878 }
879
880 /*?
881  * This command kick off ager to delete all existing MAC Address entries,
882  * except static ones, associated with an interface from the L2 FIB table.
883  *
884  * @cliexpar
885  * Example of how to flush MAC Address entries learned on an interface from the L2 FIB table:
886  * @cliexcmd{l2fib flush-mac interface GigabitEthernet2/1/0}
887 ?*/
888 /* *INDENT-OFF* */
889 VLIB_CLI_COMMAND (l2fib_flush_mac_all_cli, static) = {
890   .path = "l2fib flush-mac all",
891   .short_help = "l2fib flush-mac all",
892   .function = l2fib_flush_mac_all,
893 };
894 /* *INDENT-ON* */
895
896 /*?
897  * This command kick off ager to delete all existing MAC Address entries,
898  * except static ones, associated with an interface from the L2 FIB table.
899  *
900  * @cliexpar
901  * Example of how to flush MAC Address entries learned on an interface from the L2 FIB table:
902  * @cliexcmd{l2fib flush-mac interface GigabitEthernet2/1/0}
903 ?*/
904 /* *INDENT-OFF* */
905 VLIB_CLI_COMMAND (l2fib_flush_mac_int_cli, static) = {
906   .path = "l2fib flush-mac interface",
907   .short_help = "l2fib flush-mac interface <if-name>",
908   .function = l2fib_flush_mac_int,
909 };
910 /* *INDENT-ON* */
911
912 /**
913     Flush bridge-domain MACs except static ones.
914     The CLI format is:
915     l2fib flush-mac bridge-domain <bd-id>
916 */
917 static clib_error_t *
918 l2fib_flush_mac_bd (vlib_main_t * vm,
919                     unformat_input_t * input, vlib_cli_command_t * cmd)
920 {
921   bd_main_t *bdm = &bd_main;
922   clib_error_t *error = 0;
923   u32 bd_index, bd_id;
924   uword *p;
925
926   if (!unformat (input, "%d", &bd_id))
927     {
928       error = clib_error_return (0, "expecting bridge-domain id but got `%U'",
929                                  format_unformat_error, input);
930       goto done;
931     }
932
933   p = hash_get (bdm->bd_index_by_bd_id, bd_id);
934   if (p)
935     bd_index = *p;
936   else
937     return clib_error_return (0, "No such bridge domain %d", bd_id);
938
939   l2fib_flush_bd_mac (vm, bd_index);
940
941 done:
942   return error;
943 }
944
945 /*?
946  * This command kick off ager to delete all existing MAC Address entries,
947  * except static ones, in a bridge domain from the L2 FIB table.
948  *
949  * @cliexpar
950  * Example of how to flush MAC Address entries learned in a bridge domain from the L2 FIB table:
951  * @cliexcmd{l2fib flush-mac bridge-domain 1000}
952 ?*/
953 /* *INDENT-OFF* */
954 VLIB_CLI_COMMAND (l2fib_flush_mac_bd_cli, static) = {
955   .path = "l2fib flush-mac bridge-domain",
956   .short_help = "l2fib flush-mac bridge-domain <bd-id>",
957   .function = l2fib_flush_mac_bd,
958 };
959 /* *INDENT-ON* */
960
961 clib_error_t *
962 l2fib_sw_interface_up_down (vnet_main_t * vnm, u32 sw_if_index, u32 flags)
963 {
964   l2_input_config_t *config = l2input_intf_config (sw_if_index);
965   if ((flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) == 0 && config->bridge)
966     l2fib_flush_int_mac (vnm->vlib_main, sw_if_index);
967   return 0;
968 }
969
970 VNET_SW_INTERFACE_ADMIN_UP_DOWN_FUNCTION (l2fib_sw_interface_up_down);
971
972 BVT (clib_bihash) * get_mac_table (void)
973 {
974   l2fib_main_t *mp = &l2fib_main;
975   return &mp->mac_table;
976 }
977
978 static_always_inline void *
979 allocate_mac_evt_buf (u32 client, u32 client_index)
980 {
981   l2fib_main_t *fm = &l2fib_main;
982   vl_api_l2_macs_event_t *mp = vl_msg_api_alloc
983     (sizeof (*mp) + (fm->max_macs_in_event * sizeof (vl_api_mac_entry_t)));
984   mp->_vl_msg_id = htons (VL_API_L2_MACS_EVENT);
985   mp->pid = htonl (client);
986   mp->client_index = client_index;
987   return mp;
988 }
989
990 static_always_inline f64
991 l2fib_scan (vlib_main_t * vm, f64 start_time, u8 event_only)
992 {
993   l2fib_main_t *fm = &l2fib_main;
994   l2learn_main_t *lm = &l2learn_main;
995
996   BVT (clib_bihash) * h = &fm->mac_table;
997   int i, j, k;
998   f64 last_start = start_time;
999   f64 accum_t = 0;
1000   f64 delta_t = 0;
1001   u32 evt_idx = 0;
1002   u32 learn_count = 0;
1003   u32 client = lm->client_pid;
1004   u32 cl_idx = lm->client_index;
1005   vl_api_l2_macs_event_t *mp = 0;
1006   vl_api_registration_t *reg = 0;
1007
1008   /* Don't scan the l2 fib if it hasn't been instantiated yet */
1009   if (alloc_arena (h) == 0)
1010     return 0.0;
1011
1012   if (client)
1013     {
1014       mp = allocate_mac_evt_buf (client, cl_idx);
1015       reg = vl_api_client_index_to_registration (lm->client_index);
1016     }
1017
1018   for (i = 0; i < h->nbuckets; i++)
1019     {
1020       /* allow no more than 20us without a pause */
1021       delta_t = vlib_time_now (vm) - last_start;
1022       if (delta_t > 20e-6)
1023         {
1024           vlib_process_suspend (vm, 100e-6);    /* suspend for 100 us */
1025           last_start = vlib_time_now (vm);
1026           accum_t += delta_t;
1027         }
1028
1029       if (i < (h->nbuckets - 3))
1030         {
1031           BVT (clib_bihash_bucket) * b =
1032             BV (clib_bihash_get_bucket) (h, i + 3);
1033           CLIB_PREFETCH (b, CLIB_CACHE_LINE_BYTES, LOAD);
1034           b = BV (clib_bihash_get_bucket) (h, i + 1);
1035           if (!BV (clib_bihash_bucket_is_empty) (b))
1036             {
1037               BVT (clib_bihash_value) * v =
1038                 BV (clib_bihash_get_value) (h, b->offset);
1039               CLIB_PREFETCH (v, CLIB_CACHE_LINE_BYTES, LOAD);
1040             }
1041         }
1042
1043       BVT (clib_bihash_bucket) * b = BV (clib_bihash_get_bucket) (h, i);
1044       if (BV (clib_bihash_bucket_is_empty) (b))
1045         continue;
1046       BVT (clib_bihash_value) * v = BV (clib_bihash_get_value) (h, b->offset);
1047       for (j = 0; j < (1 << b->log2_pages); j++)
1048         {
1049           for (k = 0; k < BIHASH_KVP_PER_PAGE; k++)
1050             {
1051               if (v->kvp[k].key == ~0ULL && v->kvp[k].value == ~0ULL)
1052                 continue;
1053
1054               l2fib_entry_key_t key = {.raw = v->kvp[k].key };
1055               l2fib_entry_result_t result = {.raw = v->kvp[k].value };
1056
1057               if (!l2fib_entry_result_is_set_AGE_NOT (&result))
1058                 learn_count++;
1059
1060               if (client)
1061                 {
1062                   if (PREDICT_FALSE (evt_idx >= fm->max_macs_in_event))
1063                     {
1064                       /* event message full, send it and start a new one */
1065                       if (reg && vl_api_can_send_msg (reg))
1066                         {
1067                           mp->n_macs = htonl (evt_idx);
1068                           vl_api_send_msg (reg, (u8 *) mp);
1069                           mp = allocate_mac_evt_buf (client, cl_idx);
1070                         }
1071                       else
1072                         {
1073                           if (reg)
1074                             clib_warning ("MAC event to pid %d queue stuffed!"
1075                                           " %d MAC entries lost", client,
1076                                           evt_idx);
1077                         }
1078                       evt_idx = 0;
1079                     }
1080
1081                   if (l2fib_entry_result_is_set_LRN_EVT (&result))
1082                     {
1083                       /* copy mac entry to event msg */
1084                       clib_memcpy_fast (mp->mac[evt_idx].mac_addr,
1085                                         key.fields.mac, 6);
1086                       mp->mac[evt_idx].action =
1087                         l2fib_entry_result_is_set_LRN_MOV (&result) ?
1088                         (vl_api_mac_event_action_t) MAC_EVENT_ACTION_MOVE
1089                         : (vl_api_mac_event_action_t) MAC_EVENT_ACTION_ADD;
1090                       mp->mac[evt_idx].action =
1091                         htonl (mp->mac[evt_idx].action);
1092                       mp->mac[evt_idx].sw_if_index =
1093                         htonl (result.fields.sw_if_index);
1094                       /* clear event bits and update mac entry */
1095                       l2fib_entry_result_clear_LRN_EVT (&result);
1096                       l2fib_entry_result_clear_LRN_MOV (&result);
1097                       BVT (clib_bihash_kv) kv;
1098                       kv.key = key.raw;
1099                       kv.value = result.raw;
1100                       BV (clib_bihash_add_del) (&fm->mac_table, &kv, 1);
1101                       evt_idx++;
1102                       continue; /* skip aging */
1103                     }
1104                 }
1105
1106               if (event_only || l2fib_entry_result_is_set_AGE_NOT (&result))
1107                 continue;       /* skip aging - static_mac always age_not */
1108
1109               /* start aging processing */
1110               u32 bd_index = key.fields.bd_index;
1111               u32 sw_if_index = result.fields.sw_if_index;
1112               u16 sn = l2fib_cur_seq_num (bd_index, sw_if_index).as_u16;
1113               if (result.fields.sn.as_u16 != sn)
1114                 goto age_out;   /* stale mac */
1115
1116               l2_bridge_domain_t *bd_config =
1117                 vec_elt_at_index (l2input_main.bd_configs, bd_index);
1118
1119               if (bd_config->mac_age == 0)
1120                 continue;       /* skip aging */
1121
1122               i16 delta = (u8) (start_time / 60) - result.fields.timestamp;
1123               delta += delta < 0 ? 256 : 0;
1124
1125               if (delta < bd_config->mac_age)
1126                 continue;       /* still valid */
1127
1128             age_out:
1129               if (client)
1130                 {
1131                   /* copy mac entry to event msg */
1132                   clib_memcpy_fast (mp->mac[evt_idx].mac_addr, key.fields.mac,
1133                                     6);
1134                   mp->mac[evt_idx].action =
1135                     (vl_api_mac_event_action_t) MAC_EVENT_ACTION_DELETE;
1136                   mp->mac[evt_idx].action = htonl (mp->mac[evt_idx].action);
1137                   mp->mac[evt_idx].sw_if_index =
1138                     htonl (result.fields.sw_if_index);
1139                   evt_idx++;
1140                 }
1141               /* delete mac entry */
1142               BVT (clib_bihash_kv) kv;
1143               kv.key = key.raw;
1144               BV (clib_bihash_add_del) (&fm->mac_table, &kv, 0);
1145               learn_count--;
1146               /*
1147                * Note: we may have just freed the bucket's backing
1148                * storage, so check right here...
1149                */
1150               if (BV (clib_bihash_bucket_is_empty) (b))
1151                 goto doublebreak;
1152             }
1153           v++;
1154         }
1155     doublebreak:
1156       ;
1157     }
1158
1159   /* keep learn count consistent */
1160   l2learn_main.global_learn_count = learn_count;
1161
1162   if (mp)
1163     {
1164       /*  send any outstanding mac event message else free message buffer */
1165       if (evt_idx)
1166         {
1167           if (reg && vl_api_can_send_msg (reg))
1168             {
1169               mp->n_macs = htonl (evt_idx);
1170               vl_api_send_msg (reg, (u8 *) mp);
1171             }
1172           else
1173             {
1174               if (reg)
1175                 clib_warning ("MAC event to pid %d queue stuffed!"
1176                               " %d MAC entries lost", client, evt_idx);
1177               vl_msg_api_free (mp);
1178             }
1179         }
1180       else
1181         vl_msg_api_free (mp);
1182     }
1183   return delta_t + accum_t;
1184 }
1185
1186 static uword
1187 l2fib_mac_age_scanner_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1188                                vlib_frame_t * f)
1189 {
1190   uword event_type, *event_data = 0;
1191   l2fib_main_t *fm = &l2fib_main;
1192   l2learn_main_t *lm = &l2learn_main;
1193   bool enabled = 0;
1194   f64 start_time, next_age_scan_time = CLIB_TIME_MAX;
1195
1196   while (1)
1197     {
1198       if (lm->client_pid)
1199         vlib_process_wait_for_event_or_clock (vm, fm->event_scan_delay);
1200       else if (enabled)
1201         {
1202           f64 t = next_age_scan_time - vlib_time_now (vm);
1203           vlib_process_wait_for_event_or_clock (vm, t);
1204         }
1205       else
1206         vlib_process_wait_for_event (vm);
1207
1208       event_type = vlib_process_get_events (vm, &event_data);
1209       vec_reset_length (event_data);
1210
1211       start_time = vlib_time_now (vm);
1212       enum
1213       { SCAN_MAC_AGE, SCAN_MAC_EVENT, SCAN_DISABLE } scan = SCAN_MAC_AGE;
1214
1215       switch (event_type)
1216         {
1217         case ~0:                /* timer expired */
1218           if (lm->client_pid != 0 && start_time < next_age_scan_time)
1219             scan = SCAN_MAC_EVENT;
1220           break;
1221
1222         case L2_MAC_AGE_PROCESS_EVENT_START:
1223           enabled = 1;
1224           break;
1225
1226         case L2_MAC_AGE_PROCESS_EVENT_STOP:
1227           enabled = 0;
1228           scan = SCAN_DISABLE;
1229           break;
1230
1231         case L2_MAC_AGE_PROCESS_EVENT_ONE_PASS:
1232           break;
1233
1234         default:
1235           ASSERT (0);
1236         }
1237
1238       if (scan == SCAN_MAC_EVENT)
1239         l2fib_main.evt_scan_duration = l2fib_scan (vm, start_time, 1);
1240       else
1241         {
1242           if (scan == SCAN_MAC_AGE)
1243             l2fib_main.age_scan_duration = l2fib_scan (vm, start_time, 0);
1244           if (scan == SCAN_DISABLE)
1245             {
1246               l2fib_main.age_scan_duration = 0;
1247               l2fib_main.evt_scan_duration = 0;
1248             }
1249           /* schedule next scan */
1250           if (enabled)
1251             next_age_scan_time = start_time + L2FIB_AGE_SCAN_INTERVAL;
1252           else
1253             next_age_scan_time = CLIB_TIME_MAX;
1254         }
1255     }
1256   return 0;
1257 }
1258
1259 /* *INDENT-OFF* */
1260 VLIB_REGISTER_NODE (l2fib_mac_age_scanner_process_node) = {
1261     .function = l2fib_mac_age_scanner_process,
1262     .type = VLIB_NODE_TYPE_PROCESS,
1263     .name = "l2fib-mac-age-scanner-process",
1264 };
1265 /* *INDENT-ON* */
1266
1267 clib_error_t *
1268 l2fib_init (vlib_main_t * vm)
1269 {
1270   l2fib_main_t *mp = &l2fib_main;
1271   l2fib_entry_key_t test_key;
1272   u8 test_mac[6];
1273
1274   mp->vlib_main = vm;
1275   mp->vnet_main = vnet_get_main ();
1276
1277   /* Create the hash table  */
1278   BV (clib_bihash_init) (&mp->mac_table, "l2fib mac table",
1279                          L2FIB_NUM_BUCKETS, L2FIB_MEMORY_SIZE);
1280
1281   /* verify the key constructor is good, since it is endian-sensitive */
1282   clib_memset (test_mac, 0, sizeof (test_mac));
1283   test_mac[0] = 0x11;
1284   test_key.raw = 0;
1285   test_key.raw = l2fib_make_key ((u8 *) & test_mac, 0x1234);
1286   ASSERT (test_key.fields.mac[0] == 0x11);
1287   ASSERT (test_key.fields.bd_index == 0x1234);
1288
1289   return 0;
1290 }
1291
1292 VLIB_INIT_FUNCTION (l2fib_init);
1293
1294 /*
1295  * fd.io coding-style-patch-verification: ON
1296  *
1297  * Local Variables:
1298  * eval: (c-set-style "gnu")
1299  * End:
1300  */