forked from FRRouting/frr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.c
2205 lines (1853 loc) · 56.6 KB
/
event.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: GPL-2.0-or-later
/* Thread management routine
* Copyright (C) 1998, 2000 Kunihiro Ishiguro <kunihiro@zebra.org>
*/
/* #define DEBUG */
#include <zebra.h>
#include <sys/resource.h>
#include "frrevent.h"
#include "memory.h"
#include "frrcu.h"
#include "log.h"
#include "hash.h"
#include "command.h"
#include "sigevent.h"
#include "network.h"
#include "jhash.h"
#include "frratomic.h"
#include "frr_pthread.h"
#include "lib_errors.h"
#include "libfrr_trace.h"
#include "libfrr.h"
DEFINE_MTYPE_STATIC(LIB, THREAD, "Thread");
DEFINE_MTYPE_STATIC(LIB, EVENT_MASTER, "Thread master");
DEFINE_MTYPE_STATIC(LIB, EVENT_POLL, "Thread Poll Info");
DEFINE_MTYPE_STATIC(LIB, EVENT_STATS, "Thread stats");
DECLARE_LIST(event_list, struct event, eventitem);
struct cancel_req {
int flags;
struct event *thread;
void *eventobj;
struct event **threadref;
};
/* Flags for task cancellation */
#define EVENT_CANCEL_FLAG_READY 0x01
static int event_timer_cmp(const struct event *a, const struct event *b)
{
if (a->u.sands.tv_sec < b->u.sands.tv_sec)
return -1;
if (a->u.sands.tv_sec > b->u.sands.tv_sec)
return 1;
if (a->u.sands.tv_usec < b->u.sands.tv_usec)
return -1;
if (a->u.sands.tv_usec > b->u.sands.tv_usec)
return 1;
return 0;
}
DECLARE_HEAP(event_timer_list, struct event, timeritem, event_timer_cmp);
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#endif
#define AWAKEN(m) \
do { \
const unsigned char wakebyte = 0x01; \
write(m->io_pipe[1], &wakebyte, 1); \
} while (0)
/* control variable for initializer */
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
pthread_key_t thread_current;
static pthread_mutex_t masters_mtx = PTHREAD_MUTEX_INITIALIZER;
static struct list *masters;
static void thread_free(struct event_loop *master, struct event *thread);
#ifndef EXCLUDE_CPU_TIME
#define EXCLUDE_CPU_TIME 0
#endif
#ifndef CONSUMED_TIME_CHECK
#define CONSUMED_TIME_CHECK 0
#endif
bool cputime_enabled = !EXCLUDE_CPU_TIME;
unsigned long cputime_threshold = CONSUMED_TIME_CHECK;
unsigned long walltime_threshold = CONSUMED_TIME_CHECK;
/* CLI start ---------------------------------------------------------------- */
#include "lib/event_clippy.c"
static unsigned int cpu_record_hash_key(const struct cpu_event_history *a)
{
int size = sizeof(a->func);
return jhash(&a->func, size, 0);
}
static bool cpu_record_hash_cmp(const struct cpu_event_history *a,
const struct cpu_event_history *b)
{
return a->func == b->func;
}
static void *cpu_record_hash_alloc(struct cpu_event_history *a)
{
struct cpu_event_history *new;
new = XCALLOC(MTYPE_EVENT_STATS, sizeof(struct cpu_event_history));
new->func = a->func;
new->funcname = a->funcname;
return new;
}
static void cpu_record_hash_free(void *a)
{
struct cpu_event_history *hist = a;
XFREE(MTYPE_EVENT_STATS, hist);
}
static void vty_out_cpu_event_history(struct vty *vty,
struct cpu_event_history *a)
{
vty_out(vty,
"%5zu %10zu.%03zu %9zu %8zu %9zu %8zu %9zu %9zu %9zu %10zu",
a->total_active, a->cpu.total / 1000, a->cpu.total % 1000,
a->total_calls, (a->cpu.total / a->total_calls), a->cpu.max,
(a->real.total / a->total_calls), a->real.max,
a->total_cpu_warn, a->total_wall_warn, a->total_starv_warn);
vty_out(vty, " %c%c%c%c%c %s\n",
a->types & (1 << EVENT_READ) ? 'R' : ' ',
a->types & (1 << EVENT_WRITE) ? 'W' : ' ',
a->types & (1 << EVENT_TIMER) ? 'T' : ' ',
a->types & (1 << EVENT_EVENT) ? 'E' : ' ',
a->types & (1 << EVENT_EXECUTE) ? 'X' : ' ', a->funcname);
}
static void cpu_record_hash_print(struct hash_bucket *bucket, void *args[])
{
struct cpu_event_history *totals = args[0];
struct cpu_event_history copy;
struct vty *vty = args[1];
uint8_t *filter = args[2];
struct cpu_event_history *a = bucket->data;
copy.total_active =
atomic_load_explicit(&a->total_active, memory_order_seq_cst);
copy.total_calls =
atomic_load_explicit(&a->total_calls, memory_order_seq_cst);
copy.total_cpu_warn =
atomic_load_explicit(&a->total_cpu_warn, memory_order_seq_cst);
copy.total_wall_warn =
atomic_load_explicit(&a->total_wall_warn, memory_order_seq_cst);
copy.total_starv_warn = atomic_load_explicit(&a->total_starv_warn,
memory_order_seq_cst);
copy.cpu.total =
atomic_load_explicit(&a->cpu.total, memory_order_seq_cst);
copy.cpu.max = atomic_load_explicit(&a->cpu.max, memory_order_seq_cst);
copy.real.total =
atomic_load_explicit(&a->real.total, memory_order_seq_cst);
copy.real.max =
atomic_load_explicit(&a->real.max, memory_order_seq_cst);
copy.types = atomic_load_explicit(&a->types, memory_order_seq_cst);
copy.funcname = a->funcname;
if (!(copy.types & *filter))
return;
vty_out_cpu_event_history(vty, ©);
totals->total_active += copy.total_active;
totals->total_calls += copy.total_calls;
totals->total_cpu_warn += copy.total_cpu_warn;
totals->total_wall_warn += copy.total_wall_warn;
totals->total_starv_warn += copy.total_starv_warn;
totals->real.total += copy.real.total;
if (totals->real.max < copy.real.max)
totals->real.max = copy.real.max;
totals->cpu.total += copy.cpu.total;
if (totals->cpu.max < copy.cpu.max)
totals->cpu.max = copy.cpu.max;
}
static void cpu_record_print(struct vty *vty, uint8_t filter)
{
struct cpu_event_history tmp;
void *args[3] = {&tmp, vty, &filter};
struct event_loop *m;
struct listnode *ln;
if (!cputime_enabled)
vty_out(vty,
"\n"
"Collecting CPU time statistics is currently disabled. Following statistics\n"
"will be zero or may display data from when collection was enabled. Use the\n"
" \"service cputime-stats\" command to start collecting data.\n"
"\nCounters and wallclock times are always maintained and should be accurate.\n");
memset(&tmp, 0, sizeof(tmp));
tmp.funcname = "TOTAL";
tmp.types = filter;
frr_with_mutex (&masters_mtx) {
for (ALL_LIST_ELEMENTS_RO(masters, ln, m)) {
const char *name = m->name ? m->name : "main";
char underline[strlen(name) + 1];
memset(underline, '-', sizeof(underline));
underline[sizeof(underline) - 1] = '\0';
vty_out(vty, "\n");
vty_out(vty, "Showing statistics for pthread %s\n",
name);
vty_out(vty, "-------------------------------%s\n",
underline);
vty_out(vty, "%30s %18s %18s\n", "",
"CPU (user+system):", "Real (wall-clock):");
vty_out(vty,
"Active Runtime(ms) Invoked Avg uSec Max uSecs");
vty_out(vty, " Avg uSec Max uSecs");
vty_out(vty,
" CPU_Warn Wall_Warn Starv_Warn Type Thread\n");
if (m->cpu_record->count)
hash_iterate(
m->cpu_record,
(void (*)(struct hash_bucket *,
void *))cpu_record_hash_print,
args);
else
vty_out(vty, "No data to display yet.\n");
vty_out(vty, "\n");
}
}
vty_out(vty, "\n");
vty_out(vty, "Total thread statistics\n");
vty_out(vty, "-------------------------\n");
vty_out(vty, "%30s %18s %18s\n", "",
"CPU (user+system):", "Real (wall-clock):");
vty_out(vty, "Active Runtime(ms) Invoked Avg uSec Max uSecs");
vty_out(vty, " Avg uSec Max uSecs CPU_Warn Wall_Warn");
vty_out(vty, " Type Thread\n");
if (tmp.total_calls > 0)
vty_out_cpu_event_history(vty, &tmp);
}
static void cpu_record_hash_clear(struct hash_bucket *bucket, void *args[])
{
uint8_t *filter = args[0];
struct hash *cpu_record = args[1];
struct cpu_event_history *a = bucket->data;
if (!(a->types & *filter))
return;
hash_release(cpu_record, bucket->data);
}
static void cpu_record_clear(uint8_t filter)
{
uint8_t *tmp = &filter;
struct event_loop *m;
struct listnode *ln;
frr_with_mutex (&masters_mtx) {
for (ALL_LIST_ELEMENTS_RO(masters, ln, m)) {
frr_with_mutex (&m->mtx) {
void *args[2] = {tmp, m->cpu_record};
hash_iterate(
m->cpu_record,
(void (*)(struct hash_bucket *,
void *))cpu_record_hash_clear,
args);
}
}
}
}
static uint8_t parse_filter(const char *filterstr)
{
int i = 0;
int filter = 0;
while (filterstr[i] != '\0') {
switch (filterstr[i]) {
case 'r':
case 'R':
filter |= (1 << EVENT_READ);
break;
case 'w':
case 'W':
filter |= (1 << EVENT_WRITE);
break;
case 't':
case 'T':
filter |= (1 << EVENT_TIMER);
break;
case 'e':
case 'E':
filter |= (1 << EVENT_EVENT);
break;
case 'x':
case 'X':
filter |= (1 << EVENT_EXECUTE);
break;
default:
break;
}
++i;
}
return filter;
}
DEFUN_NOSH (show_thread_cpu,
show_thread_cpu_cmd,
"show thread cpu [FILTER]",
SHOW_STR
"Thread information\n"
"Thread CPU usage\n"
"Display filter (rwtex)\n")
{
uint8_t filter = (uint8_t)-1U;
int idx = 0;
if (argv_find(argv, argc, "FILTER", &idx)) {
filter = parse_filter(argv[idx]->arg);
if (!filter) {
vty_out(vty,
"Invalid filter \"%s\" specified; must contain at leastone of 'RWTEXB'\n",
argv[idx]->arg);
return CMD_WARNING;
}
}
cpu_record_print(vty, filter);
return CMD_SUCCESS;
}
DEFPY (service_cputime_stats,
service_cputime_stats_cmd,
"[no] service cputime-stats",
NO_STR
"Set up miscellaneous service\n"
"Collect CPU usage statistics\n")
{
cputime_enabled = !no;
return CMD_SUCCESS;
}
DEFPY (service_cputime_warning,
service_cputime_warning_cmd,
"[no] service cputime-warning (1-4294967295)",
NO_STR
"Set up miscellaneous service\n"
"Warn for tasks exceeding CPU usage threshold\n"
"Warning threshold in milliseconds\n")
{
if (no)
cputime_threshold = 0;
else
cputime_threshold = cputime_warning * 1000;
return CMD_SUCCESS;
}
ALIAS (service_cputime_warning,
no_service_cputime_warning_cmd,
"no service cputime-warning",
NO_STR
"Set up miscellaneous service\n"
"Warn for tasks exceeding CPU usage threshold\n")
DEFPY (service_walltime_warning,
service_walltime_warning_cmd,
"[no] service walltime-warning (1-4294967295)",
NO_STR
"Set up miscellaneous service\n"
"Warn for tasks exceeding total wallclock threshold\n"
"Warning threshold in milliseconds\n")
{
if (no)
walltime_threshold = 0;
else
walltime_threshold = walltime_warning * 1000;
return CMD_SUCCESS;
}
ALIAS (service_walltime_warning,
no_service_walltime_warning_cmd,
"no service walltime-warning",
NO_STR
"Set up miscellaneous service\n"
"Warn for tasks exceeding total wallclock threshold\n")
static void show_thread_poll_helper(struct vty *vty, struct event_loop *m)
{
const char *name = m->name ? m->name : "main";
char underline[strlen(name) + 1];
struct event *thread;
uint32_t i;
memset(underline, '-', sizeof(underline));
underline[sizeof(underline) - 1] = '\0';
vty_out(vty, "\nShowing poll FD's for %s\n", name);
vty_out(vty, "----------------------%s\n", underline);
vty_out(vty, "Count: %u/%d\n", (uint32_t)m->handler.pfdcount,
m->fd_limit);
for (i = 0; i < m->handler.pfdcount; i++) {
vty_out(vty, "\t%6d fd:%6d events:%2d revents:%2d\t\t", i,
m->handler.pfds[i].fd, m->handler.pfds[i].events,
m->handler.pfds[i].revents);
if (m->handler.pfds[i].events & POLLIN) {
thread = m->read[m->handler.pfds[i].fd];
if (!thread)
vty_out(vty, "ERROR ");
else
vty_out(vty, "%s ", thread->xref->funcname);
} else
vty_out(vty, " ");
if (m->handler.pfds[i].events & POLLOUT) {
thread = m->write[m->handler.pfds[i].fd];
if (!thread)
vty_out(vty, "ERROR\n");
else
vty_out(vty, "%s\n", thread->xref->funcname);
} else
vty_out(vty, "\n");
}
}
DEFUN_NOSH (show_thread_poll,
show_thread_poll_cmd,
"show thread poll",
SHOW_STR
"Thread information\n"
"Show poll FD's and information\n")
{
struct listnode *node;
struct event_loop *m;
frr_with_mutex (&masters_mtx) {
for (ALL_LIST_ELEMENTS_RO(masters, node, m))
show_thread_poll_helper(vty, m);
}
return CMD_SUCCESS;
}
DEFUN (clear_thread_cpu,
clear_thread_cpu_cmd,
"clear thread cpu [FILTER]",
"Clear stored data in all pthreads\n"
"Thread information\n"
"Thread CPU usage\n"
"Display filter (rwtexb)\n")
{
uint8_t filter = (uint8_t)-1U;
int idx = 0;
if (argv_find(argv, argc, "FILTER", &idx)) {
filter = parse_filter(argv[idx]->arg);
if (!filter) {
vty_out(vty,
"Invalid filter \"%s\" specified; must contain at leastone of 'RWTEXB'\n",
argv[idx]->arg);
return CMD_WARNING;
}
}
cpu_record_clear(filter);
return CMD_SUCCESS;
}
static void show_thread_timers_helper(struct vty *vty, struct event_loop *m)
{
const char *name = m->name ? m->name : "main";
char underline[strlen(name) + 1];
struct event *thread;
memset(underline, '-', sizeof(underline));
underline[sizeof(underline) - 1] = '\0';
vty_out(vty, "\nShowing timers for %s\n", name);
vty_out(vty, "-------------------%s\n", underline);
frr_each (event_timer_list, &m->timer, thread) {
vty_out(vty, " %-50s%pTH\n", thread->hist->funcname, thread);
}
}
DEFPY_NOSH (show_thread_timers,
show_thread_timers_cmd,
"show thread timers",
SHOW_STR
"Thread information\n"
"Show all timers and how long they have in the system\n")
{
struct listnode *node;
struct event_loop *m;
frr_with_mutex (&masters_mtx) {
for (ALL_LIST_ELEMENTS_RO(masters, node, m))
show_thread_timers_helper(vty, m);
}
return CMD_SUCCESS;
}
void event_cmd_init(void)
{
install_element(VIEW_NODE, &show_thread_cpu_cmd);
install_element(VIEW_NODE, &show_thread_poll_cmd);
install_element(ENABLE_NODE, &clear_thread_cpu_cmd);
install_element(CONFIG_NODE, &service_cputime_stats_cmd);
install_element(CONFIG_NODE, &service_cputime_warning_cmd);
install_element(CONFIG_NODE, &no_service_cputime_warning_cmd);
install_element(CONFIG_NODE, &service_walltime_warning_cmd);
install_element(CONFIG_NODE, &no_service_walltime_warning_cmd);
install_element(VIEW_NODE, &show_thread_timers_cmd);
}
/* CLI end ------------------------------------------------------------------ */
static void cancelreq_del(void *cr)
{
XFREE(MTYPE_TMP, cr);
}
/* initializer, only ever called once */
static void initializer(void)
{
pthread_key_create(&thread_current, NULL);
}
struct event_loop *event_master_create(const char *name)
{
struct event_loop *rv;
struct rlimit limit;
pthread_once(&init_once, &initializer);
rv = XCALLOC(MTYPE_EVENT_MASTER, sizeof(struct event_loop));
/* Initialize master mutex */
pthread_mutex_init(&rv->mtx, NULL);
pthread_cond_init(&rv->cancel_cond, NULL);
/* Set name */
name = name ? name : "default";
rv->name = XSTRDUP(MTYPE_EVENT_MASTER, name);
/* Initialize I/O task data structures */
/* Use configured limit if present, ulimit otherwise. */
rv->fd_limit = frr_get_fd_limit();
if (rv->fd_limit == 0) {
getrlimit(RLIMIT_NOFILE, &limit);
rv->fd_limit = (int)limit.rlim_cur;
}
rv->read = XCALLOC(MTYPE_EVENT_POLL,
sizeof(struct event *) * rv->fd_limit);
rv->write = XCALLOC(MTYPE_EVENT_POLL,
sizeof(struct event *) * rv->fd_limit);
char tmhashname[strlen(name) + 32];
snprintf(tmhashname, sizeof(tmhashname), "%s - threadmaster event hash",
name);
rv->cpu_record = hash_create_size(
8, (unsigned int (*)(const void *))cpu_record_hash_key,
(bool (*)(const void *, const void *))cpu_record_hash_cmp,
tmhashname);
event_list_init(&rv->event);
event_list_init(&rv->ready);
event_list_init(&rv->unuse);
event_timer_list_init(&rv->timer);
/* Initialize event_fetch() settings */
rv->spin = true;
rv->handle_signals = true;
/* Set pthread owner, should be updated by actual owner */
rv->owner = pthread_self();
rv->cancel_req = list_new();
rv->cancel_req->del = cancelreq_del;
rv->canceled = true;
/* Initialize pipe poker */
pipe(rv->io_pipe);
set_nonblocking(rv->io_pipe[0]);
set_nonblocking(rv->io_pipe[1]);
/* Initialize data structures for poll() */
rv->handler.pfdsize = rv->fd_limit;
rv->handler.pfdcount = 0;
rv->handler.pfds = XCALLOC(MTYPE_EVENT_MASTER,
sizeof(struct pollfd) * rv->handler.pfdsize);
rv->handler.copy = XCALLOC(MTYPE_EVENT_MASTER,
sizeof(struct pollfd) * rv->handler.pfdsize);
/* add to list of threadmasters */
frr_with_mutex (&masters_mtx) {
if (!masters)
masters = list_new();
listnode_add(masters, rv);
}
return rv;
}
void event_master_set_name(struct event_loop *master, const char *name)
{
frr_with_mutex (&master->mtx) {
XFREE(MTYPE_EVENT_MASTER, master->name);
master->name = XSTRDUP(MTYPE_EVENT_MASTER, name);
}
}
#define EVENT_UNUSED_DEPTH 10
/* Move thread to unuse list. */
static void thread_add_unuse(struct event_loop *m, struct event *thread)
{
pthread_mutex_t mtxc = thread->mtx;
assert(m != NULL && thread != NULL);
thread->hist->total_active--;
memset(thread, 0, sizeof(struct event));
thread->type = EVENT_UNUSED;
/* Restore the thread mutex context. */
thread->mtx = mtxc;
if (event_list_count(&m->unuse) < EVENT_UNUSED_DEPTH) {
event_list_add_tail(&m->unuse, thread);
return;
}
thread_free(m, thread);
}
/* Free all unused thread. */
static void thread_list_free(struct event_loop *m, struct event_list_head *list)
{
struct event *t;
while ((t = event_list_pop(list)))
thread_free(m, t);
}
static void thread_array_free(struct event_loop *m, struct event **thread_array)
{
struct event *t;
int index;
for (index = 0; index < m->fd_limit; ++index) {
t = thread_array[index];
if (t) {
thread_array[index] = NULL;
thread_free(m, t);
}
}
XFREE(MTYPE_EVENT_POLL, thread_array);
}
/*
* event_master_free_unused
*
* As threads are finished with they are put on the
* unuse list for later reuse.
* If we are shutting down, Free up unused threads
* So we can see if we forget to shut anything off
*/
void event_master_free_unused(struct event_loop *m)
{
frr_with_mutex (&m->mtx) {
struct event *t;
while ((t = event_list_pop(&m->unuse)))
thread_free(m, t);
}
}
/* Stop thread scheduler. */
void event_master_free(struct event_loop *m)
{
struct event *t;
frr_with_mutex (&masters_mtx) {
listnode_delete(masters, m);
if (masters->count == 0)
list_delete(&masters);
}
thread_array_free(m, m->read);
thread_array_free(m, m->write);
while ((t = event_timer_list_pop(&m->timer)))
thread_free(m, t);
thread_list_free(m, &m->event);
thread_list_free(m, &m->ready);
thread_list_free(m, &m->unuse);
pthread_mutex_destroy(&m->mtx);
pthread_cond_destroy(&m->cancel_cond);
close(m->io_pipe[0]);
close(m->io_pipe[1]);
list_delete(&m->cancel_req);
m->cancel_req = NULL;
hash_clean_and_free(&m->cpu_record, cpu_record_hash_free);
XFREE(MTYPE_EVENT_MASTER, m->name);
XFREE(MTYPE_EVENT_MASTER, m->handler.pfds);
XFREE(MTYPE_EVENT_MASTER, m->handler.copy);
XFREE(MTYPE_EVENT_MASTER, m);
}
/* Return remain time in milliseconds. */
unsigned long event_timer_remain_msec(struct event *thread)
{
int64_t remain;
if (!event_is_scheduled(thread))
return 0;
frr_with_mutex (&thread->mtx) {
remain = monotime_until(&thread->u.sands, NULL) / 1000LL;
}
return remain < 0 ? 0 : remain;
}
/* Return remain time in seconds. */
unsigned long event_timer_remain_second(struct event *thread)
{
return event_timer_remain_msec(thread) / 1000LL;
}
struct timeval event_timer_remain(struct event *thread)
{
struct timeval remain;
frr_with_mutex (&thread->mtx) {
monotime_until(&thread->u.sands, &remain);
}
return remain;
}
static int time_hhmmss(char *buf, int buf_size, long sec)
{
long hh;
long mm;
int wr;
assert(buf_size >= 8);
hh = sec / 3600;
sec %= 3600;
mm = sec / 60;
sec %= 60;
wr = snprintf(buf, buf_size, "%02ld:%02ld:%02ld", hh, mm, sec);
return wr != 8;
}
char *event_timer_to_hhmmss(char *buf, int buf_size, struct event *t_timer)
{
if (t_timer)
time_hhmmss(buf, buf_size, event_timer_remain_second(t_timer));
else
snprintf(buf, buf_size, "--:--:--");
return buf;
}
/* Get new thread. */
static struct event *thread_get(struct event_loop *m, uint8_t type,
void (*func)(struct event *), void *arg,
const struct xref_eventsched *xref)
{
struct event *thread = event_list_pop(&m->unuse);
struct cpu_event_history tmp;
if (!thread) {
thread = XCALLOC(MTYPE_THREAD, sizeof(struct event));
/* mutex only needs to be initialized at struct creation. */
pthread_mutex_init(&thread->mtx, NULL);
m->alloc++;
}
thread->type = type;
thread->add_type = type;
thread->master = m;
thread->arg = arg;
thread->yield = EVENT_YIELD_TIME_SLOT; /* default */
thread->ref = NULL;
thread->ignore_timer_late = false;
/*
* So if the passed in funcname is not what we have
* stored that means the thread->hist needs to be
* updated. We keep the last one around in unused
* under the assumption that we are probably
* going to immediately allocate the same
* type of thread.
* This hopefully saves us some serious
* hash_get lookups.
*/
if ((thread->xref && thread->xref->funcname != xref->funcname)
|| thread->func != func) {
tmp.func = func;
tmp.funcname = xref->funcname;
thread->hist =
hash_get(m->cpu_record, &tmp,
(void *(*)(void *))cpu_record_hash_alloc);
}
thread->hist->total_active++;
thread->func = func;
thread->xref = xref;
return thread;
}
static void thread_free(struct event_loop *master, struct event *thread)
{
/* Update statistics. */
assert(master->alloc > 0);
master->alloc--;
/* Free allocated resources. */
pthread_mutex_destroy(&thread->mtx);
XFREE(MTYPE_THREAD, thread);
}
static int fd_poll(struct event_loop *m, const struct timeval *timer_wait,
bool *eintr_p)
{
sigset_t origsigs;
unsigned char trash[64];
nfds_t count = m->handler.copycount;
/*
* If timer_wait is null here, that means poll() should block
* indefinitely, unless the event_master has overridden it by setting
* ->selectpoll_timeout.
*
* If the value is positive, it specifies the maximum number of
* milliseconds to wait. If the timeout is -1, it specifies that
* we should never wait and always return immediately even if no
* event is detected. If the value is zero, the behavior is default.
*/
int timeout = -1;
/* number of file descriptors with events */
int num;
if (timer_wait != NULL && m->selectpoll_timeout == 0) {
/* use the default value */
timeout = (timer_wait->tv_sec * 1000)
+ (timer_wait->tv_usec / 1000);
} else if (m->selectpoll_timeout > 0) {
/* use the user's timeout */
timeout = m->selectpoll_timeout;
} else if (m->selectpoll_timeout < 0) {
/* effect a poll (return immediately) */
timeout = 0;
}
zlog_tls_buffer_flush();
rcu_read_unlock();
rcu_assert_read_unlocked();
/* add poll pipe poker */
assert(count + 1 < m->handler.pfdsize);
m->handler.copy[count].fd = m->io_pipe[0];
m->handler.copy[count].events = POLLIN;
m->handler.copy[count].revents = 0x00;
/* We need to deal with a signal-handling race here: we
* don't want to miss a crucial signal, such as SIGTERM or SIGINT,
* that may arrive just before we enter poll(). We will block the
* key signals, then check whether any have arrived - if so, we return
* before calling poll(). If not, we'll re-enable the signals
* in the ppoll() call.
*/
sigemptyset(&origsigs);
if (m->handle_signals) {
/* Main pthread that handles the app signals */
if (frr_sigevent_check(&origsigs)) {
/* Signal to process - restore signal mask and return */
pthread_sigmask(SIG_SETMASK, &origsigs, NULL);
num = -1;
*eintr_p = true;
goto done;
}
} else {
/* Don't make any changes for the non-main pthreads */
pthread_sigmask(SIG_SETMASK, NULL, &origsigs);
}
#if defined(HAVE_PPOLL)
struct timespec ts, *tsp;
if (timeout >= 0) {
ts.tv_sec = timeout / 1000;
ts.tv_nsec = (timeout % 1000) * 1000000;
tsp = &ts;
} else
tsp = NULL;
num = ppoll(m->handler.copy, count + 1, tsp, &origsigs);
pthread_sigmask(SIG_SETMASK, &origsigs, NULL);
#else
/* Not ideal - there is a race after we restore the signal mask */
pthread_sigmask(SIG_SETMASK, &origsigs, NULL);
num = poll(m->handler.copy, count + 1, timeout);
#endif
done:
if (num < 0 && errno == EINTR)
*eintr_p = true;
if (num > 0 && m->handler.copy[count].revents != 0 && num--)
while (read(m->io_pipe[0], &trash, sizeof(trash)) > 0)
;
rcu_read_lock();
return num;
}
/* Add new read thread. */
void _event_add_read_write(const struct xref_eventsched *xref,
struct event_loop *m, void (*func)(struct event *),
void *arg, int fd, struct event **t_ptr)
{
int dir = xref->event_type;
struct event *thread = NULL;
struct event **thread_array;
if (dir == EVENT_READ)
frrtrace(9, frr_libfrr, schedule_read, m,
xref->funcname, xref->xref.file, xref->xref.line,
t_ptr, fd, 0, arg, 0);
else
frrtrace(9, frr_libfrr, schedule_write, m,
xref->funcname, xref->xref.file, xref->xref.line,
t_ptr, fd, 0, arg, 0);
assert(fd >= 0);
if (fd >= m->fd_limit)
assert(!"Number of FD's open is greater than FRR currently configured to handle, aborting");
frr_with_mutex (&m->mtx) {
/* Thread is already scheduled; don't reschedule */
if (t_ptr && *t_ptr)
break;
/* default to a new pollfd */
nfds_t queuepos = m->handler.pfdcount;
if (dir == EVENT_READ)
thread_array = m->read;
else
thread_array = m->write;
/*
* if we already have a pollfd for our file descriptor, find and
* use it
*/
for (nfds_t i = 0; i < m->handler.pfdcount; i++)
if (m->handler.pfds[i].fd == fd) {
queuepos = i;
#ifdef DEV_BUILD
/*
* What happens if we have a thread already
* created for this event?
*/
if (thread_array[fd])