Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suspicious code in MXC_SPI_RevA2_SetFrequency #1339

Open
perkinsmg opened this issue Feb 6, 2025 · 0 comments
Open

Suspicious code in MXC_SPI_RevA2_SetFrequency #1339

perkinsmg opened this issue Feb 6, 2025 · 0 comments

Comments

@perkinsmg
Copy link
Contributor

In the MXC_SPI_RevA2_SetFrequency function in spi_reva2.c, I see the code:

// Set the clock high and low
freq_div = MXC_SPI_GetPeripheralClock((mxc_spi_regs_t *)spi);
freq_div = (freq_div / freq);

hi_clk = freq_div / 2;
lo_clk = freq_div / 2;
scale = 0;

if (freq_div % 2) {
    hi_clk += 1;
}

while (hi_clk >= 16 && scale < 8) {
    hi_clk /= 2;
    lo_clk /= 2;
    scale++;
}

if (scale == 8) {
    lo_clk = 15;
    hi_clk = 15;
}

Let's imagine that the peripheral clock is 512MHz, and the desired frequency is 100kHz. So freq_div = 5120 at the start.

First we set hi_clk = lo_clk = 2560, and scale = 0. Then we iterate, increasing scale and dividing hi_clk and lo_clk.

hi_clk lo_clk scale
2560 2560 0
1280 1280 1
640 640 2
320 320 3
160 160 4
80 80 5
40 40 6
20 20 7
10 10 8

But the final test says "scale == 8" so we end up with

lo_clk = 15
hi_clk = 15
scale = 8

despite the fact that I think hi_clk = 10, lo_clk = 10, scale = 8 would have been fine and more accurate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant