How to use platform_driver_register in Linux?

In Linux, the platform_driver_register() function is used to register a platform driver.

To use this function, the header file must be included.

Here is a simple example code:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>

static int my_driver_probe(struct platform_device *pdev)
{
    // 在这里编写驱动程序的初始化代码
    return 0;
}

static int my_driver_remove(struct platform_device *pdev)
{
    // 在这里编写驱动程序的卸载代码
    return 0;
}

static struct platform_driver my_driver = {
    .probe = my_driver_probe,
    .remove = my_driver_remove,
    .driver = {
        .name = "my_driver",
        .owner = THIS_MODULE,
    },
};

static int __init my_driver_init(void)
{
    int ret = platform_driver_register(&my_driver);
    if (ret != 0) {
        pr_err("Failed to register platform driver\n");
        return ret;
    }

    pr_info("Platform driver registered\n");
    return 0;
}

static void __exit my_driver_exit(void)
{
    platform_driver_unregister(&my_driver);
    pr_info("Platform driver unregistered\n");
}

module_init(my_driver_init);
module_exit(my_driver_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple platform driver");

In the example above, the function my_driver_probe() is a callback function used to initialize the driver, while my_driver_remove() is a callback function used to uninstall the driver.

The structure my_driver defines information about the driver, with the .probe field specifying the initialization callback function, and the .remove field specifying the unload callback function.

The function my_driver_init() registers the driver by calling the platform_driver_register() function. If the registration is successful, the return value is 0; otherwise, a negative number is returned.

The function my_driver_exit() unloads the driver by calling the platform_driver_unregister() function.

It is important to note that when writing a driver program, you also need to implement other necessary functions, such as device initialization and resource allocation. The above example only provides a basic framework, and the specific implementation should be modified according to your needs.

bannerAds