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 (!cyclic->already_warned)) {
90 pr_err("cyclic function %s took too long: %lldus vs %dus max\n",
91 cyclic->name, cpu_time,
92 CONFIG_CYCLIC_MAX_CPU_TIME_US);
95 * Don't disable this function, just warn once
96 * about this exceeding CPU time usage
98 cyclic->already_warned = true;
102 gd->cyclic->cyclic_running = false;
107 /* The HW watchdog is not integrated into the cyclic IF (yet) */
108 if (IS_ENABLED(CONFIG_HW_WATCHDOG))
112 * schedule() might get called very early before the cyclic IF is
113 * ready. Make sure to only call cyclic_run() when it's initalized.
115 if (gd && gd->cyclic && gd->cyclic->cyclic_ready)
119 int cyclic_uninit(void)
121 struct cyclic_info *cyclic, *tmp;
123 list_for_each_entry_safe(cyclic, tmp, &gd->cyclic->cyclic_list, list)
124 cyclic_unregister(cyclic);
125 gd->cyclic->cyclic_ready = false;
130 int cyclic_init(void)
132 int size = sizeof(struct cyclic_drv);
134 gd->cyclic = (struct cyclic_drv *)malloc(size);
138 memset(gd->cyclic, '\0', size);
139 INIT_LIST_HEAD(&gd->cyclic->cyclic_list);
140 gd->cyclic->cyclic_ready = true;