forked from freebsd/freebsd-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfib_algo.c
2078 lines (1766 loc) · 52 KB
/
fib_algo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2020 Alexander V. Chernikov
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#include "opt_inet.h"
#include "opt_inet6.h"
#include "opt_route.h"
#include <sys/param.h>
#include <sys/eventhandler.h>
#include <sys/kernel.h>
#include <sys/sbuf.h>
#include <sys/lock.h>
#include <sys/rmlock.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/module.h>
#include <sys/kernel.h>
#include <sys/priv.h>
#include <sys/proc.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/sysctl.h>
#include <sys/syslog.h>
#include <sys/queue.h>
#include <net/vnet.h>
#include <net/if.h>
#include <net/if_var.h>
#include <netinet/in.h>
#include <netinet/in_var.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#ifdef INET6
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#endif
#include <net/route.h>
#include <net/route/nhop.h>
#include <net/route/route_ctl.h>
#include <net/route/route_var.h>
#include <net/route/fib_algo.h>
#include <machine/stdarg.h>
/*
* Fib lookup framework.
*
* This framework enables accelerated longest-prefix-match lookups for the
* routing tables by adding the ability to dynamically attach/detach lookup
* algorithms implementation to/from the datapath.
*
* flm - fib lookup modules - implementation of particular lookup algorithm
* fd - fib data - instance of an flm bound to specific routing table
*
* This file provides main framework functionality.
*
* The following are the features provided by the framework
*
* 1) nexhops abstraction -> provides transparent referencing, indexing
* and efficient idx->ptr mappings for nexthop and nexthop groups.
* 2) Routing table synchronisation
* 3) dataplane attachment points
* 4) automatic algorithm selection based on the provided preference.
*
*
* DATAPATH
* For each supported address family, there is a an allocated array of fib_dp
* structures, indexed by fib number. Each array entry contains callback function
* and its argument. This function will be called with a family-specific lookup key,
* scope and provided argument. This array gets re-created every time when new algo
* instance gets created. Please take a look at the replace_rtables_family() function
* for more details.
*
*/
SYSCTL_DECL(_net_route);
SYSCTL_NODE(_net_route, OID_AUTO, algo, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
"Fib algorithm lookups");
/* Algorithm sync policy */
/* Time interval to bucket updates */
VNET_DEFINE_STATIC(unsigned int, update_bucket_time_ms) = 50;
#define V_update_bucket_time_ms VNET(update_bucket_time_ms)
SYSCTL_UINT(_net_route_algo, OID_AUTO, bucket_time_ms, CTLFLAG_RW | CTLFLAG_VNET,
&VNET_NAME(update_bucket_time_ms), 0, "Time interval to calculate update rate");
/* Minimum update rate to delay sync */
VNET_DEFINE_STATIC(unsigned int, bucket_change_threshold_rate) = 500;
#define V_bucket_change_threshold_rate VNET(bucket_change_threshold_rate)
SYSCTL_UINT(_net_route_algo, OID_AUTO, bucket_change_threshold_rate, CTLFLAG_RW | CTLFLAG_VNET,
&VNET_NAME(bucket_change_threshold_rate), 0, "Minimum update rate to delay sync");
/* Max allowed delay to sync */
VNET_DEFINE_STATIC(unsigned int, fib_max_sync_delay_ms) = 1000;
#define V_fib_max_sync_delay_ms VNET(fib_max_sync_delay_ms)
SYSCTL_UINT(_net_route_algo, OID_AUTO, fib_max_sync_delay_ms, CTLFLAG_RW | CTLFLAG_VNET,
&VNET_NAME(fib_max_sync_delay_ms), 0, "Maximum time to delay sync (ms)");
#ifdef INET6
VNET_DEFINE_STATIC(bool, algo_fixed_inet6) = false;
#define V_algo_fixed_inet6 VNET(algo_fixed_inet6)
SYSCTL_NODE(_net_route_algo, OID_AUTO, inet6, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
"IPv6 longest prefix match lookups");
#endif
#ifdef INET
VNET_DEFINE_STATIC(bool, algo_fixed_inet) = false;
#define V_algo_fixed_inet VNET(algo_fixed_inet)
SYSCTL_NODE(_net_route_algo, OID_AUTO, inet, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
"IPv4 longest prefix match lookups");
#endif
/* Fib instance counter */
static uint32_t fib_gen = 0;
struct nhop_ref_table {
uint32_t count;
int32_t refcnt[0];
};
enum fib_callout_action {
FDA_NONE, /* No callout scheduled */
FDA_REBUILD, /* Asks to rebuild algo instance */
FDA_EVAL, /* Asks to evaluate if the current algo is still be best */
FDA_BATCH, /* Asks to submit batch of updates to the algo */
};
struct fib_sync_status {
struct timeval diverge_time; /* ts when diverged */
uint32_t num_changes; /* number of changes since sync */
uint32_t bucket_changes; /* num changes within the current bucket */
uint64_t bucket_id; /* 50ms bucket # */
struct fib_change_queue fd_change_queue;/* list of scheduled entries */
};
/*
* Data structure for the fib lookup instance tied to the particular rib.
*/
struct fib_data {
uint32_t number_nhops; /* current # of nhops */
uint8_t hit_nhops; /* true if out of nhop limit */
uint8_t init_done; /* true if init is competed */
uint32_t fd_dead:1; /* Scheduled for deletion */
uint32_t fd_linked:1; /* true if linked */
uint32_t fd_need_rebuild:1; /* true if rebuild scheduled */
uint32_t fd_batch:1; /* true if batched notification scheduled */
uint8_t fd_family; /* family */
uint32_t fd_fibnum; /* fibnum */
uint32_t fd_failed_rebuilds; /* stat: failed rebuilds */
uint32_t fd_gen; /* instance gen# */
struct callout fd_callout; /* rebuild callout */
enum fib_callout_action fd_callout_action; /* Callout action to take */
void *fd_algo_data; /* algorithm data */
struct nhop_object **nh_idx; /* nhop idx->ptr array */
struct nhop_ref_table *nh_ref_table; /* array with # of nhop references */
struct rib_head *fd_rh; /* RIB table we're attached to */
struct rib_subscription *fd_rs; /* storing table subscription */
struct fib_dp fd_dp; /* fib datapath data */
struct vnet *fd_vnet; /* vnet fib belongs to */
struct epoch_context fd_epoch_ctx; /* epoch context for deletion */
struct fib_lookup_module *fd_flm;/* pointer to the lookup module */
struct fib_sync_status fd_ss; /* State relevant to the rib sync */
uint32_t fd_num_changes; /* number of changes since last callout */
TAILQ_ENTRY(fib_data) entries; /* list of all fds in vnet */
};
static bool rebuild_fd(struct fib_data *fd, const char *reason);
static bool rebuild_fd_flm(struct fib_data *fd, struct fib_lookup_module *flm_new);
static void handle_fd_callout(void *_data);
static void destroy_fd_instance_epoch(epoch_context_t ctx);
static bool is_idx_free(struct fib_data *fd, uint32_t index);
static void set_algo_fixed(struct rib_head *rh);
static bool is_algo_fixed(struct rib_head *rh);
static uint32_t fib_ref_nhop(struct fib_data *fd, struct nhop_object *nh);
static void fib_unref_nhop(struct fib_data *fd, struct nhop_object *nh);
static struct fib_lookup_module *fib_check_best_algo(struct rib_head *rh,
struct fib_lookup_module *orig_flm);
static void fib_unref_algo(struct fib_lookup_module *flm);
static bool flm_error_check(const struct fib_lookup_module *flm, uint32_t fibnum);
struct mtx fib_mtx;
#define FIB_MOD_LOCK() mtx_lock(&fib_mtx)
#define FIB_MOD_UNLOCK() mtx_unlock(&fib_mtx)
#define FIB_MOD_LOCK_ASSERT() mtx_assert(&fib_mtx, MA_OWNED)
MTX_SYSINIT(fib_mtx, &fib_mtx, "algo list mutex", MTX_DEF);
/* Algorithm has to be this percent better than the current to switch */
#define BEST_DIFF_PERCENT (5 * 256 / 100)
/* Schedule algo re-evaluation X seconds after a change */
#define ALGO_EVAL_DELAY_MS 30000
/* Force algo re-evaluation after X changes */
#define ALGO_EVAL_NUM_ROUTES 100
/* Try to setup algorithm X times */
#define FIB_MAX_TRIES 32
/* Max amount of supported nexthops */
#define FIB_MAX_NHOPS 262144
#define FIB_CALLOUT_DELAY_MS 50
/* Debug */
static int flm_debug_level = LOG_NOTICE;
SYSCTL_INT(_net_route_algo, OID_AUTO, debug_level, CTLFLAG_RW | CTLFLAG_RWTUN,
&flm_debug_level, 0, "debuglevel");
#define FLM_MAX_DEBUG_LEVEL LOG_DEBUG
#ifndef LOG_DEBUG2
#define LOG_DEBUG2 8
#endif
#define _PASS_MSG(_l) (flm_debug_level >= (_l))
#define ALGO_PRINTF(_l, _fmt, ...) if (_PASS_MSG(_l)) { \
printf("[fib_algo] %s: " _fmt "\n", __func__, ##__VA_ARGS__); \
}
#define _ALGO_PRINTF(_fib, _fam, _aname, _gen, _func, _fmt, ...) \
printf("[fib_algo] %s.%u (%s#%u) %s: " _fmt "\n",\
print_family(_fam), _fib, _aname, _gen, _func, ## __VA_ARGS__)
#define _RH_PRINTF(_fib, _fam, _func, _fmt, ...) \
printf("[fib_algo] %s.%u %s: " _fmt "\n", print_family(_fam), _fib, _func, ## __VA_ARGS__)
#define RH_PRINTF(_l, _rh, _fmt, ...) if (_PASS_MSG(_l)) { \
_RH_PRINTF(_rh->rib_fibnum, _rh->rib_family, __func__, _fmt, ## __VA_ARGS__);\
}
#define FD_PRINTF(_l, _fd, _fmt, ...) FD_PRINTF_##_l(_l, _fd, _fmt, ## __VA_ARGS__)
#define _FD_PRINTF(_l, _fd, _fmt, ...) if (_PASS_MSG(_l)) { \
_ALGO_PRINTF(_fd->fd_fibnum, _fd->fd_family, _fd->fd_flm->flm_name, \
_fd->fd_gen, __func__, _fmt, ## __VA_ARGS__); \
}
#if FLM_MAX_DEBUG_LEVEL>=LOG_DEBUG2
#define FD_PRINTF_LOG_DEBUG2 _FD_PRINTF
#else
#define FD_PRINTF_LOG_DEBUG2(_l, _fd, _fmt, ...)
#endif
#if FLM_MAX_DEBUG_LEVEL>=LOG_DEBUG
#define FD_PRINTF_LOG_DEBUG _FD_PRINTF
#else
#define FD_PRINTF_LOG_DEBUG()
#endif
#if FLM_MAX_DEBUG_LEVEL>=LOG_INFO
#define FD_PRINTF_LOG_INFO _FD_PRINTF
#else
#define FD_PRINTF_LOG_INFO()
#endif
#define FD_PRINTF_LOG_NOTICE _FD_PRINTF
#define FD_PRINTF_LOG_ERR _FD_PRINTF
#define FD_PRINTF_LOG_WARNING _FD_PRINTF
/* List of all registered lookup algorithms */
static TAILQ_HEAD(, fib_lookup_module) all_algo_list = TAILQ_HEAD_INITIALIZER(all_algo_list);
/* List of all fib lookup instances in the vnet */
VNET_DEFINE_STATIC(TAILQ_HEAD(fib_data_head, fib_data), fib_data_list);
#define V_fib_data_list VNET(fib_data_list)
/* Datastructure for storing non-transient fib lookup module failures */
struct fib_error {
int fe_family;
uint32_t fe_fibnum; /* failed rtable */
struct fib_lookup_module *fe_flm; /* failed module */
TAILQ_ENTRY(fib_error) entries;/* list of all errored entries */
};
VNET_DEFINE_STATIC(TAILQ_HEAD(fib_error_head, fib_error), fib_error_list);
#define V_fib_error_list VNET(fib_error_list)
/* Per-family array of fibnum -> {func, arg} mappings used in datapath */
struct fib_dp_header {
struct epoch_context fdh_epoch_ctx;
uint32_t fdh_num_tables;
struct fib_dp fdh_idx[0];
};
/*
* Tries to add new non-transient algorithm error to the list of
* errors.
* Returns true on success.
*/
static bool
flm_error_add(struct fib_lookup_module *flm, uint32_t fibnum)
{
struct fib_error *fe;
fe = malloc(sizeof(struct fib_error), M_TEMP, M_NOWAIT | M_ZERO);
if (fe == NULL)
return (false);
fe->fe_flm = flm;
fe->fe_family = flm->flm_family;
fe->fe_fibnum = fibnum;
FIB_MOD_LOCK();
/* Avoid duplicates by checking if error already exists first */
if (flm_error_check(flm, fibnum)) {
FIB_MOD_UNLOCK();
free(fe, M_TEMP);
return (true);
}
TAILQ_INSERT_HEAD(&V_fib_error_list, fe, entries);
FIB_MOD_UNLOCK();
return (true);
}
/*
* True if non-transient error has been registered for @flm in @fibnum.
*/
static bool
flm_error_check(const struct fib_lookup_module *flm, uint32_t fibnum)
{
const struct fib_error *fe;
TAILQ_FOREACH(fe, &V_fib_error_list, entries) {
if ((fe->fe_flm == flm) && (fe->fe_fibnum == fibnum))
return (true);
}
return (false);
}
/*
* Clear all errors of algo specified by @flm.
*/
static void
fib_error_clear_flm(struct fib_lookup_module *flm)
{
struct fib_error *fe, *fe_tmp;
FIB_MOD_LOCK_ASSERT();
TAILQ_FOREACH_SAFE(fe, &V_fib_error_list, entries, fe_tmp) {
if (fe->fe_flm == flm) {
TAILQ_REMOVE(&V_fib_error_list, fe, entries);
free(fe, M_TEMP);
}
}
}
/*
* Clears all errors in current VNET.
*/
static void
fib_error_clear(void)
{
struct fib_error *fe, *fe_tmp;
FIB_MOD_LOCK_ASSERT();
TAILQ_FOREACH_SAFE(fe, &V_fib_error_list, entries, fe_tmp) {
TAILQ_REMOVE(&V_fib_error_list, fe, entries);
free(fe, M_TEMP);
}
}
static const char *
print_op_result(enum flm_op_result result)
{
switch (result) {
case FLM_SUCCESS:
return "success";
case FLM_REBUILD:
return "rebuild";
case FLM_BATCH:
return "batch";
case FLM_ERROR:
return "error";
}
return "unknown";
}
static const char *
print_family(int family)
{
if (family == AF_INET)
return ("inet");
else if (family == AF_INET6)
return ("inet6");
else
return ("unknown");
}
/*
* Debug function used by lookup algorithms.
* Outputs message denoted by @fmt, prepended by "[fib_algo] inetX.Y (algo) "
*/
void
fib_printf(int level, struct fib_data *fd, const char *func, char *fmt, ...)
{
char buf[128];
va_list ap;
if (level > flm_debug_level)
return;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
_ALGO_PRINTF(fd->fd_fibnum, fd->fd_family, fd->fd_flm->flm_name,
fd->fd_gen, func, "%s", buf);
}
/*
* Outputs list of algorithms supported by the provided address family.
*/
static int
print_algos_sysctl(struct sysctl_req *req, int family)
{
struct fib_lookup_module *flm;
struct sbuf sbuf;
int error, count = 0;
error = sysctl_wire_old_buffer(req, 0);
if (error == 0) {
sbuf_new_for_sysctl(&sbuf, NULL, 512, req);
TAILQ_FOREACH(flm, &all_algo_list, entries) {
if (flm->flm_family == family) {
if (count++ > 0)
sbuf_cat(&sbuf, ", ");
sbuf_cat(&sbuf, flm->flm_name);
}
}
error = sbuf_finish(&sbuf);
sbuf_delete(&sbuf);
}
return (error);
}
#ifdef INET6
static int
print_algos_sysctl_inet6(SYSCTL_HANDLER_ARGS)
{
return (print_algos_sysctl(req, AF_INET6));
}
SYSCTL_PROC(_net_route_algo_inet6, OID_AUTO, algo_list,
CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
print_algos_sysctl_inet6, "A", "List of IPv6 lookup algorithms");
#endif
#ifdef INET
static int
print_algos_sysctl_inet(SYSCTL_HANDLER_ARGS)
{
return (print_algos_sysctl(req, AF_INET));
}
SYSCTL_PROC(_net_route_algo_inet, OID_AUTO, algo_list,
CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
print_algos_sysctl_inet, "A", "List of IPv4 lookup algorithms");
#endif
/*
* Calculate delay between repeated failures.
* Returns current delay in milliseconds.
*/
static uint32_t
callout_calc_delay_ms(struct fib_data *fd)
{
uint32_t shift;
if (fd->fd_failed_rebuilds > 10)
shift = 10;
else
shift = fd->fd_failed_rebuilds;
return ((1 << shift) * FIB_CALLOUT_DELAY_MS);
}
static void
schedule_callout(struct fib_data *fd, enum fib_callout_action action, int delay_ms)
{
FD_PRINTF(LOG_DEBUG, fd, "delay=%d action=%d", delay_ms, action);
fd->fd_callout_action = action;
callout_reset_sbt(&fd->fd_callout, SBT_1MS * delay_ms, 0,
handle_fd_callout, fd, 0);
}
static void
schedule_fd_rebuild(struct fib_data *fd, const char *reason)
{
RIB_WLOCK_ASSERT(fd->fd_rh);
if (!fd->fd_need_rebuild) {
fd->fd_need_rebuild = true;
/* Stop batch updates */
fd->fd_batch = false;
/*
* Potentially re-schedules pending callout
* initiated by schedule_algo_eval.
*/
FD_PRINTF(LOG_INFO, fd, "Scheduling rebuild: %s (failures=%d)",
reason, fd->fd_failed_rebuilds);
schedule_callout(fd, FDA_REBUILD, callout_calc_delay_ms(fd));
}
}
static void
sync_rib_gen(struct fib_data *fd)
{
FD_PRINTF(LOG_DEBUG, fd, "Sync gen %u -> %u", fd->fd_rh->rnh_gen, fd->fd_rh->rnh_gen_rib);
fd->fd_rh->rnh_gen = fd->fd_rh->rnh_gen_rib;
}
static int64_t
get_tv_diff_ms(const struct timeval *old_tv, const struct timeval *new_tv)
{
int64_t diff = 0;
diff = ((int64_t)(new_tv->tv_sec - old_tv->tv_sec)) * 1000;
diff += (new_tv->tv_usec - old_tv->tv_usec) / 1000;
return (diff);
}
static void
add_tv_diff_ms(struct timeval *tv, int ms)
{
tv->tv_sec += ms / 1000;
ms = ms % 1000;
if (ms * 1000 + tv->tv_usec < 1000000)
tv->tv_usec += ms * 1000;
else {
tv->tv_sec += 1;
tv->tv_usec = ms * 1000 + tv->tv_usec - 1000000;
}
}
/*
* Marks the time when algo state diverges from the rib state.
*/
static void
mark_diverge_time(struct fib_data *fd)
{
struct fib_sync_status *fd_ss = &fd->fd_ss;
getmicrouptime(&fd_ss->diverge_time);
fd_ss->bucket_id = 0;
fd_ss->bucket_changes = 0;
}
/*
* Calculates and updates the next algorithm sync time, based on the current activity.
*
* The intent is to provide reasonable balance between the update
* latency and efficient batching when changing large amount of routes.
*
* High-level algorithm looks the following:
* 1) all changes are bucketed in 50ms intervals
* 2) If amount of changes within the bucket is greater than the threshold,
* the update gets delayed, up to maximum delay threshold.
*/
static void
update_rebuild_delay(struct fib_data *fd, enum fib_callout_action action)
{
uint32_t bucket_id, new_delay = 0;
struct timeval tv;
/* Fetch all variables at once to ensure consistent reads */
uint32_t bucket_time_ms = V_update_bucket_time_ms;
uint32_t threshold_rate = V_bucket_change_threshold_rate;
uint32_t max_delay_ms = V_fib_max_sync_delay_ms;
if (bucket_time_ms == 0)
bucket_time_ms = 50;
/* calculate per-bucket threshold rate */
threshold_rate = threshold_rate * bucket_time_ms / 1000;
getmicrouptime(&tv);
struct fib_sync_status *fd_ss = &fd->fd_ss;
bucket_id = get_tv_diff_ms(&fd_ss->diverge_time, &tv) / bucket_time_ms;
if (fd_ss->bucket_id == bucket_id) {
fd_ss->bucket_changes++;
if (fd_ss->bucket_changes == threshold_rate) {
new_delay = (bucket_id + 2) * bucket_time_ms;
if (new_delay <= max_delay_ms) {
FD_PRINTF(LOG_DEBUG, fd,
"hit threshold of %u routes, delay update,"
"bucket: %u, total delay: %u",
threshold_rate, bucket_id + 1, new_delay);
} else {
new_delay = 0;
FD_PRINTF(LOG_DEBUG, fd,
"maximum sync delay (%u ms) reached", max_delay_ms);
}
} else if ((bucket_id == 0) && (fd_ss->bucket_changes == 1))
new_delay = bucket_time_ms;
} else {
fd_ss->bucket_id = bucket_id;
fd_ss->bucket_changes = 1;
}
if (new_delay > 0) {
/* Calculated time has been updated */
struct timeval new_tv = fd_ss->diverge_time;
add_tv_diff_ms(&new_tv, new_delay);
int32_t delay_ms = get_tv_diff_ms(&tv, &new_tv);
schedule_callout(fd, action, delay_ms);
}
}
static void
update_algo_state(struct fib_data *fd)
{
RIB_WLOCK_ASSERT(fd->fd_rh);
if (fd->fd_batch || fd->fd_need_rebuild) {
enum fib_callout_action action = fd->fd_need_rebuild ? FDA_REBUILD : FDA_BATCH;
update_rebuild_delay(fd, action);
return;
}
if (fd->fd_num_changes++ == 0) {
/* Start callout to consider switch */
if (!callout_pending(&fd->fd_callout))
schedule_callout(fd, FDA_EVAL, ALGO_EVAL_DELAY_MS);
} else if (fd->fd_num_changes == ALGO_EVAL_NUM_ROUTES) {
/* Reset callout to exec immediately */
if (fd->fd_callout_action == FDA_EVAL)
schedule_callout(fd, FDA_EVAL, 1);
}
}
static bool
need_immediate_sync(struct fib_data *fd, struct rib_cmd_info *rc)
{
struct nhop_object *nh;
/* Sync addition/removal of interface routes */
switch (rc->rc_cmd) {
case RTM_ADD:
nh = rc->rc_nh_new;
if (!NH_IS_NHGRP(nh)) {
if (!(nh->nh_flags & NHF_GATEWAY))
return (true);
if (nhop_get_rtflags(nh) & RTF_STATIC)
return (true);
}
break;
case RTM_DELETE:
nh = rc->rc_nh_old;
if (!NH_IS_NHGRP(nh)) {
if (!(nh->nh_flags & NHF_GATEWAY))
return (true);
if (nhop_get_rtflags(nh) & RTF_STATIC)
return (true);
}
break;
}
return (false);
}
static bool
apply_rtable_changes(struct fib_data *fd)
{
enum flm_op_result result;
struct fib_change_queue *q = &fd->fd_ss.fd_change_queue;
result = fd->fd_flm->flm_change_rib_items_cb(fd->fd_rh, q, fd->fd_algo_data);
if (result == FLM_SUCCESS) {
sync_rib_gen(fd);
for (int i = 0; i < q->count; i++)
if (q->entries[i].nh_old)
fib_unref_nhop(fd, q->entries[i].nh_old);
q->count = 0;
}
fd->fd_batch = false;
return (result == FLM_SUCCESS);
}
static bool
fill_change_entry(struct fib_data *fd, struct fib_change_entry *ce, struct rib_cmd_info *rc)
{
int plen = 0;
switch (fd->fd_family) {
#ifdef INET
case AF_INET:
rt_get_inet_prefix_plen(rc->rc_rt, &ce->addr4, &plen, &ce->scopeid);
break;
#endif
#ifdef INET6
case AF_INET6:
rt_get_inet6_prefix_plen(rc->rc_rt, &ce->addr6, &plen, &ce->scopeid);
break;
#endif
}
ce->plen = plen;
ce->nh_old = rc->rc_nh_old;
ce->nh_new = rc->rc_nh_new;
if (ce->nh_new != NULL) {
if (fib_ref_nhop(fd, ce->nh_new) == 0)
return (false);
}
return (true);
}
static bool
queue_rtable_change(struct fib_data *fd, struct rib_cmd_info *rc)
{
struct fib_change_queue *q = &fd->fd_ss.fd_change_queue;
if (q->count >= q->size) {
uint32_t q_size;
if (q->size == 0)
q_size = 256; /* ~18k memory */
else
q_size = q->size * 2;
size_t size = q_size * sizeof(struct fib_change_entry);
void *a = realloc(q->entries, size, M_TEMP, M_NOWAIT | M_ZERO);
if (a == NULL) {
FD_PRINTF(LOG_INFO, fd, "Unable to realloc queue for %u elements",
q_size);
return (false);
}
q->entries = a;
q->size = q_size;
}
return (fill_change_entry(fd, &q->entries[q->count++], rc));
}
/*
* Rib subscription handler. Checks if the algorithm is ready to
* receive updates, handles nexthop refcounting and passes change
* data to the algorithm callback.
*/
static void
handle_rtable_change_cb(struct rib_head *rnh, struct rib_cmd_info *rc,
void *_data)
{
struct fib_data *fd = (struct fib_data *)_data;
enum flm_op_result result;
RIB_WLOCK_ASSERT(rnh);
/*
* There is a small gap between subscribing for route changes
* and initiating rtable dump. Avoid receiving route changes
* prior to finishing rtable dump by checking `init_done`.
*/
if (!fd->init_done)
return;
bool immediate_sync = need_immediate_sync(fd, rc);
/* Consider scheduling algorithm re-evaluation */
update_algo_state(fd);
/*
* If algo requested rebuild, stop sending updates by default.
* This simplifies nexthop refcount handling logic.
*/
if (fd->fd_need_rebuild) {
if (immediate_sync)
rebuild_fd(fd, "rtable change type enforced sync");
return;
}
/*
* Algo requested updates to be delivered in batches.
* Add the current change to the queue and return.
*/
if (fd->fd_batch) {
if (immediate_sync) {
if (!queue_rtable_change(fd, rc) || !apply_rtable_changes(fd))
rebuild_fd(fd, "batch sync failed");
} else {
if (!queue_rtable_change(fd, rc))
schedule_fd_rebuild(fd, "batch queue failed");
}
return;
}
/*
* Maintain guarantee that every nexthop returned by the dataplane
* lookup has > 0 refcount, so can be safely referenced within current
* epoch.
*/
if (rc->rc_nh_new != NULL) {
if (fib_ref_nhop(fd, rc->rc_nh_new) == 0) {
/* ran out of indexes */
schedule_fd_rebuild(fd, "ran out of nhop indexes");
return;
}
}
result = fd->fd_flm->flm_change_rib_item_cb(rnh, rc, fd->fd_algo_data);
switch (result) {
case FLM_SUCCESS:
sync_rib_gen(fd);
/* Unref old nexthop on success */
if (rc->rc_nh_old != NULL)
fib_unref_nhop(fd, rc->rc_nh_old);
break;
case FLM_BATCH:
/*
* Algo asks to batch the changes.
*/
if (queue_rtable_change(fd, rc)) {
if (!immediate_sync) {
fd->fd_batch = true;
mark_diverge_time(fd);
update_rebuild_delay(fd, FDA_BATCH);
break;
}
if (apply_rtable_changes(fd))
break;
}
FD_PRINTF(LOG_ERR, fd, "batched sync failed, force the rebuild");
case FLM_REBUILD:
/*
* Algo is not able to apply the update.
* Schedule algo rebuild.
*/
if (!immediate_sync) {
mark_diverge_time(fd);
schedule_fd_rebuild(fd, "algo requested rebuild");
break;
}
FD_PRINTF(LOG_INFO, fd, "running sync rebuild");
rebuild_fd(fd, "rtable change type enforced sync");
break;
case FLM_ERROR:
/*
* Algo reported a non-recoverable error.
* Record the error and schedule rebuild, which will
* trigger best algo selection.
*/
FD_PRINTF(LOG_ERR, fd, "algo reported non-recoverable error");
if (!flm_error_add(fd->fd_flm, fd->fd_fibnum))
FD_PRINTF(LOG_ERR, fd, "failed to ban algo");
schedule_fd_rebuild(fd, "algo reported non-recoverable error");
}
}
static void
estimate_nhop_scale(const struct fib_data *old_fd, struct fib_data *fd)
{
if (old_fd == NULL) {
// TODO: read from rtable
fd->number_nhops = 16;
return;
}
if (old_fd->hit_nhops && old_fd->number_nhops < FIB_MAX_NHOPS)
fd->number_nhops = 2 * old_fd->number_nhops;
else
fd->number_nhops = old_fd->number_nhops;
}
struct walk_cbdata {
struct fib_data *fd;
flm_dump_t *func;
enum flm_op_result result;
};
/*
* Handler called after all rtenties have been dumped.
* Performs post-dump framework checks and calls
* algo:flm_dump_end_cb().
*
* Updates walk_cbdata result.
*/
static void
sync_algo_end_cb(struct rib_head *rnh, enum rib_walk_hook stage, void *_data)
{
struct walk_cbdata *w = (struct walk_cbdata *)_data;
struct fib_data *fd = w->fd;
RIB_WLOCK_ASSERT(w->fd->fd_rh);
if (rnh->rib_dying) {
w->result = FLM_ERROR;
return;
}
if (fd->hit_nhops) {
FD_PRINTF(LOG_INFO, fd, "ran out of nexthops at %u nhops",
fd->nh_ref_table->count);
if (w->result == FLM_SUCCESS)
w->result = FLM_REBUILD;
return;
}
if (stage != RIB_WALK_HOOK_POST || w->result != FLM_SUCCESS)
return;
/* Post-dump hook, dump successful */
w->result = fd->fd_flm->flm_dump_end_cb(fd->fd_algo_data, &fd->fd_dp);
if (w->result == FLM_SUCCESS) {
/* Mark init as done to allow routing updates */
fd->init_done = 1;
}
}
/*
* Callback for each entry in rib.
* Calls algo:flm_dump_rib_item_cb func as a part of initial
* route table synchronisation.
*/
static int
sync_algo_cb(struct rtentry *rt, void *_data)
{
struct walk_cbdata *w = (struct walk_cbdata *)_data;
RIB_WLOCK_ASSERT(w->fd->fd_rh);
if (w->result == FLM_SUCCESS && w->func) {
/*
* Reference nexthops to maintain guarantee that
* each nexthop returned by datapath has > 0 references
* and can be safely referenced within current epoch.
*/
struct nhop_object *nh = rt_get_raw_nhop(rt);
if (fib_ref_nhop(w->fd, nh) != 0)
w->result = w->func(rt, w->fd->fd_algo_data);
else
w->result = FLM_REBUILD;
}
return (0);
}
/*
* Dump all routing table state to the algo instance.
*/
static enum flm_op_result
sync_algo(struct fib_data *fd)
{
struct walk_cbdata w = {
.fd = fd,
.func = fd->fd_flm->flm_dump_rib_item_cb,
.result = FLM_SUCCESS,
};
rib_walk_ext_locked(fd->fd_rh, sync_algo_cb, sync_algo_end_cb, &w);
FD_PRINTF(LOG_INFO, fd,
"initial dump completed (rtable version: %d), result: %s",
fd->fd_rh->rnh_gen, print_op_result(w.result));
return (w.result);
}
/*
* Schedules epoch-backed @fd instance deletion.
* * Unlinks @fd from the list of active algo instances.