Re: staging: media: tegra-video: Use common error handling code in tegra_vi_graph_parse_one()

From: Dan Carpenter
Date: Tue Mar 05 2024 - 11:21:59 EST


On Tue, Mar 05, 2024 at 04:24:27PM +0100, Luca Ceresoli wrote:
> Hello Dan, Markus,
>
> On Sat, 2 Mar 2024 11:40:26 +0100
> Markus Elfring <Markus.Elfring@xxxxxx> wrote:
>
> > >>> Add a jump target so that a bit of exception handling can be better reused
> > >>> at the end of this function implementation.
> > …
> > >> Reviewed-by: Luca Ceresoli <luca.ceresoli@xxxxxxxxxxx>
> > >
> > > These patches make the code worse.
>
> This is of course a legitimate opinion. However Markus' patch
> implements what is recommended by the documentation and is in common
> use in the kernel code. A quick search found 73 occurrences in v6.8-rc7:
>
> $ expr $(pcregrep -r -M ':\n\tfwnode_handle_put' drivers | wc -l) / 2
> 73
> $
>
> 300+ are found for of_node_put().
>

Using an unwind ladder is the best way to write error handling, yes.
I've written a long blog about it.

https://staticthinking.wordpress.com/2022/04/28/free-the-last-thing-style/

In my blog, I talk about that "Unwinding from loops is slightly
complicated." Because what you want to do is clean up partial
iterations before the goto.

Now imagine we apply Markus's patch and someone comes along an adds a
new allocation after the loop is over. Then we have to do some kind of
bunny hop:

free_new_thing:
free(thing);
goto cleanup; <-- ugly little goto
put_fwnode:
fwnode_handle_put(remote);
cleanup:
dev_err(vi->dev, "failed parsing the graph: %d\n", ret);
v4l2_async_nf_cleanup(&chan->notifier);
return ret;

Adding the little goto seems like a small thing when you're seeing it
in an email like this. But when you add the new goto years later,
people are used to unwind ladders working in a specific way and they
forget that, "Oh this ladder has a weird rung that we have to skip over."
We see these bugs more with locking.

one = alloc();
if (!one)
return;

lock();
two = alloc();
if (!two)
goto free_one; <-- should have unlocked before the goto
unlock;

three = alloc();
if (!three)
goto free_two;

return 0;

free_two:
free(two);
free_one:
unlock();
free(one);

return -ENOMEM;

regards,
dan carpenter