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 void hw_watchdog_reset(void);
23 struct list_head *cyclic_get_list(void)
25 return &gd->cyclic->cyclic_list;
28 struct cyclic_info *cyclic_register(cyclic_func_t func, uint64_t delay_us,
29 const char *name, void *ctx)
31 struct cyclic_info *cyclic;
33 if (!gd->cyclic->cyclic_ready) {
34 pr_debug("Cyclic IF not ready yet\n");
38 cyclic = calloc(1, sizeof(struct cyclic_info));
40 pr_debug("Memory allocation error\n");
44 /* Store values in struct */
47 cyclic->name = strdup(name);
48 cyclic->delay_us = delay_us;
49 cyclic->start_time_us = timer_get_us();
50 list_add_tail(&cyclic->list, &gd->cyclic->cyclic_list);
55 int cyclic_unregister(struct cyclic_info *cyclic)
57 list_del(&cyclic->list);
65 struct cyclic_info *cyclic, *tmp;
66 uint64_t now, cpu_time;
68 /* Prevent recursion */
69 if (gd->cyclic->cyclic_running)
72 gd->cyclic->cyclic_running = true;
73 list_for_each_entry_safe(cyclic, tmp, &gd->cyclic->cyclic_list, list) {
75 * Check if this cyclic function needs to get called, e.g.
76 * do not call the cyclic func too often
79 if (time_after_eq64(now, cyclic->next_call)) {
80 /* Call cyclic function and account it's cpu-time */
81 cyclic->next_call = now + cyclic->delay_us;
82 cyclic->func(cyclic->ctx);
84 cpu_time = timer_get_us() - now;
85 cyclic->cpu_time_us += cpu_time;
87 /* Check if cpu-time exceeds max allowed time */
88 if (cpu_time > CONFIG_CYCLIC_MAX_CPU_TIME_US) {
89 pr_err("cyclic function %s took too long: %lldus vs %dus max, disabling\n",
90 cyclic->name, cpu_time,
91 CONFIG_CYCLIC_MAX_CPU_TIME_US);
93 /* Unregister this cyclic function */
94 cyclic_unregister(cyclic);
98 gd->cyclic->cyclic_running = false;
103 /* The HW watchdog is not integrated into the cyclic IF (yet) */
104 if (IS_ENABLED(CONFIG_HW_WATCHDOG))
108 * schedule() might get called very early before the cyclic IF is
109 * ready. Make sure to only call cyclic_run() when it's initalized.
111 if (gd && gd->cyclic && gd->cyclic->cyclic_ready)
115 int cyclic_uninit(void)
117 struct cyclic_info *cyclic, *tmp;
119 list_for_each_entry_safe(cyclic, tmp, &gd->cyclic->cyclic_list, list)
120 cyclic_unregister(cyclic);
121 gd->cyclic->cyclic_ready = false;
126 int cyclic_init(void)
128 int size = sizeof(struct cyclic_drv);
130 gd->cyclic = (struct cyclic_drv *)malloc(size);
134 memset(gd->cyclic, '\0', size);
135 INIT_LIST_HEAD(&gd->cyclic->cyclic_list);
136 gd->cyclic->cyclic_ready = true;