在 2023/5/10 下午3:03, Andy Shevchenko 写道:
_original_
const char rdiv[12] = {0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10, 11};
div = DIV_ROUND_UP_ULL(loongson_spi->clk_rate, hz);
if (div < 2)
div = 2;
if (div > 4096)
div = 4096;
bit = fls(div) - 1;
if ((1<<bit) == div)
bit--;
div_tmp = rdiv[bit];
loongson_spi->spcr = div_tmp & 3;
loongson_spi->sper = (div_tmp >> 2) & 3;
_proposed_
const char rdiv[12] = {0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10, 11};
// as far as I understood the above table
00 00 [0] <= 2
00 01 [1] <= 4
01 00 [2] <= 8
00 10 [3] <= 16
00 11 [4] <= 32
01 01 [5] <= 64
01 10 [6] <= 128
01 11 [7] <= 256
10 00 [8] <= 512
10 01 [9] <= 1024
10 10 [10] <= 2048
10 11 [11] <= 4096
div =
clamp_val(DIV_ROUND_UP_ULL(loongson_spi->clk_rate, hz), 2, 4096);
div_tmp = rdiv[fls(div - 1)];
loongson_spi->spcr = (div_tmp & GENMASK(1, 0)) >> 0;
loongson_spi->sper = (div_tmp & GENMASK(3, 2)) >> 2;
But TBH I would expect the author to think about it more.
In previous code, if mode need to be updated but clk not to be updated
then the clk settting code will be also run. so, I think it is better
to confiure clk and mode separately.
if (hz && loongson_spi->hz != hz) {
div = clamp_val(DIV_ROUND_UP_ULL(loongson_spi->clk_rate, hz), 2,
4096);
div_tmp = rdiv[fls(div - 1)];
loongson_spi->spcr = (div_tmp & GENMASK(1, 0)) >> 0;
loongson_spi->sper = (div_tmp & GENMASK(3, 2)) >> 2;
val = loongson_spi_read_reg(loongson_spi, LOONGSON_SPI_SPCR_REG);
loongson_spi_write_reg(loongson_spi, LOONGSON_SPI_SPCR_REG,
(val & ~3) | loongson_spi->spcr);
val = loongson_spi_read_reg(loongson_spi, LOONGSON_SPI_SPER_REG);
loongson_spi_write_reg(loongson_spi, LOONGSON_SPI_SPER_REG,
(val & ~3) |loongson_spi->sper);
loongson_spi->hz = hz;
}
if ((spi->mode ^ loongson_spi->mode) & SPI_MODE_X_MASK) {
val = loongson_spi_read_reg(loongson_spi, LOONGSON_SPI_SPCR_REG);
val &= ~(LOONGSON_SPI_SPCR_CPOL | LOONGSON_SPI_SPCR_CPHA);
if (spi->mode & SPI_CPOL)
val |= LOONGSON_SPI_SPCR_CPOL;
if (spi->mode & SPI_CPHA)
val |= LOONGSON_SPI_SPCR_CPHA;
loongson_spi_write_reg(loongson_spi, LOONGSON_SPI_SPCR_REG, val);
loongson_spi->mode |= spi->mode;
}
Also the check can be modified to have less indented code:
if (hz && loongson_spi->hz == hz)
return 0;
if (!((spi->mode ^ loongson_spi->mode) & SPI_MODE_X_MASK))
return 0;
The setting register about clk and mode was the same SPCR register, so
only the clk and mode don't need to be updated in the same, then return
0, so the code seems to be as follows. But setting clk and mode
separately doesn't require follows judgement.
if ((hz && loongson_spi->hz == hz) &&
!((spi->mode ^ loongson_spi->mode) & SPI_MODE_X_MASK))
return 0;
Thanks.