kobject_init_and_add is easy to misuse

From: Matthew Wilcox
Date: Tue Jun 02 2020 - 08:10:53 EST

On Tue, Jun 02, 2020 at 07:50:33PM +0800, Wang Hai wrote:
> syzkaller reports for memory leak when kobject_init_and_add()
> returns an error in the function sysfs_slab_add() [1]
> When this happened, the function kobject_put() is not called for the
> corresponding kobject, which potentially leads to memory leak.
> This patch fixes the issue by calling kobject_put() even if
> kobject_init_and_add() fails.

I think this speaks to a deeper problem with kobject_init_and_add()
-- the need to call kobject_put() if it fails is not readily apparent
to most users. This same bug appears in the first three users of
kobject_init_and_add() that I checked --

Some do get it right --

I'd argue that the current behaviour is wrong, that kobject_init_and_add()
should call kobject_put() if the add fails. This would need a tree-wide
audit. But somebody needs to do that anyway because based on my random
sampling, half of the users currently get it wrong.