1// SPDX-License-Identifier: GPL-2.0-only
2#include "dm-core.h"
3
4/*
5 * The kobject release method must not be placed in the module itself,
6 * otherwise we are subject to module unload races.
7 *
8 * The release method is called when the last reference to the kobject is
9 * dropped. It may be called by any other kernel code that drops the last
10 * reference.
11 *
12 * The release method suffers from module unload race. We may prevent the
13 * module from being unloaded at the start of the release method (using
14 * increased module reference count or synchronizing against the release
15 * method), however there is no way to prevent the module from being
16 * unloaded at the end of the release method.
17 *
18 * If this code were placed in the dm module, the following race may
19 * happen:
20 *  1. Some other process takes a reference to dm kobject
21 *  2. The user issues ioctl function to unload the dm device
22 *  3. dm_sysfs_exit calls kobject_put, however the object is not released
23 *     because of the other reference taken at step 1
24 *  4. dm_sysfs_exit waits on the completion
25 *  5. The other process that took the reference in step 1 drops it,
26 *     dm_kobject_release is called from this process
27 *  6. dm_kobject_release calls complete()
28 *  7. a reschedule happens before dm_kobject_release returns
29 *  8. dm_sysfs_exit continues, the dm device is unloaded, module reference
30 *     count is decremented
31 *  9. The user unloads the dm module
32 * 10. The other process that was rescheduled in step 7 continues to run,
33 *     it is now executing code in unloaded module, so it crashes
34 *
35 * Note that if the process that takes the foreign reference to dm kobject
36 * has a low priority and the system is sufficiently loaded with
37 * higher-priority processes that prevent the low-priority process from
38 * being scheduled long enough, this bug may really happen.
39 *
40 * In order to fix this module unload race, we place the release method
41 * into a helper code that is compiled directly into the kernel.
42 */
43
44void dm_kobject_release(struct kobject *kobj)
45{
46	complete(dm_get_completion_from_kobject(kobj));
47}
48EXPORT_SYMBOL(dm_kobject_release);
49