Re: [PATCH v6 2/3] zram: fix deadlock with sysfs attribute usage and module removal

From: Greg KH
Date: Wed Jul 21 2021 - 07:41:01 EST


On Fri, Jul 02, 2021 at 05:19:57PM -0700, Luis Chamberlain wrote:
> +#define MODULE_DEVICE_ATTR_FUNC_STORE(_name) \
> +static ssize_t module_ ## _name ## _store(struct device *dev, \
> + struct device_attribute *attr, \
> + const char *buf, size_t len) \
> +{ \
> + ssize_t __ret; \
> + if (!try_module_get(THIS_MODULE)) \
> + return -ENODEV; \

I feel like this needs to be written down somewhere as I see it come up
all the time.

Again, this is racy and broken code. You can NEVER try to increment
your own module reference count unless it has already been incremented
by someone external first.

As "proof", what happens if this module is unloaded right _before_ this
call happens? The module will be unloaded, memory zeroed out (or
overridden), and then the processor will resume here and try to call (or
return into) this code path.

Boom.

Just say no to "try_module_get(THIS_MODULE)" as it is totally wrong.

thanks,

greg k-h