1 // SPDX-License-Identifier: GPL-2.0+
3 * A general-purpose cyclic execution infrastructure, to allow "small"
4 * (run-time wise) functions to be executed at a specified frequency.
5 * Things like LED blinking or watchdog triggering are examples for such
8 * Copyright (C) 2022 Stefan Roese <sr@denx.de>
15 #include <linux/errno.h>
16 #include <linux/list.h>
17 #include <asm/global_data.h>
19 DECLARE_GLOBAL_DATA_PTR;
21 struct list_head *cyclic_get_list(void)
23 return &gd->cyclic->cyclic_list;
26 struct cyclic_info *cyclic_register(cyclic_func_t func, uint64_t delay_us,
27 const char *name, void *ctx)
29 struct cyclic_info *cyclic;
31 if (!gd->cyclic->cyclic_ready) {
32 pr_debug("Cyclic IF not ready yet\n");
36 cyclic = calloc(1, sizeof(struct cyclic_info));
38 pr_debug("Memory allocation error\n");
42 /* Store values in struct */
45 cyclic->name = strdup(name);
46 cyclic->delay_us = delay_us;
47 cyclic->start_time_us = timer_get_us();
48 list_add_tail(&cyclic->list, &gd->cyclic->cyclic_list);
53 int cyclic_unregister(struct cyclic_info *cyclic)
55 list_del(&cyclic->list);
63 struct cyclic_info *cyclic, *tmp;
64 uint64_t now, cpu_time;
66 /* Prevent recursion */
67 if (gd->cyclic->cyclic_running)
70 gd->cyclic->cyclic_running = true;
71 list_for_each_entry_safe(cyclic, tmp, &gd->cyclic->cyclic_list, list) {
73 * Check if this cyclic function needs to get called, e.g.
74 * do not call the cyclic func too often
77 if (time_after_eq64(now, cyclic->next_call)) {
78 /* Call cyclic function and account it's cpu-time */
79 cyclic->next_call = now + cyclic->delay_us;
80 cyclic->func(cyclic->ctx);
82 cpu_time = timer_get_us() - now;
83 cyclic->cpu_time_us += cpu_time;
85 /* Check if cpu-time exceeds max allowed time */
86 if (cpu_time > CONFIG_CYCLIC_MAX_CPU_TIME_US) {
87 pr_err("cyclic function %s took too long: %lldus vs %dus max, disabling\n",
88 cyclic->name, cpu_time,
89 CONFIG_CYCLIC_MAX_CPU_TIME_US);
91 /* Unregister this cyclic function */
92 cyclic_unregister(cyclic);
96 gd->cyclic->cyclic_running = false;
99 int cyclic_uninit(void)
101 struct cyclic_info *cyclic, *tmp;
103 list_for_each_entry_safe(cyclic, tmp, &gd->cyclic->cyclic_list, list)
104 cyclic_unregister(cyclic);
105 gd->cyclic->cyclic_ready = false;
110 int cyclic_init(void)
112 int size = sizeof(struct cyclic_drv);
114 gd->cyclic = (struct cyclic_drv *)malloc(size);
118 memset(gd->cyclic, '\0', size);
119 INIT_LIST_HEAD(&gd->cyclic->cyclic_list);
120 gd->cyclic->cyclic_ready = true;