On 23/02/2022 20.31, Linus Torvalds 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 > > 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. I have often wished that the iterator macros would consistently set the loop variable to NULL upon reaching the end. It could be done by changing the stop condition from i != HEAD to i != HEAD || (i = NULL, 0) [the comma operator mostly for clarity, we want the side effect of the assignment but the whole RHS to still evaluate to false, which "i=NULL" by itself of course would]. In the vast majority of cases where the iterator variable is not used after the loop, the compiler should see through it and just drop the dead assignment. And it would make the test for "did we break out early finding what we looked for, or did we iterate till the end" quite natural, without any auxiliary bool or extra 'struct foo*' variable. But it will probably break too much existing code. Rasmus