Re: [PATCH v7 8/8] iio: adc: ad4851: add ad485x driver

Uwe Kleine-König
2024-12-07T15:29:55Z

[-- Attachment #1: Type: text/plain, Size: 2338 bytes --]

Hello Antoniu,

On Fri, Nov 29, 2024 at 05:35:46PM +0200, Antoniu Miclaus wrote:
> +static int ad4851_set_sampling_freq(struct ad4851_state *st, unsigned int freq)
> +{
> + struct pwm_state cnv_state = {
> + .duty_cycle = AD4851_T_CNVH_NS,
> + .enabled = true,
> + };
> + int ret;
> +
> + freq = clamp(freq, 1, st->info->max_sample_rate_hz);
> +
> + cnv_state.period = DIV_ROUND_UP_ULL(NSEC_PER_SEC, freq);
> +
> + ret = pwm_apply_might_sleep(st->cnv, &cnv_state);
> + if (ret)
> + return ret;

If you want to be sure that pwm_apply_might_sleep() doesn't round down
.period (and .duty_cycle?) too much, you might consider using
pwm_round_waveform_might_sleep(). But note that this function only works
for two hwpwm drivers currently.

> +
> + st->sampling_freq = freq;
> +
> + return 0;
> +}
> +
> +static const int ad4851_oversampling_ratios[] = {
> + 1, 2, 4, 8, 16, 32, 64, 128,
> + 256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
> + 65536,
> +};
> +
> +static int ad4851_osr_to_regval(int ratio)

This function is called with an unsigned parameter only.

> +{
> + int i;
> +
> + for (i = 1; i < ARRAY_SIZE(ad4851_oversampling_ratios); i++)
> + if (ratio == ad4851_oversampling_ratios[i])
> + return i - 1;

Given that ad4851_oversampling_ratios[i] == 1 << i you could simplify
that. Something like:

if (is_power_of_2(ratio) && ratio <= 65536 && ratio > 0)
return ilog2(ratio);

> +
> + return -EINVAL;
> +}
> +
> +static int ad4851_set_oversampling_ratio(struct ad4851_state *st,
> + const struct iio_chan_spec *chan,
> + unsigned int osr)
> +{
> + unsigned int val;
> + int ret;
> +
> + guard(mutex)(&st->lock);
> +
> + if (osr == 1) {
> + ret = regmap_clear_bits(st->regmap, AD4851_REG_OVERSAMPLE,
> + AD4851_OS_EN_MSK);
> + if (ret)
> + return ret;
> +
> + ret = iio_backend_oversampling_disable(st->back);
> + if (ret)
> + return ret;
> + } else {
> + val = ad4851_osr_to_regval(osr);
> + if (val < 0)
> + return -EINVAL;
> +
> + ret = regmap_set_bits(st->regmap, AD4851_REG_OVERSAMPLE,
> + AD4851_OS_EN_MSK);
> + if (ret)
> + return ret;
> +
> + ret = regmap_update_bits(st->regmap, AD4851_REG_OVERSAMPLE,
> + AD4851_OS_RATIO_MSK, val);

You set this register twice in a row. Can this be done in a single
register access?

> + if (ret)
> + return ret;

Best regards
Uwe

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]