</>EmbeddedInterview

What is a platform device and platform driver?

MediumLinux Kernel & Device Drivers

Short answer: Platform devices are peripherals that are not on a discoverable bus: SoC blocks at fixed memory addresses (UARTs, timers, I2C/SPI controllers, GPIO banks, display controllers), usually described in the device tree. A platform driver registers a struct platform_driver with an OF match table; in probe() it gets its memory region, interrupts, clocks, resets and regulators from the device's resources and sets up the hardware.

#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/interrupt.h>

struct mydev { void __iomem *base; struct clk *clk; int irq; };

static irqreturn_t mydev_irq(int irq, void *data)
{
    struct mydev *d = data;
    u32 st = readl(d->base + 0x04);
    if (!st) return IRQ_NONE;                 /* not ours (shared line) */
    writel(st, d->base + 0x04);               /* acknowledge */
    return IRQ_HANDLED;
}

static int mydev_probe(struct platform_device *pdev)
{
    struct device *dev = &pdev->dev;
    struct mydev *d = devm_kzalloc(dev, sizeof(*d), GFP_KERNEL);
    int ret;

    if (!d) return -ENOMEM;
    d->base = devm_platform_ioremap_resource(pdev, 0);
    if (IS_ERR(d->base)) return PTR_ERR(d->base);

    d->clk = devm_clk_get_enabled(dev, NULL);          /* get + prepare + enable, auto-disabled */
    if (IS_ERR(d->clk)) return dev_err_probe(dev, PTR_ERR(d->clk), "no clock\n");

    d->irq = platform_get_irq(pdev, 0);
    if (d->irq < 0) return d->irq;
    ret = devm_request_irq(dev, d->irq, mydev_irq, 0, dev_name(dev), d);
    if (ret) return ret;

    platform_set_drvdata(pdev, d);
    dev_info(dev, "probed, version 0x%x\n", readl(d->base));
    return 0;
}

static const struct of_device_id mydev_of_match[] = {
    { .compatible = "acme,mydev" },
    { }
};
MODULE_DEVICE_TABLE(of, mydev_of_match);

static struct platform_driver mydev_driver = {
    .probe  = mydev_probe,
    .driver = { .name = "mydev", .of_match_table = mydev_of_match },
};
module_platform_driver(mydev_driver);
MODULE_LICENSE("GPL");

Matching device tree node

mydev@40010000 {
    compatible = "acme,mydev";
    reg = <0x40010000 0x1000>;
    interrupts = <GIC_SPI 45 IRQ_TYPE_LEVEL_HIGH>;
    clocks = <&ccu 12>;
};

Tips: use dev_err_probe() for errors (it stays quiet for -EPROBE_DEFER), store per-device state in a struct (no globals, so multiple instances work), and use of_device_get_match_data() to pass per-variant data from the match table.