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

From: Jakob
Date: Wed Feb 23 2022 - 15:15:26 EST




> On 23. Feb 2022, at 20:31, Linus Torvalds <torvalds@xxxxxxxxxxxxxxxxxxxx> wrote:
>
> 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

in such a case you would still have to set the iterator value to
NULL when reaching the terminating condition or am I missing something?

Since the iterator value will always be set to *something* when
calling list_for_each_entry().

>
> 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.

I completely agree and was intending to do it in such a way.
However I couldn't find a way to do that without breaking the kernel
between commits.

Either you need to first set the iterator to NULL when terminating
which breaks the current code here

or

patch the code location first to do if(iterator), which does not
work with the current list_for_each_entry().


>
> 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