Search code examples
kernellinux-device-driverkernel-modulelinuxkit

Linux Kernel: how to use request_module() and try_module_get()


I'm struggling to understand how to use in the proper way the

try_module_get()

I found this interesting post: How to put a check in the code to ensure the inter kernel module dependency - Linux Kernel?

But I miss one point: I can get the request_module working, but I don' get how to use the try_module_get

I explain:

If I use

ret = request_module("ipt_conntrack")

the module xt_conntrack is correctly inserted, but marked as no used, because accordingly to the above post I didn't used the try_module_get.

But how can I call the try_module_get? The function requires a struct module parameter, which I don't know how to populate for the xt_conntrack module. I found several examples, but all related to the "THIS_MODULE" parameter, which does not apply in this case. Can you point me in the right direction for this?

Thanks for your help


Solution

  • Perhaps something like this would work. I haven't tested it.

    /**
     * try_find_module_get() - Try and get reference to named module
     * @name: Name of module
     *
     * Attempt to find the named module.  If not found, attempt to request the module by
     * name and try to find it again.  If the module is found (possibly after requesting the
     * module), try and get a reference to it.
     *
     * Return:
     * * pointer to module if found and got a reference.
     * * NULL if module not found or failed to get a reference.
     */
    static struct module *try_find_module_get(const char *name)
    {
        struct module *mod;
    
        mutex_lock(&module_mutex);
        /* Try and find the module. */
        mod = find_module(name);
        if (!mod) {
            mutex_unlock(&module_mutex);
            /* Not found.  Try and request it. */
            if (request_module(name))
                return NULL;  /* Failed to request module. */
            mutex_lock(&module_mutex);
            /* Module requested.  Try and find it again. */
            mod = find_module(name);
        }
        /* Try and get a reference if module found. */
        if (mod && !try_module_get(mod))
            mod = NULL;  /* Failed to get a reference. */
        mutex_unlock(&module_mutex);
        return mod;
    }