From 1950e7a06b1dc4c1b8918375748420b65f18c266 Mon Sep 17 00:00:00 2001 From: laokaiyao Date: Fri, 12 Jan 2024 15:09:51 +0800 Subject: [PATCH] fix(hal_utils): add division range check in integral algorithm --- components/hal/hal_utils.c | 13 ++++++++++++- components/hal/include/hal/hal_utils.h | 6 ++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/components/hal/hal_utils.c b/components/hal/hal_utils.c index 1213aa49cf..1ef92ffe11 100644 --- a/components/hal/hal_utils.c +++ b/components/hal/hal_utils.c @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD + * SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ @@ -133,6 +133,17 @@ uint32_t hal_utils_calc_clk_div_integer(const hal_utils_clk_info_t *clk_info, ui (freq_error >= clk_info->src_freq_hz / (2 * div_integ * (div_integ + 1))))) { div_integ++; } + /* Check the integral division whether in range [min_integ, max_integ) */ + /* If the result is less than the minimum, set the division to the minimum but return 0 */ + if (div_integ < clk_info->min_integ) { + *int_div = clk_info->min_integ; + return 0; + } + /* if the result is greater or equal to the maximum , set the division to the maximum but return 0 */ + if (div_integ >= clk_info->max_integ) { + *int_div = clk_info->max_integ - 1; + return 0; + } // Assign result *int_div = div_integ; diff --git a/components/hal/include/hal/hal_utils.h b/components/hal/include/hal/hal_utils.h index f05312963b..da8023c7a8 100644 --- a/components/hal/include/hal/hal_utils.h +++ b/components/hal/include/hal/hal_utils.h @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD + * SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ @@ -80,7 +80,9 @@ uint32_t hal_utils_calc_clk_div_frac_accurate(const hal_utils_clk_info_t *clk_in * @param[in] clk_info The clock infomation * @param[out] int_div The clock integral division * @return - * - 0: Failed to get the result because the division is out of range + * - 0: Failed to get the result because the division is out of range, + * but parameter `int_div` will still be assigned to min/max division that given in `clk_info`, + * incase the caller still want to use the min/max division in this case. * - others: The real output clock frequency */ uint32_t hal_utils_calc_clk_div_integer(const hal_utils_clk_info_t *clk_info, uint32_t *int_div);