Re: [RFC PATCH v3 4/6] media: tegra: Add Tegra210 Video input driver

From: Hans Verkuil
Date: Thu Feb 20 2020 - 08:33:55 EST


(Replying to myself so I can explain this a bit more)

On 2/20/20 1:44 PM, Hans Verkuil wrote:
>> +
>> +static int tegra_csi_tpg_channels_alloc(struct tegra_csi *csi)
>> +{
>> + struct device_node *node = csi->dev->of_node;
>> + unsigned int port_num;
>> + int ret;
>> + struct tegra_csi_channel *item;
>> + unsigned int tpg_channels = csi->soc->csi_max_channels;
>> +
>> + /* allocate CSI channel for each CSI x2 ports */
>> + for (port_num = 0; port_num < tpg_channels; port_num++) {
>> + item = devm_kzalloc(csi->dev, sizeof(*item), GFP_KERNEL);
>
> Using devm_*alloc can be dangerous. If someone unbinds the driver, then
> all memory allocated with devm_ is immediately freed. But if an application
> still has a filehandle open, then when it closes it it might still reference
> this already-freed memory.
>
> I recommend that you avoid using devm_*alloc for media drivers.

A good test is to unbind & bind the driver:

cd /sys/devices/platform/50000000.host1x/54080000.vi/driver
echo -n 54080000.vi >unbind
echo -n 54080000.vi >bind

First just do this without the driver being used. That already
gives me 'list_del corruption' kernel messages (list debugging
is turned on in my kernel).

Note that this first test is basically identical to a rmmod/modprobe
of the driver. But when I compiled the driver as a module it didn't
create any video device nodes! Nor did I see any errors in the kernel
log. I didn't pursue this, and perhaps I did something wrong, but it's
worth taking a look at.

The next step would be to have a video node open with:

v4l2-ctl --sleep 10

then while it is sleeping unbind the driver and see what happens
when v4l2-ctl exits.

Worst case is when you are streaming:

v4l2-ctl --stream-mmap

and then unbind.

In general, the best way to get this to work correctly is:

1) don't use devm_*alloc
2) set the release callback of struct v4l2_device and do all freeing there.
3) in the platform remove() callback you call media_device_unregister()
and video_unregister_device().

It's worth getting this right in this early stage, rather than fixing it
in the future.

Regards,

Hans