|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Michael Hope <[email protected]> |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#define DT_DRV_COMPAT wch_iwdg |
| 8 | + |
| 9 | +#include <zephyr/drivers/watchdog.h> |
| 10 | +#include <zephyr/kernel.h> |
| 11 | +#include <zephyr/sys_clock.h> |
| 12 | +#include <errno.h> |
| 13 | + |
| 14 | +#include <ch32fun.h> |
| 15 | + |
| 16 | +static int iwdg_wch_setup(const struct device *dev, uint8_t options) |
| 17 | +{ |
| 18 | + if (options != 0) { |
| 19 | + return -ENOTSUP; |
| 20 | + } |
| 21 | + |
| 22 | + IWDG->CTLR = CTLR_KEY_Enable; |
| 23 | + |
| 24 | + return 0; |
| 25 | +} |
| 26 | + |
| 27 | +static int iwdg_wch_disable(const struct device *dev) |
| 28 | +{ |
| 29 | + return -EPERM; |
| 30 | +} |
| 31 | + |
| 32 | +static int iwdg_wch_install_timeout(const struct device *dev, |
| 33 | + const struct wdt_timeout_cfg *config) |
| 34 | +{ |
| 35 | + int prescaler = 0; |
| 36 | + /* The IWDT is driven by the 128 kHz LSI oscillator with at least a /4 prescaler. */ |
| 37 | + uint32_t lsi_frequency = DT_PROP(DT_NODELABEL(clk_lsi), clock_frequency); |
| 38 | + uint32_t reload = config->window.max * (lsi_frequency / 1000 / 4); |
| 39 | + |
| 40 | + if (config->callback != NULL) { |
| 41 | + return -ENOTSUP; |
| 42 | + } |
| 43 | + if (config->window.min != 0) { |
| 44 | + return -ENOTSUP; |
| 45 | + } |
| 46 | + if ((config->flags & WDT_FLAG_RESET_MASK) != WDT_FLAG_RESET_SOC) { |
| 47 | + return -ENOTSUP; |
| 48 | + } |
| 49 | + |
| 50 | + for (; reload > IWDG_RL && prescaler < IWDG_PR;) { |
| 51 | + prescaler++; |
| 52 | + reload /= 2; |
| 53 | + } |
| 54 | + if (reload > IWDG_RL) { |
| 55 | + /* The reload is too high even with the maximum prescaler */ |
| 56 | + return -EINVAL; |
| 57 | + } |
| 58 | + |
| 59 | + /* Wait for the watchdog to be idle, unlock it, update, and wait for idle. */ |
| 60 | + while ((IWDG->STATR & (IWDG_RVU | IWDG_PVU)) != 0) { |
| 61 | + } |
| 62 | + |
| 63 | + IWDG->CTLR = IWDG_WriteAccess_Enable; |
| 64 | + IWDG->PSCR = prescaler; |
| 65 | + IWDG->RLDR = reload; |
| 66 | + |
| 67 | + while ((IWDG->STATR & (IWDG_RVU | IWDG_PVU)) != 0) { |
| 68 | + } |
| 69 | + |
| 70 | + return 0; |
| 71 | +} |
| 72 | + |
| 73 | +static int iwdg_wch_feed(const struct device *dev, int channel_id) |
| 74 | +{ |
| 75 | + IWDG->CTLR = CTLR_KEY_Reload; |
| 76 | + |
| 77 | + return 0; |
| 78 | +} |
| 79 | + |
| 80 | +static const struct wdt_driver_api iwdg_wch_api = { |
| 81 | + .setup = iwdg_wch_setup, |
| 82 | + .disable = iwdg_wch_disable, |
| 83 | + .install_timeout = iwdg_wch_install_timeout, |
| 84 | + .feed = iwdg_wch_feed, |
| 85 | +}; |
| 86 | + |
| 87 | +static int iwdg_wch_init(const struct device *dev) |
| 88 | +{ |
| 89 | + return 0; |
| 90 | +} |
| 91 | + |
| 92 | +DEVICE_DT_INST_DEFINE(0, iwdg_wch_init, NULL, NULL, NULL, PRE_KERNEL_1, |
| 93 | + CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &iwdg_wch_api); |
0 commit comments