Re: [RFC PATCH 04/13] vfio/mdev: remove the usage of the list iterator after the loop

From: Linus Torvalds
Date: Wed Feb 23 2022 - 14:31:37 EST


On Wed, Feb 23, 2022 at 11:12 AM Jason Gunthorpe <jgg@xxxxxxxx> wrote:
>
> Yes, this is what I had put together as well about this patch, and I
> think it is OK as-is. In this case the list head is in the .bss of a
> module so I don't think it is very likely that the type confused
> container_of() will alias a kalloc result, but it is certainly
> technically wrong as-is.

I think that the pattern we should strive to use is not top use a
'bool' with the

- initialize to false, and then in loop: do 'found = true;' if found

- use the iterator variable if 'found'.

but instead strive to

- either only use the iterator variable inside the loop

- if you want to use it after the loop, have a externally visible
separate pointer initialized to NULL, and set it to the iterator
variable inside the loop

IOW, instead of having a variable that is a 'bool', just make that
variable _be_ the pointer you want. It's clearer, and it avoids using
the iterator variable outside the loop.

It also is likely to generate better code, because there are fewer
live variables - outside the loop now only uses that one variable,
rather than using the 'bool' variable _and_ the iterator variable.

Linus