</>EmbeddedInterview

What are the devm_ (managed) APIs?

MediumLinux Kernel & Device Drivers

Short answer: Device-managed resource functions (devm_kzalloc, devm_platform_ioremap_resource, devm_request_irq, devm_clk_get_enabled, devm_regulator_get, devm_gpiod_get...) record a release action on the device. If probe fails, or the device is later unbound, all managed resources are released automatically in reverse order. This removes most error-path cleanup code and the leaks that come with it.

Before and after

/* manual: every error path must undo the previous steps */
base = ioremap(res->start, resource_size(res));
if (!base) return -ENOMEM;
ret = request_irq(irq, handler, 0, "x", d);
if (ret) { iounmap(base); return ret; }

/* managed: just return on error */
base = devm_ioremap_resource(dev, res);
if (IS_ERR(base)) return PTR_ERR(base);
ret = devm_request_irq(dev, irq, handler, 0, "x", d);
if (ret) return ret;

Custom cleanup: devm_add_action_or_reset(dev, my_cleanup, data) registers any function to run on release (e.g. to put hardware into reset).

Pitfalls

  • Ordering with remove(): managed resources are released after remove() returns. A managed IRQ can still fire after remove() has stopped or freed something the handler uses; disable the device's interrupts in hardware in remove(), or make that teardown itself a devm action registered in the right order.
  • Lifetime: memory from devm_kzalloc is freed when the device unbinds, even if user space still has the /dev file open; data reachable from open files must be reference-counted separately.
  • Do not use devm functions outside probe paths for resources that are created and destroyed repeatedly (they accumulate until unbind).