1 /* Thread management routine
2 * Copyright (C) 1998, 2000 Kunihiro Ishiguro <kunihiro@zebra.org>
4 * This file is part of GNU Zebra.
6 * GNU Zebra is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2, or (at your option) any
11 * GNU Zebra is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; see the file COPYING; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24 #include <sys/resource.h>
35 #include "frratomic.h"
36 #include "lib_errors.h"
38 DEFINE_MTYPE_STATIC(LIB
, THREAD
, "Thread")
39 DEFINE_MTYPE_STATIC(LIB
, THREAD_MASTER
, "Thread master")
40 DEFINE_MTYPE_STATIC(LIB
, THREAD_POLL
, "Thread Poll Info")
41 DEFINE_MTYPE_STATIC(LIB
, THREAD_STATS
, "Thread stats")
43 #if defined(__APPLE__)
44 #include <mach/mach.h>
45 #include <mach/mach_time.h>
50 static unsigned char wakebyte = 0x01; \
51 write(m->io_pipe[1], &wakebyte, 1); \
54 /* control variable for initializer */
55 pthread_once_t init_once
= PTHREAD_ONCE_INIT
;
56 pthread_key_t thread_current
;
58 pthread_mutex_t masters_mtx
= PTHREAD_MUTEX_INITIALIZER
;
59 static struct list
*masters
;
61 static void thread_free(struct thread_master
*master
, struct thread
*thread
);
63 /* CLI start ---------------------------------------------------------------- */
64 static unsigned int cpu_record_hash_key(struct cpu_thread_history
*a
)
66 int size
= sizeof(a
->func
);
68 return jhash(&a
->func
, size
, 0);
71 static bool cpu_record_hash_cmp(const struct cpu_thread_history
*a
,
72 const struct cpu_thread_history
*b
)
74 return a
->func
== b
->func
;
77 static void *cpu_record_hash_alloc(struct cpu_thread_history
*a
)
79 struct cpu_thread_history
*new;
80 new = XCALLOC(MTYPE_THREAD_STATS
, sizeof(struct cpu_thread_history
));
82 new->funcname
= a
->funcname
;
86 static void cpu_record_hash_free(void *a
)
88 struct cpu_thread_history
*hist
= a
;
90 XFREE(MTYPE_THREAD_STATS
, hist
);
93 static void vty_out_cpu_thread_history(struct vty
*vty
,
94 struct cpu_thread_history
*a
)
96 vty_out(vty
, "%5d %10lu.%03lu %9u %8lu %9lu %8lu %9lu", a
->total_active
,
97 a
->cpu
.total
/ 1000, a
->cpu
.total
% 1000, a
->total_calls
,
98 a
->cpu
.total
/ a
->total_calls
, a
->cpu
.max
,
99 a
->real
.total
/ a
->total_calls
, a
->real
.max
);
100 vty_out(vty
, " %c%c%c%c%c %s\n",
101 a
->types
& (1 << THREAD_READ
) ? 'R' : ' ',
102 a
->types
& (1 << THREAD_WRITE
) ? 'W' : ' ',
103 a
->types
& (1 << THREAD_TIMER
) ? 'T' : ' ',
104 a
->types
& (1 << THREAD_EVENT
) ? 'E' : ' ',
105 a
->types
& (1 << THREAD_EXECUTE
) ? 'X' : ' ', a
->funcname
);
108 static void cpu_record_hash_print(struct hash_backet
*bucket
, void *args
[])
110 struct cpu_thread_history
*totals
= args
[0];
111 struct cpu_thread_history copy
;
112 struct vty
*vty
= args
[1];
113 uint8_t *filter
= args
[2];
115 struct cpu_thread_history
*a
= bucket
->data
;
118 atomic_load_explicit(&a
->total_active
, memory_order_seq_cst
);
120 atomic_load_explicit(&a
->total_calls
, memory_order_seq_cst
);
122 atomic_load_explicit(&a
->cpu
.total
, memory_order_seq_cst
);
123 copy
.cpu
.max
= atomic_load_explicit(&a
->cpu
.max
, memory_order_seq_cst
);
125 atomic_load_explicit(&a
->real
.total
, memory_order_seq_cst
);
127 atomic_load_explicit(&a
->real
.max
, memory_order_seq_cst
);
128 copy
.types
= atomic_load_explicit(&a
->types
, memory_order_seq_cst
);
129 copy
.funcname
= a
->funcname
;
131 if (!(copy
.types
& *filter
))
134 vty_out_cpu_thread_history(vty
, ©
);
135 totals
->total_active
+= copy
.total_active
;
136 totals
->total_calls
+= copy
.total_calls
;
137 totals
->real
.total
+= copy
.real
.total
;
138 if (totals
->real
.max
< copy
.real
.max
)
139 totals
->real
.max
= copy
.real
.max
;
140 totals
->cpu
.total
+= copy
.cpu
.total
;
141 if (totals
->cpu
.max
< copy
.cpu
.max
)
142 totals
->cpu
.max
= copy
.cpu
.max
;
145 static void cpu_record_print(struct vty
*vty
, uint8_t filter
)
147 struct cpu_thread_history tmp
;
148 void *args
[3] = {&tmp
, vty
, &filter
};
149 struct thread_master
*m
;
152 memset(&tmp
, 0, sizeof tmp
);
153 tmp
.funcname
= "TOTAL";
156 pthread_mutex_lock(&masters_mtx
);
158 for (ALL_LIST_ELEMENTS_RO(masters
, ln
, m
)) {
159 const char *name
= m
->name
? m
->name
: "main";
161 char underline
[strlen(name
) + 1];
162 memset(underline
, '-', sizeof(underline
));
163 underline
[sizeof(underline
) - 1] = '\0';
166 vty_out(vty
, "Showing statistics for pthread %s\n",
168 vty_out(vty
, "-------------------------------%s\n",
170 vty_out(vty
, "%21s %18s %18s\n", "",
171 "CPU (user+system):", "Real (wall-clock):");
173 "Active Runtime(ms) Invoked Avg uSec Max uSecs");
174 vty_out(vty
, " Avg uSec Max uSecs");
175 vty_out(vty
, " Type Thread\n");
177 if (m
->cpu_record
->count
)
180 (void (*)(struct hash_backet
*,
181 void *))cpu_record_hash_print
,
184 vty_out(vty
, "No data to display yet.\n");
189 pthread_mutex_unlock(&masters_mtx
);
192 vty_out(vty
, "Total thread statistics\n");
193 vty_out(vty
, "-------------------------\n");
194 vty_out(vty
, "%21s %18s %18s\n", "",
195 "CPU (user+system):", "Real (wall-clock):");
196 vty_out(vty
, "Active Runtime(ms) Invoked Avg uSec Max uSecs");
197 vty_out(vty
, " Avg uSec Max uSecs");
198 vty_out(vty
, " Type Thread\n");
200 if (tmp
.total_calls
> 0)
201 vty_out_cpu_thread_history(vty
, &tmp
);
204 static void cpu_record_hash_clear(struct hash_backet
*bucket
, void *args
[])
206 uint8_t *filter
= args
[0];
207 struct hash
*cpu_record
= args
[1];
209 struct cpu_thread_history
*a
= bucket
->data
;
211 if (!(a
->types
& *filter
))
214 hash_release(cpu_record
, bucket
->data
);
217 static void cpu_record_clear(uint8_t filter
)
219 uint8_t *tmp
= &filter
;
220 struct thread_master
*m
;
223 pthread_mutex_lock(&masters_mtx
);
225 for (ALL_LIST_ELEMENTS_RO(masters
, ln
, m
)) {
226 pthread_mutex_lock(&m
->mtx
);
228 void *args
[2] = {tmp
, m
->cpu_record
};
231 (void (*)(struct hash_backet
*,
232 void *))cpu_record_hash_clear
,
235 pthread_mutex_unlock(&m
->mtx
);
238 pthread_mutex_unlock(&masters_mtx
);
241 static uint8_t parse_filter(const char *filterstr
)
246 while (filterstr
[i
] != '\0') {
247 switch (filterstr
[i
]) {
250 filter
|= (1 << THREAD_READ
);
254 filter
|= (1 << THREAD_WRITE
);
258 filter
|= (1 << THREAD_TIMER
);
262 filter
|= (1 << THREAD_EVENT
);
266 filter
|= (1 << THREAD_EXECUTE
);
276 DEFUN (show_thread_cpu
,
278 "show thread cpu [FILTER]",
280 "Thread information\n"
282 "Display filter (rwtexb)\n")
284 uint8_t filter
= (uint8_t)-1U;
287 if (argv_find(argv
, argc
, "FILTER", &idx
)) {
288 filter
= parse_filter(argv
[idx
]->arg
);
291 "Invalid filter \"%s\" specified; must contain at least"
298 cpu_record_print(vty
, filter
);
302 static void show_thread_poll_helper(struct vty
*vty
, struct thread_master
*m
)
304 const char *name
= m
->name
? m
->name
: "main";
305 char underline
[strlen(name
) + 1];
308 memset(underline
, '-', sizeof(underline
));
309 underline
[sizeof(underline
) - 1] = '\0';
311 vty_out(vty
, "\nShowing poll FD's for %s\n", name
);
312 vty_out(vty
, "----------------------%s\n", underline
);
313 vty_out(vty
, "Count: %u\n", (uint32_t)m
->handler
.pfdcount
);
314 for (i
= 0; i
< m
->handler
.pfdcount
; i
++)
315 vty_out(vty
, "\t%6d fd:%6d events:%2d revents:%2d\n", i
,
316 m
->handler
.pfds
[i
].fd
,
317 m
->handler
.pfds
[i
].events
,
318 m
->handler
.pfds
[i
].revents
);
321 DEFUN (show_thread_poll
,
322 show_thread_poll_cmd
,
325 "Thread information\n"
326 "Show poll FD's and information\n")
328 struct listnode
*node
;
329 struct thread_master
*m
;
331 pthread_mutex_lock(&masters_mtx
);
333 for (ALL_LIST_ELEMENTS_RO(masters
, node
, m
)) {
334 show_thread_poll_helper(vty
, m
);
337 pthread_mutex_unlock(&masters_mtx
);
343 DEFUN (clear_thread_cpu
,
344 clear_thread_cpu_cmd
,
345 "clear thread cpu [FILTER]",
346 "Clear stored data in all pthreads\n"
347 "Thread information\n"
349 "Display filter (rwtexb)\n")
351 uint8_t filter
= (uint8_t)-1U;
354 if (argv_find(argv
, argc
, "FILTER", &idx
)) {
355 filter
= parse_filter(argv
[idx
]->arg
);
358 "Invalid filter \"%s\" specified; must contain at least"
365 cpu_record_clear(filter
);
369 void thread_cmd_init(void)
371 install_element(VIEW_NODE
, &show_thread_cpu_cmd
);
372 install_element(VIEW_NODE
, &show_thread_poll_cmd
);
373 install_element(ENABLE_NODE
, &clear_thread_cpu_cmd
);
375 /* CLI end ------------------------------------------------------------------ */
378 static int thread_timer_cmp(void *a
, void *b
)
380 struct thread
*thread_a
= a
;
381 struct thread
*thread_b
= b
;
383 if (timercmp(&thread_a
->u
.sands
, &thread_b
->u
.sands
, <))
385 if (timercmp(&thread_a
->u
.sands
, &thread_b
->u
.sands
, >))
390 static void thread_timer_update(void *node
, int actual_position
)
392 struct thread
*thread
= node
;
394 thread
->index
= actual_position
;
397 static void cancelreq_del(void *cr
)
399 XFREE(MTYPE_TMP
, cr
);
402 /* initializer, only ever called once */
403 static void initializer()
405 pthread_key_create(&thread_current
, NULL
);
408 struct thread_master
*thread_master_create(const char *name
)
410 struct thread_master
*rv
;
413 pthread_once(&init_once
, &initializer
);
415 rv
= XCALLOC(MTYPE_THREAD_MASTER
, sizeof(struct thread_master
));
419 /* Initialize master mutex */
420 pthread_mutex_init(&rv
->mtx
, NULL
);
421 pthread_cond_init(&rv
->cancel_cond
, NULL
);
424 rv
->name
= name
? XSTRDUP(MTYPE_THREAD_MASTER
, name
) : NULL
;
426 /* Initialize I/O task data structures */
427 getrlimit(RLIMIT_NOFILE
, &limit
);
428 rv
->fd_limit
= (int)limit
.rlim_cur
;
429 rv
->read
= XCALLOC(MTYPE_THREAD_POLL
,
430 sizeof(struct thread
*) * rv
->fd_limit
);
432 rv
->write
= XCALLOC(MTYPE_THREAD_POLL
,
433 sizeof(struct thread
*) * rv
->fd_limit
);
435 rv
->cpu_record
= hash_create_size(
436 8, (unsigned int (*)(void *))cpu_record_hash_key
,
437 (bool (*)(const void *, const void *))cpu_record_hash_cmp
,
441 /* Initialize the timer queues */
442 rv
->timer
= pqueue_create();
443 rv
->timer
->cmp
= thread_timer_cmp
;
444 rv
->timer
->update
= thread_timer_update
;
446 /* Initialize thread_fetch() settings */
448 rv
->handle_signals
= true;
450 /* Set pthread owner, should be updated by actual owner */
451 rv
->owner
= pthread_self();
452 rv
->cancel_req
= list_new();
453 rv
->cancel_req
->del
= cancelreq_del
;
456 /* Initialize pipe poker */
458 set_nonblocking(rv
->io_pipe
[0]);
459 set_nonblocking(rv
->io_pipe
[1]);
461 /* Initialize data structures for poll() */
462 rv
->handler
.pfdsize
= rv
->fd_limit
;
463 rv
->handler
.pfdcount
= 0;
464 rv
->handler
.pfds
= XCALLOC(MTYPE_THREAD_MASTER
,
465 sizeof(struct pollfd
) * rv
->handler
.pfdsize
);
466 rv
->handler
.copy
= XCALLOC(MTYPE_THREAD_MASTER
,
467 sizeof(struct pollfd
) * rv
->handler
.pfdsize
);
469 /* add to list of threadmasters */
470 pthread_mutex_lock(&masters_mtx
);
473 masters
= list_new();
475 listnode_add(masters
, rv
);
477 pthread_mutex_unlock(&masters_mtx
);
482 void thread_master_set_name(struct thread_master
*master
, const char *name
)
484 pthread_mutex_lock(&master
->mtx
);
487 XFREE(MTYPE_THREAD_MASTER
, master
->name
);
488 master
->name
= XSTRDUP(MTYPE_THREAD_MASTER
, name
);
490 pthread_mutex_unlock(&master
->mtx
);
493 /* Add a new thread to the list. */
494 static void thread_list_add(struct thread_list
*list
, struct thread
*thread
)
497 thread
->prev
= list
->tail
;
499 list
->tail
->next
= thread
;
506 /* Delete a thread from the list. */
507 static struct thread
*thread_list_delete(struct thread_list
*list
,
508 struct thread
*thread
)
511 thread
->next
->prev
= thread
->prev
;
513 list
->tail
= thread
->prev
;
515 thread
->prev
->next
= thread
->next
;
517 list
->head
= thread
->next
;
518 thread
->next
= thread
->prev
= NULL
;
523 /* Thread list is empty or not. */
524 static int thread_empty(struct thread_list
*list
)
526 return list
->head
? 0 : 1;
529 /* Delete top of the list and return it. */
530 static struct thread
*thread_trim_head(struct thread_list
*list
)
532 if (!thread_empty(list
))
533 return thread_list_delete(list
, list
->head
);
537 #define THREAD_UNUSED_DEPTH 10
539 /* Move thread to unuse list. */
540 static void thread_add_unuse(struct thread_master
*m
, struct thread
*thread
)
542 pthread_mutex_t mtxc
= thread
->mtx
;
544 assert(m
!= NULL
&& thread
!= NULL
);
545 assert(thread
->next
== NULL
);
546 assert(thread
->prev
== NULL
);
548 thread
->hist
->total_active
--;
549 memset(thread
, 0, sizeof(struct thread
));
550 thread
->type
= THREAD_UNUSED
;
552 /* Restore the thread mutex context. */
555 if (m
->unuse
.count
< THREAD_UNUSED_DEPTH
) {
556 thread_list_add(&m
->unuse
, thread
);
560 thread_free(m
, thread
);
563 /* Free all unused thread. */
564 static void thread_list_free(struct thread_master
*m
, struct thread_list
*list
)
569 for (t
= list
->head
; t
; t
= next
) {
576 static void thread_array_free(struct thread_master
*m
,
577 struct thread
**thread_array
)
582 for (index
= 0; index
< m
->fd_limit
; ++index
) {
583 t
= thread_array
[index
];
585 thread_array
[index
] = NULL
;
589 XFREE(MTYPE_THREAD_POLL
, thread_array
);
592 static void thread_queue_free(struct thread_master
*m
, struct pqueue
*queue
)
596 for (i
= 0; i
< queue
->size
; i
++)
597 thread_free(m
, queue
->array
[i
]);
599 pqueue_delete(queue
);
603 * thread_master_free_unused
605 * As threads are finished with they are put on the
606 * unuse list for later reuse.
607 * If we are shutting down, Free up unused threads
608 * So we can see if we forget to shut anything off
610 void thread_master_free_unused(struct thread_master
*m
)
612 pthread_mutex_lock(&m
->mtx
);
615 while ((t
= thread_trim_head(&m
->unuse
)) != NULL
) {
619 pthread_mutex_unlock(&m
->mtx
);
622 /* Stop thread scheduler. */
623 void thread_master_free(struct thread_master
*m
)
625 pthread_mutex_lock(&masters_mtx
);
627 listnode_delete(masters
, m
);
628 if (masters
->count
== 0) {
629 list_delete(&masters
);
632 pthread_mutex_unlock(&masters_mtx
);
634 thread_array_free(m
, m
->read
);
635 thread_array_free(m
, m
->write
);
636 thread_queue_free(m
, m
->timer
);
637 thread_list_free(m
, &m
->event
);
638 thread_list_free(m
, &m
->ready
);
639 thread_list_free(m
, &m
->unuse
);
640 pthread_mutex_destroy(&m
->mtx
);
641 pthread_cond_destroy(&m
->cancel_cond
);
642 close(m
->io_pipe
[0]);
643 close(m
->io_pipe
[1]);
644 list_delete(&m
->cancel_req
);
645 m
->cancel_req
= NULL
;
647 hash_clean(m
->cpu_record
, cpu_record_hash_free
);
648 hash_free(m
->cpu_record
);
649 m
->cpu_record
= NULL
;
652 XFREE(MTYPE_THREAD_MASTER
, m
->name
);
653 XFREE(MTYPE_THREAD_MASTER
, m
->handler
.pfds
);
654 XFREE(MTYPE_THREAD_MASTER
, m
->handler
.copy
);
655 XFREE(MTYPE_THREAD_MASTER
, m
);
658 /* Return remain time in second. */
659 unsigned long thread_timer_remain_second(struct thread
*thread
)
663 pthread_mutex_lock(&thread
->mtx
);
665 remain
= monotime_until(&thread
->u
.sands
, NULL
) / 1000000LL;
667 pthread_mutex_unlock(&thread
->mtx
);
669 return remain
< 0 ? 0 : remain
;
672 #define debugargdef const char *funcname, const char *schedfrom, int fromln
673 #define debugargpass funcname, schedfrom, fromln
675 struct timeval
thread_timer_remain(struct thread
*thread
)
677 struct timeval remain
;
678 pthread_mutex_lock(&thread
->mtx
);
680 monotime_until(&thread
->u
.sands
, &remain
);
682 pthread_mutex_unlock(&thread
->mtx
);
686 /* Get new thread. */
687 static struct thread
*thread_get(struct thread_master
*m
, uint8_t type
,
688 int (*func
)(struct thread
*), void *arg
,
691 struct thread
*thread
= thread_trim_head(&m
->unuse
);
692 struct cpu_thread_history tmp
;
695 thread
= XCALLOC(MTYPE_THREAD
, sizeof(struct thread
));
696 /* mutex only needs to be initialized at struct creation. */
697 pthread_mutex_init(&thread
->mtx
, NULL
);
702 thread
->add_type
= type
;
706 thread
->yield
= THREAD_YIELD_TIME_SLOT
; /* default */
710 * So if the passed in funcname is not what we have
711 * stored that means the thread->hist needs to be
712 * updated. We keep the last one around in unused
713 * under the assumption that we are probably
714 * going to immediately allocate the same
716 * This hopefully saves us some serious
719 if (thread
->funcname
!= funcname
|| thread
->func
!= func
) {
721 tmp
.funcname
= funcname
;
723 hash_get(m
->cpu_record
, &tmp
,
724 (void *(*)(void *))cpu_record_hash_alloc
);
726 thread
->hist
->total_active
++;
728 thread
->funcname
= funcname
;
729 thread
->schedfrom
= schedfrom
;
730 thread
->schedfrom_line
= fromln
;
735 static void thread_free(struct thread_master
*master
, struct thread
*thread
)
737 /* Update statistics. */
738 assert(master
->alloc
> 0);
741 /* Free allocated resources. */
742 pthread_mutex_destroy(&thread
->mtx
);
743 XFREE(MTYPE_THREAD
, thread
);
746 static int fd_poll(struct thread_master
*m
, struct pollfd
*pfds
, nfds_t pfdsize
,
747 nfds_t count
, const struct timeval
*timer_wait
)
749 /* If timer_wait is null here, that means poll() should block
751 * unless the thread_master has overriden it by setting
752 * ->selectpoll_timeout.
753 * If the value is positive, it specifies the maximum number of
755 * to wait. If the timeout is -1, it specifies that we should never wait
757 * always return immediately even if no event is detected. If the value
759 * zero, the behavior is default. */
762 /* number of file descriptors with events */
765 if (timer_wait
!= NULL
766 && m
->selectpoll_timeout
== 0) // use the default value
767 timeout
= (timer_wait
->tv_sec
* 1000)
768 + (timer_wait
->tv_usec
/ 1000);
769 else if (m
->selectpoll_timeout
> 0) // use the user's timeout
770 timeout
= m
->selectpoll_timeout
;
771 else if (m
->selectpoll_timeout
772 < 0) // effect a poll (return immediately)
775 /* add poll pipe poker */
776 assert(count
+ 1 < pfdsize
);
777 pfds
[count
].fd
= m
->io_pipe
[0];
778 pfds
[count
].events
= POLLIN
;
779 pfds
[count
].revents
= 0x00;
781 num
= poll(pfds
, count
+ 1, timeout
);
783 unsigned char trash
[64];
784 if (num
> 0 && pfds
[count
].revents
!= 0 && num
--)
785 while (read(m
->io_pipe
[0], &trash
, sizeof(trash
)) > 0)
791 /* Add new read thread. */
792 struct thread
*funcname_thread_add_read_write(int dir
, struct thread_master
*m
,
793 int (*func
)(struct thread
*),
795 struct thread
**t_ptr
,
798 struct thread
*thread
= NULL
;
800 assert(fd
>= 0 && fd
< m
->fd_limit
);
801 pthread_mutex_lock(&m
->mtx
);
804 && *t_ptr
) // thread is already scheduled; don't reschedule
806 pthread_mutex_unlock(&m
->mtx
);
810 /* default to a new pollfd */
811 nfds_t queuepos
= m
->handler
.pfdcount
;
813 /* if we already have a pollfd for our file descriptor, find and
815 for (nfds_t i
= 0; i
< m
->handler
.pfdcount
; i
++)
816 if (m
->handler
.pfds
[i
].fd
== fd
) {
821 /* make sure we have room for this fd + pipe poker fd */
822 assert(queuepos
+ 1 < m
->handler
.pfdsize
);
824 thread
= thread_get(m
, dir
, func
, arg
, debugargpass
);
826 m
->handler
.pfds
[queuepos
].fd
= fd
;
827 m
->handler
.pfds
[queuepos
].events
|=
828 (dir
== THREAD_READ
? POLLIN
: POLLOUT
);
830 if (queuepos
== m
->handler
.pfdcount
)
831 m
->handler
.pfdcount
++;
834 pthread_mutex_lock(&thread
->mtx
);
837 if (dir
== THREAD_READ
)
838 m
->read
[thread
->u
.fd
] = thread
;
840 m
->write
[thread
->u
.fd
] = thread
;
842 pthread_mutex_unlock(&thread
->mtx
);
852 pthread_mutex_unlock(&m
->mtx
);
857 static struct thread
*
858 funcname_thread_add_timer_timeval(struct thread_master
*m
,
859 int (*func
)(struct thread
*), int type
,
860 void *arg
, struct timeval
*time_relative
,
861 struct thread
**t_ptr
, debugargdef
)
863 struct thread
*thread
;
864 struct pqueue
*queue
;
868 assert(type
== THREAD_TIMER
);
869 assert(time_relative
);
871 pthread_mutex_lock(&m
->mtx
);
874 && *t_ptr
) // thread is already scheduled; don't reschedule
876 pthread_mutex_unlock(&m
->mtx
);
881 thread
= thread_get(m
, type
, func
, arg
, debugargpass
);
883 pthread_mutex_lock(&thread
->mtx
);
885 monotime(&thread
->u
.sands
);
886 timeradd(&thread
->u
.sands
, time_relative
,
888 pqueue_enqueue(thread
, queue
);
894 pthread_mutex_unlock(&thread
->mtx
);
898 pthread_mutex_unlock(&m
->mtx
);
904 /* Add timer event thread. */
905 struct thread
*funcname_thread_add_timer(struct thread_master
*m
,
906 int (*func
)(struct thread
*),
907 void *arg
, long timer
,
908 struct thread
**t_ptr
, debugargdef
)
917 return funcname_thread_add_timer_timeval(m
, func
, THREAD_TIMER
, arg
,
918 &trel
, t_ptr
, debugargpass
);
921 /* Add timer event thread with "millisecond" resolution */
922 struct thread
*funcname_thread_add_timer_msec(struct thread_master
*m
,
923 int (*func
)(struct thread
*),
924 void *arg
, long timer
,
925 struct thread
**t_ptr
,
932 trel
.tv_sec
= timer
/ 1000;
933 trel
.tv_usec
= 1000 * (timer
% 1000);
935 return funcname_thread_add_timer_timeval(m
, func
, THREAD_TIMER
, arg
,
936 &trel
, t_ptr
, debugargpass
);
939 /* Add timer event thread with "millisecond" resolution */
940 struct thread
*funcname_thread_add_timer_tv(struct thread_master
*m
,
941 int (*func
)(struct thread
*),
942 void *arg
, struct timeval
*tv
,
943 struct thread
**t_ptr
, debugargdef
)
945 return funcname_thread_add_timer_timeval(m
, func
, THREAD_TIMER
, arg
, tv
,
946 t_ptr
, debugargpass
);
949 /* Add simple event thread. */
950 struct thread
*funcname_thread_add_event(struct thread_master
*m
,
951 int (*func
)(struct thread
*),
953 struct thread
**t_ptr
, debugargdef
)
955 struct thread
*thread
;
959 pthread_mutex_lock(&m
->mtx
);
962 && *t_ptr
) // thread is already scheduled; don't reschedule
964 pthread_mutex_unlock(&m
->mtx
);
968 thread
= thread_get(m
, THREAD_EVENT
, func
, arg
, debugargpass
);
969 pthread_mutex_lock(&thread
->mtx
);
972 thread_list_add(&m
->event
, thread
);
974 pthread_mutex_unlock(&thread
->mtx
);
983 pthread_mutex_unlock(&m
->mtx
);
988 /* Thread cancellation ------------------------------------------------------ */
991 * NOT's out the .events field of pollfd corresponding to the given file
992 * descriptor. The event to be NOT'd is passed in the 'state' parameter.
994 * This needs to happen for both copies of pollfd's. See 'thread_fetch'
995 * implementation for details.
999 * @param state the event to cancel. One or more (OR'd together) of the
1004 static void thread_cancel_rw(struct thread_master
*master
, int fd
, short state
)
1008 /* Cancel POLLHUP too just in case some bozo set it */
1011 /* find the index of corresponding pollfd */
1014 for (i
= 0; i
< master
->handler
.pfdcount
; i
++)
1015 if (master
->handler
.pfds
[i
].fd
== fd
) {
1022 "[!] Received cancellation request for nonexistent rw job");
1023 zlog_debug("[!] threadmaster: %s | fd: %d",
1024 master
->name
? master
->name
: "", fd
);
1028 /* NOT out event. */
1029 master
->handler
.pfds
[i
].events
&= ~(state
);
1031 /* If all events are canceled, delete / resize the pollfd array. */
1032 if (master
->handler
.pfds
[i
].events
== 0) {
1033 memmove(master
->handler
.pfds
+ i
, master
->handler
.pfds
+ i
+ 1,
1034 (master
->handler
.pfdcount
- i
- 1)
1035 * sizeof(struct pollfd
));
1036 master
->handler
.pfdcount
--;
1039 /* If we have the same pollfd in the copy, perform the same operations,
1040 * otherwise return. */
1041 if (i
>= master
->handler
.copycount
)
1044 master
->handler
.copy
[i
].events
&= ~(state
);
1046 if (master
->handler
.copy
[i
].events
== 0) {
1047 memmove(master
->handler
.copy
+ i
, master
->handler
.copy
+ i
+ 1,
1048 (master
->handler
.copycount
- i
- 1)
1049 * sizeof(struct pollfd
));
1050 master
->handler
.copycount
--;
1055 * Process cancellation requests.
1057 * This may only be run from the pthread which owns the thread_master.
1059 * @param master the thread master to process
1060 * @REQUIRE master->mtx
1062 static void do_thread_cancel(struct thread_master
*master
)
1064 struct thread_list
*list
= NULL
;
1065 struct pqueue
*queue
= NULL
;
1066 struct thread
**thread_array
= NULL
;
1067 struct thread
*thread
;
1069 struct cancel_req
*cr
;
1070 struct listnode
*ln
;
1071 for (ALL_LIST_ELEMENTS_RO(master
->cancel_req
, ln
, cr
)) {
1072 /* If this is an event object cancellation, linear search
1074 * list deleting any events which have the specified argument.
1076 * need to check every thread in the ready queue. */
1079 thread
= master
->event
.head
;
1085 if (t
->arg
== cr
->eventobj
) {
1086 thread_list_delete(&master
->event
, t
);
1089 thread_add_unuse(master
, t
);
1093 thread
= master
->ready
.head
;
1098 if (t
->arg
== cr
->eventobj
) {
1099 thread_list_delete(&master
->ready
, t
);
1102 thread_add_unuse(master
, t
);
1108 /* The pointer varies depending on whether the cancellation
1110 * made asynchronously or not. If it was, we need to check
1112 * thread even exists anymore before cancelling it. */
1113 thread
= (cr
->thread
) ? cr
->thread
: *cr
->threadref
;
1118 /* Determine the appropriate queue to cancel the thread from */
1119 switch (thread
->type
) {
1121 thread_cancel_rw(master
, thread
->u
.fd
, POLLIN
);
1122 thread_array
= master
->read
;
1125 thread_cancel_rw(master
, thread
->u
.fd
, POLLOUT
);
1126 thread_array
= master
->write
;
1129 queue
= master
->timer
;
1132 list
= &master
->event
;
1135 list
= &master
->ready
;
1143 assert(thread
->index
>= 0);
1144 assert(thread
== queue
->array
[thread
->index
]);
1145 pqueue_remove_at(thread
->index
, queue
);
1147 thread_list_delete(list
, thread
);
1148 } else if (thread_array
) {
1149 thread_array
[thread
->u
.fd
] = NULL
;
1151 assert(!"Thread should be either in queue or list or array!");
1155 *thread
->ref
= NULL
;
1157 thread_add_unuse(thread
->master
, thread
);
1160 /* Delete and free all cancellation requests */
1161 list_delete_all_node(master
->cancel_req
);
1163 /* Wake up any threads which may be blocked in thread_cancel_async() */
1164 master
->canceled
= true;
1165 pthread_cond_broadcast(&master
->cancel_cond
);
1169 * Cancel any events which have the specified argument.
1173 * @param m the thread_master to cancel from
1174 * @param arg the argument passed when creating the event
1176 void thread_cancel_event(struct thread_master
*master
, void *arg
)
1178 assert(master
->owner
== pthread_self());
1180 pthread_mutex_lock(&master
->mtx
);
1182 struct cancel_req
*cr
=
1183 XCALLOC(MTYPE_TMP
, sizeof(struct cancel_req
));
1185 listnode_add(master
->cancel_req
, cr
);
1186 do_thread_cancel(master
);
1188 pthread_mutex_unlock(&master
->mtx
);
1192 * Cancel a specific task.
1196 * @param thread task to cancel
1198 void thread_cancel(struct thread
*thread
)
1200 struct thread_master
*master
= thread
->master
;
1202 assert(master
->owner
== pthread_self());
1204 pthread_mutex_lock(&master
->mtx
);
1206 struct cancel_req
*cr
=
1207 XCALLOC(MTYPE_TMP
, sizeof(struct cancel_req
));
1208 cr
->thread
= thread
;
1209 listnode_add(master
->cancel_req
, cr
);
1210 do_thread_cancel(master
);
1212 pthread_mutex_unlock(&master
->mtx
);
1216 * Asynchronous cancellation.
1218 * Called with either a struct thread ** or void * to an event argument,
1219 * this function posts the correct cancellation request and blocks until it is
1222 * If the thread is currently running, execution blocks until it completes.
1224 * The last two parameters are mutually exclusive, i.e. if you pass one the
1225 * other must be NULL.
1227 * When the cancellation procedure executes on the target thread_master, the
1228 * thread * provided is checked for nullity. If it is null, the thread is
1229 * assumed to no longer exist and the cancellation request is a no-op. Thus
1230 * users of this API must pass a back-reference when scheduling the original
1235 * @param master the thread master with the relevant event / task
1236 * @param thread pointer to thread to cancel
1237 * @param eventobj the event
1239 void thread_cancel_async(struct thread_master
*master
, struct thread
**thread
,
1242 assert(!(thread
&& eventobj
) && (thread
|| eventobj
));
1243 assert(master
->owner
!= pthread_self());
1245 pthread_mutex_lock(&master
->mtx
);
1247 master
->canceled
= false;
1250 struct cancel_req
*cr
=
1251 XCALLOC(MTYPE_TMP
, sizeof(struct cancel_req
));
1252 cr
->threadref
= thread
;
1253 listnode_add(master
->cancel_req
, cr
);
1254 } else if (eventobj
) {
1255 struct cancel_req
*cr
=
1256 XCALLOC(MTYPE_TMP
, sizeof(struct cancel_req
));
1257 cr
->eventobj
= eventobj
;
1258 listnode_add(master
->cancel_req
, cr
);
1262 while (!master
->canceled
)
1263 pthread_cond_wait(&master
->cancel_cond
, &master
->mtx
);
1265 pthread_mutex_unlock(&master
->mtx
);
1267 /* ------------------------------------------------------------------------- */
1269 static struct timeval
*thread_timer_wait(struct pqueue
*queue
,
1270 struct timeval
*timer_val
)
1273 struct thread
*next_timer
= queue
->array
[0];
1274 monotime_until(&next_timer
->u
.sands
, timer_val
);
1280 static struct thread
*thread_run(struct thread_master
*m
, struct thread
*thread
,
1281 struct thread
*fetch
)
1284 thread_add_unuse(m
, thread
);
1288 static int thread_process_io_helper(struct thread_master
*m
,
1289 struct thread
*thread
, short state
, int pos
)
1291 struct thread
**thread_array
;
1296 if (thread
->type
== THREAD_READ
)
1297 thread_array
= m
->read
;
1299 thread_array
= m
->write
;
1301 thread_array
[thread
->u
.fd
] = NULL
;
1302 thread_list_add(&m
->ready
, thread
);
1303 thread
->type
= THREAD_READY
;
1304 /* if another pthread scheduled this file descriptor for the event we're
1305 * responding to, no problem; we're getting to it now */
1306 thread
->master
->handler
.pfds
[pos
].events
&= ~(state
);
1311 * Process I/O events.
1313 * Walks through file descriptor array looking for those pollfds whose .revents
1314 * field has something interesting. Deletes any invalid file descriptors.
1316 * @param m the thread master
1317 * @param num the number of active file descriptors (return value of poll())
1319 static void thread_process_io(struct thread_master
*m
, unsigned int num
)
1321 unsigned int ready
= 0;
1322 struct pollfd
*pfds
= m
->handler
.copy
;
1324 for (nfds_t i
= 0; i
< m
->handler
.copycount
&& ready
< num
; ++i
) {
1325 /* no event for current fd? immediately continue */
1326 if (pfds
[i
].revents
== 0)
1331 /* Unless someone has called thread_cancel from another pthread,
1333 * thing that could have changed in m->handler.pfds while we
1335 * asleep is the .events field in a given pollfd. Barring
1337 * that value should be a superset of the values we have in our
1339 * there's no need to update it. Similarily, barring deletion,
1341 * should still be a valid index into the master's pfds. */
1342 if (pfds
[i
].revents
& (POLLIN
| POLLHUP
))
1343 thread_process_io_helper(m
, m
->read
[pfds
[i
].fd
], POLLIN
,
1345 if (pfds
[i
].revents
& POLLOUT
)
1346 thread_process_io_helper(m
, m
->write
[pfds
[i
].fd
],
1349 /* if one of our file descriptors is garbage, remove the same
1351 * both pfds + update sizes and index */
1352 if (pfds
[i
].revents
& POLLNVAL
) {
1353 memmove(m
->handler
.pfds
+ i
, m
->handler
.pfds
+ i
+ 1,
1354 (m
->handler
.pfdcount
- i
- 1)
1355 * sizeof(struct pollfd
));
1356 m
->handler
.pfdcount
--;
1358 memmove(pfds
+ i
, pfds
+ i
+ 1,
1359 (m
->handler
.copycount
- i
- 1)
1360 * sizeof(struct pollfd
));
1361 m
->handler
.copycount
--;
1368 /* Add all timers that have popped to the ready list. */
1369 static unsigned int thread_process_timers(struct pqueue
*queue
,
1370 struct timeval
*timenow
)
1372 struct thread
*thread
;
1373 unsigned int ready
= 0;
1375 while (queue
->size
) {
1376 thread
= queue
->array
[0];
1377 if (timercmp(timenow
, &thread
->u
.sands
, <))
1379 pqueue_dequeue(queue
);
1380 thread
->type
= THREAD_READY
;
1381 thread_list_add(&thread
->master
->ready
, thread
);
1387 /* process a list en masse, e.g. for event thread lists */
1388 static unsigned int thread_process(struct thread_list
*list
)
1390 struct thread
*thread
;
1391 struct thread
*next
;
1392 unsigned int ready
= 0;
1394 for (thread
= list
->head
; thread
; thread
= next
) {
1395 next
= thread
->next
;
1396 thread_list_delete(list
, thread
);
1397 thread
->type
= THREAD_READY
;
1398 thread_list_add(&thread
->master
->ready
, thread
);
1405 /* Fetch next ready thread. */
1406 struct thread
*thread_fetch(struct thread_master
*m
, struct thread
*fetch
)
1408 struct thread
*thread
= NULL
;
1410 struct timeval zerotime
= {0, 0};
1412 struct timeval
*tw
= NULL
;
1417 /* Handle signals if any */
1418 if (m
->handle_signals
)
1419 quagga_sigevent_process();
1421 pthread_mutex_lock(&m
->mtx
);
1423 /* Process any pending cancellation requests */
1424 do_thread_cancel(m
);
1427 * Attempt to flush ready queue before going into poll().
1428 * This is performance-critical. Think twice before modifying.
1430 if ((thread
= thread_trim_head(&m
->ready
))) {
1431 fetch
= thread_run(m
, thread
, fetch
);
1434 pthread_mutex_unlock(&m
->mtx
);
1438 /* otherwise, tick through scheduling sequence */
1441 * Post events to ready queue. This must come before the
1442 * following block since events should occur immediately
1444 thread_process(&m
->event
);
1447 * If there are no tasks on the ready queue, we will poll()
1448 * until a timer expires or we receive I/O, whichever comes
1449 * first. The strategy for doing this is:
1451 * - If there are events pending, set the poll() timeout to zero
1452 * - If there are no events pending, but there are timers
1454 * timeout to the smallest remaining time on any timer
1455 * - If there are neither timers nor events pending, but there
1457 * descriptors pending, block indefinitely in poll()
1458 * - If nothing is pending, it's time for the application to die
1460 * In every case except the last, we need to hit poll() at least
1461 * once per loop to avoid starvation by events
1463 if (m
->ready
.count
== 0)
1464 tw
= thread_timer_wait(m
->timer
, &tv
);
1466 if (m
->ready
.count
!= 0 || (tw
&& !timercmp(tw
, &zerotime
, >)))
1469 if (!tw
&& m
->handler
.pfdcount
== 0) { /* die */
1470 pthread_mutex_unlock(&m
->mtx
);
1476 * Copy pollfd array + # active pollfds in it. Not necessary to
1477 * copy the array size as this is fixed.
1479 m
->handler
.copycount
= m
->handler
.pfdcount
;
1480 memcpy(m
->handler
.copy
, m
->handler
.pfds
,
1481 m
->handler
.copycount
* sizeof(struct pollfd
));
1483 pthread_mutex_unlock(&m
->mtx
);
1485 num
= fd_poll(m
, m
->handler
.copy
, m
->handler
.pfdsize
,
1486 m
->handler
.copycount
, tw
);
1488 pthread_mutex_lock(&m
->mtx
);
1490 /* Handle any errors received in poll() */
1492 if (errno
== EINTR
) {
1493 pthread_mutex_unlock(&m
->mtx
);
1494 /* loop around to signal handler */
1499 flog_err(EC_LIB_SYSTEM_CALL
, "poll() error: %s",
1500 safe_strerror(errno
));
1501 pthread_mutex_unlock(&m
->mtx
);
1506 /* Post timers to ready queue. */
1508 thread_process_timers(m
->timer
, &now
);
1510 /* Post I/O to ready queue. */
1512 thread_process_io(m
, num
);
1514 pthread_mutex_unlock(&m
->mtx
);
1516 } while (!thread
&& m
->spin
);
1521 static unsigned long timeval_elapsed(struct timeval a
, struct timeval b
)
1523 return (((a
.tv_sec
- b
.tv_sec
) * TIMER_SECOND_MICRO
)
1524 + (a
.tv_usec
- b
.tv_usec
));
1527 unsigned long thread_consumed_time(RUSAGE_T
*now
, RUSAGE_T
*start
,
1528 unsigned long *cputime
)
1530 /* This is 'user + sys' time. */
1531 *cputime
= timeval_elapsed(now
->cpu
.ru_utime
, start
->cpu
.ru_utime
)
1532 + timeval_elapsed(now
->cpu
.ru_stime
, start
->cpu
.ru_stime
);
1533 return timeval_elapsed(now
->real
, start
->real
);
1536 /* We should aim to yield after yield milliseconds, which defaults
1537 to THREAD_YIELD_TIME_SLOT .
1538 Note: we are using real (wall clock) time for this calculation.
1539 It could be argued that CPU time may make more sense in certain
1540 contexts. The things to consider are whether the thread may have
1541 blocked (in which case wall time increases, but CPU time does not),
1542 or whether the system is heavily loaded with other processes competing
1543 for CPU time. On balance, wall clock time seems to make sense.
1544 Plus it has the added benefit that gettimeofday should be faster
1545 than calling getrusage. */
1546 int thread_should_yield(struct thread
*thread
)
1549 pthread_mutex_lock(&thread
->mtx
);
1551 result
= monotime_since(&thread
->real
, NULL
)
1552 > (int64_t)thread
->yield
;
1554 pthread_mutex_unlock(&thread
->mtx
);
1558 void thread_set_yield_time(struct thread
*thread
, unsigned long yield_time
)
1560 pthread_mutex_lock(&thread
->mtx
);
1562 thread
->yield
= yield_time
;
1564 pthread_mutex_unlock(&thread
->mtx
);
1567 void thread_getrusage(RUSAGE_T
*r
)
1570 getrusage(RUSAGE_SELF
, &(r
->cpu
));
1576 * This function will atomically update the thread's usage history. At present
1577 * this is the only spot where usage history is written. Nevertheless the code
1578 * has been written such that the introduction of writers in the future should
1579 * not need to update it provided the writers atomically perform only the
1580 * operations done here, i.e. updating the total and maximum times. In
1581 * particular, the maximum real and cpu times must be monotonically increasing
1582 * or this code is not correct.
1584 void thread_call(struct thread
*thread
)
1586 _Atomic
unsigned long realtime
, cputime
;
1588 unsigned long helper
;
1589 RUSAGE_T before
, after
;
1592 thread
->real
= before
.real
;
1594 pthread_setspecific(thread_current
, thread
);
1595 (*thread
->func
)(thread
);
1596 pthread_setspecific(thread_current
, NULL
);
1600 realtime
= thread_consumed_time(&after
, &before
, &helper
);
1603 /* update realtime */
1604 atomic_fetch_add_explicit(&thread
->hist
->real
.total
, realtime
,
1605 memory_order_seq_cst
);
1606 exp
= atomic_load_explicit(&thread
->hist
->real
.max
,
1607 memory_order_seq_cst
);
1608 while (exp
< realtime
1609 && !atomic_compare_exchange_weak_explicit(
1610 &thread
->hist
->real
.max
, &exp
, realtime
,
1611 memory_order_seq_cst
, memory_order_seq_cst
))
1614 /* update cputime */
1615 atomic_fetch_add_explicit(&thread
->hist
->cpu
.total
, cputime
,
1616 memory_order_seq_cst
);
1617 exp
= atomic_load_explicit(&thread
->hist
->cpu
.max
,
1618 memory_order_seq_cst
);
1619 while (exp
< cputime
1620 && !atomic_compare_exchange_weak_explicit(
1621 &thread
->hist
->cpu
.max
, &exp
, cputime
,
1622 memory_order_seq_cst
, memory_order_seq_cst
))
1625 atomic_fetch_add_explicit(&thread
->hist
->total_calls
, 1,
1626 memory_order_seq_cst
);
1627 atomic_fetch_or_explicit(&thread
->hist
->types
, 1 << thread
->add_type
,
1628 memory_order_seq_cst
);
1630 #ifdef CONSUMED_TIME_CHECK
1631 if (realtime
> CONSUMED_TIME_CHECK
) {
1633 * We have a CPU Hog on our hands.
1634 * Whinge about it now, so we're aware this is yet another task
1639 "SLOW THREAD: task %s (%lx) ran for %lums (cpu time %lums)",
1640 thread
->funcname
, (unsigned long)thread
->func
,
1641 realtime
/ 1000, cputime
/ 1000);
1643 #endif /* CONSUMED_TIME_CHECK */
1646 /* Execute thread */
1647 void funcname_thread_execute(struct thread_master
*m
,
1648 int (*func
)(struct thread
*), void *arg
, int val
,
1651 struct thread
*thread
;
1653 /* Get or allocate new thread to execute. */
1654 pthread_mutex_lock(&m
->mtx
);
1656 thread
= thread_get(m
, THREAD_EVENT
, func
, arg
, debugargpass
);
1658 /* Set its event value. */
1659 pthread_mutex_lock(&thread
->mtx
);
1661 thread
->add_type
= THREAD_EXECUTE
;
1662 thread
->u
.val
= val
;
1663 thread
->ref
= &thread
;
1665 pthread_mutex_unlock(&thread
->mtx
);
1667 pthread_mutex_unlock(&m
->mtx
);
1669 /* Execute thread doing all accounting. */
1670 thread_call(thread
);
1672 /* Give back or free thread. */
1673 thread_add_unuse(m
, thread
);