Character-device lifetime after deletion (source code)

= Character-device lifetime after deletion

\b[Character-device lifetime after deletion] is the interval during which a removed <character device> still needs valid backing state because existing users can invoke its operations. Linux `cdev_del` removes the device from new-open lookup; it does not invalidate already-open <file descriptors>. The kernel explicitly permits their file-operation callbacks after deletion returns.<Character-device number registration in the Linux kernel documentation>[Char devices, cdev_del lifetime note]{ref}

Consider an original event sequence. Process A opens an interface and retains a pointer to driver state. Removal calls `cdev_del`; process B can no longer obtain a new open through that registration. Process A then calls `read`. Freeing the state immediately after deletion would make that callback access dead storage: a <use-after-free>. The lookup lifetime and the backing allocation lifetime are different.

A useful ownership model gives the allocation one registration reference and one reference for each successful open. In a simplified <reference counting> design with $n$ opens, the reference count is $1+n$. Removal drops the registration reference; each final close drops its open reference. With two opens, the sequence is $3\to2\to1\to0$, and storage is reclaimed only at zero. This is a model of ownership, not a complete driver implementation: taking references must itself be synchronized with removal, and asynchronous work can require additional references.

The <character device> may be disconnected from its hardware before its storage is reclaimed. Existing operations can observe a synchronized disconnected state and return an appropriate error while the allocation remains valid. Reference protection alone does not make removed hardware usable or serialize simultaneous operations.

For combined device objects, `cdev_device_add` and `cdev_device_del` have their own documented pairing and parent-reference rules. The add helper can expose callbacks even when it reports failure; the delete helper distinguishes stopped sysfs callbacks from still-callable operations on existing opens.<Character-device number registration in the Linux kernel documentation>[cdev_device_add description and failure warning; cdev_device_del note]{ref} Therefore <unwinding a failed character-device registration> must follow the actual publication and ownership state. Releasing the <device number> reservation is separate from proving that every user of private storage has finished.