Question

I developed a peripheral driver for Linux. The .probe function performs the usual error checks like memory allocation failures, and also attempts to communicate with the hardware and in any type of error, deallocates any memory and returns an error code like -ENOMEM or -EIO.

The problem is, although the module probe function return -EIO when the hardware is unreachable, I still see the module is listed in lsmod output. Is it possible to make sure an insmod completely fails when there is a problem during initialization?

Here is my current probe function. All device specific functions return an appropriate error code on failure, usually -EIO.

static int mlx90399_probe(struct i2c_client *client,
        const struct i2c_device_id *id)
{
    int err;
    struct mlx90399_data *data;

    data = kzalloc(sizeof(*data), GFP_KERNEL);
    if (!data) {
        dev_err(&client->dev, "Memory allocation fails\n");
        err = -ENOMEM;
        goto exit;
    }
    i2c_set_clientdata(client, data);
    data->client = client;
    mutex_init(&data->lock);
    data->mode = MLX90399_MODE_OFF;

    err = mlx90399_reset(client);
    if (err < 0)
        goto exit;

    msleep(1); /* nominal 0.6ms from reset */
    err = mlx90399_write_register_defaults(client);
    if (err < 0)
        goto exit;

    err = mlx90399_update_scale(client);
    if (err < 0)
        goto exit;

    data->indio_dev = iio_allocate_device(0);
    if (data->indio_dev == NULL) {
        err = -ENOMEM;
        goto exit;
    }

    data->indio_dev->dev.parent = &client->dev;
    data->indio_dev->info = &mlx90399_info;
    data->indio_dev->dev_data = (void *)(data);
    data->indio_dev->modes = INDIO_DIRECT_MODE;

    mlx90399_setup_irq(client);

    err = iio_device_register(data->indio_dev);
    if(err < 0)
        goto exit;

    return 0;

exit:
    kfree(data);
    return err;
}
Was it helpful?

Solution

See the comment in __driver_attach():

/*
 * Lock device and try to bind to it. We drop the error
 * here and always return 0, because we need to keep trying
 * to bind to devices and some drivers will return an error
 * simply if it didn't support the device.
 *
 * driver_probe_device() will spit a warning if there
 * is an error.
 */

To make the module initialization fail, unregister the driver and return an error code from your init function.

OTHER TIPS

Note that there isn't necessarily a 1:1 relationship between a module and a device. One module may be used for several devices. With the use of device trees, for example, a device tree may declare several on-board UARTs, all using one serial device kernel module. The module's probe function would be called several times, once for each device. Just because one probe call fails, that doesn't necessarily mean the module should be unloaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top