Re: [PATCH v2] platform/x86: intel_pmc_core: Prevent possibile overflow

From: Andy Shevchenko
Date: Thu Aug 05 2021 - 04:17:18 EST


On Thu, Aug 5, 2021 at 12:40 AM David E. Box
<david.e.box@xxxxxxxxxxxxxxx> wrote:
>
> Low Power Mode (LPM) priority is encoded in 4 bits. Yet, this value is used
> as an index to an array whose element size was less than 16, leading to the
> possibility of overflow should we read a larger than expected priority. In
> addition to the overflow, bad values can lead to incorrect state reporting.
> So rework the priority code to prevent the overflow and perform some
> validation of the register. Use the priority register values if they give
> an ordering of unique numbers between 0 and the maximum number of states.
> Otherwise, use a default ordering instead.

...


> + if (!bad_pri_reg) {

Not sure why you need three separate blocks each of them with the same
conditional?
Perhaps you need to refactor this code, because like this it doesn't look good.

Yes, after I read more I see it, but i think something like

bad_pri_reg = foo1(..., bad_pri_reg);
...foo2(...);
...foo3(...);

might be better (or variations of the above).

> + /*
> + * Each byte contains gives the priority level for 2 modes (7:4 and 3:0).
> + * In a 32 bit register this allows for describing 8 modes. Store the
> + * levels and look for values out of range.
> + */
> + for (mode = 0; mode < 8; mode++) {

> + int level = GENMASK(3, 0) & lpm_pri;

Yoda style?

> - lpm_priority[pri0] = mode;
> - lpm_priority[pri1] = mode + 1;
> + if (level >= LPM_MAX_NUM_MODES) {
> + bad_pri_reg = true;
> + break;
> + }
> +
> + mode_order[mode] = level;
> + lpm_pri >>= 4;
> + }
> }
>
> + if (!bad_pri_reg) {
> + /* Check that we have unique values */
> + for (i = 0; i < LPM_MAX_NUM_MODES - 1; i++)
> + for (j = i + 1; j < LPM_MAX_NUM_MODES; j++)
> + if (mode_order[i] == mode_order[j]) {
> + bad_pri_reg = true;
> + break;
> + }
> + }
> +
> + /*
> + * If bad_pri_reg is false, then mode_order must contain unique values for
> + * all priority levels from 0 to LPM_MAX_NUM_MODES and this loop with properly

proper? property?

> + * overwrite our default ordering. Otherwise just use the default.
> + */
> + if (!bad_pri_reg)
> + /* Get list of modes in priority order */
> + for (mode = 0; mode < LPM_MAX_NUM_MODES; mode++)
> + pri_order[mode_order[mode]] = mode;
> + else
> + dev_warn(&pdev->dev, "Assuming a default substate order for this platform\n");
> +
> /*
> * Loop though all modes from lowest to highest priority,

throught

> * and capture all enabled modes in order
> */

...

> #define LPM_MAX_NUM_MODES 8

> +/* Must contain LPM_MAX_NUM_MODES elements */

Instead of the comment the static_assert() against ARRAY_SIZE may be better.

> +#define LPM_DEFAULT_PRI { 7, 5, 2, 6, 4, 3, 1, 0 }


--
With Best Regards,
Andy Shevchenko