devm-helpers.h (2740B)
1/* SPDX-License-Identifier: GPL-2.0-only */ 2#ifndef __LINUX_DEVM_HELPERS_H 3#define __LINUX_DEVM_HELPERS_H 4 5/* 6 * Functions which do automatically cancel operations or release resources upon 7 * driver detach. 8 * 9 * These should be helpful to avoid mixing the manual and devm-based resource 10 * management which can be source of annoying, rarely occurring, 11 * hard-to-reproduce bugs. 12 * 13 * Please take into account that devm based cancellation may be performed some 14 * time after the remove() is ran. 15 * 16 * Thus mixing devm and manual resource management can easily cause problems 17 * when unwinding operations with dependencies. IRQ scheduling a work in a queue 18 * is typical example where IRQs are often devm-managed and WQs are manually 19 * cleaned at remove(). If IRQs are not manually freed at remove() (and this is 20 * often the case when we use devm for IRQs) we have a period of time after 21 * remove() - and before devm managed IRQs are freed - where new IRQ may fire 22 * and schedule a work item which won't be cancelled because remove() was 23 * already ran. 24 */ 25 26#include <linux/device.h> 27#include <linux/workqueue.h> 28 29static inline void devm_delayed_work_drop(void *res) 30{ 31 cancel_delayed_work_sync(res); 32} 33 34/** 35 * devm_delayed_work_autocancel - Resource-managed delayed work allocation 36 * @dev: Device which lifetime work is bound to 37 * @w: Work item to be queued 38 * @worker: Worker function 39 * 40 * Initialize delayed work which is automatically cancelled when driver is 41 * detached. A few drivers need delayed work which must be cancelled before 42 * driver is detached to avoid accessing removed resources. 43 * devm_delayed_work_autocancel() can be used to omit the explicit 44 * cancelleation when driver is detached. 45 */ 46static inline int devm_delayed_work_autocancel(struct device *dev, 47 struct delayed_work *w, 48 work_func_t worker) 49{ 50 INIT_DELAYED_WORK(w, worker); 51 return devm_add_action(dev, devm_delayed_work_drop, w); 52} 53 54static inline void devm_work_drop(void *res) 55{ 56 cancel_work_sync(res); 57} 58 59/** 60 * devm_work_autocancel - Resource-managed work allocation 61 * @dev: Device which lifetime work is bound to 62 * @w: Work to be added (and automatically cancelled) 63 * @worker: Worker function 64 * 65 * Initialize work which is automatically cancelled when driver is detached. 66 * A few drivers need to queue work which must be cancelled before driver 67 * is detached to avoid accessing removed resources. 68 * devm_work_autocancel() can be used to omit the explicit 69 * cancelleation when driver is detached. 70 */ 71static inline int devm_work_autocancel(struct device *dev, 72 struct work_struct *w, 73 work_func_t worker) 74{ 75 INIT_WORK(w, worker); 76 return devm_add_action(dev, devm_work_drop, w); 77} 78 79#endif