linux-stable/lib/once.c
Kefeng Wang 57bd5b59f1 once: Fix panic when module unload
[ Upstream commit 1027b96ec9 ]

DO_ONCE
DEFINE_STATIC_KEY_TRUE(___once_key);
__do_once_done
  once_disable_jump(once_key);
    INIT_WORK(&w->work, once_deferred);
    struct once_work *w;
    w->key = key;
    schedule_work(&w->work);                     module unload
                                                   //*the key is
destroy*
process_one_work
  once_deferred
    BUG_ON(!static_key_enabled(work->key));
       static_key_count((struct static_key *)x)    //*access key, crash*

When module uses DO_ONCE mechanism, it could crash due to the above
concurrency problem, we could reproduce it with link[1].

Fix it by add/put module refcount in the once work process.

[1] https://lore.kernel.org/netdev/eaa6c371-465e-57eb-6be9-f4b16b9d7cbf@huawei.com/

Cc: Hannes Frederic Sowa <hannes@stressinduktion.org>
Cc: Daniel Borkmann <daniel@iogearbox.net>
Cc: David S. Miller <davem@davemloft.net>
Cc: Eric Dumazet <edumazet@google.com>
Reported-by: Minmin chen <chenmingmin@huawei.com>
Signed-off-by: Kefeng Wang <wangkefeng.wang@huawei.com>
Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
Signed-off-by: Sasha Levin <sashal@kernel.org>
2021-09-03 10:08:12 +02:00

68 lines
1.5 KiB
C

// SPDX-License-Identifier: GPL-2.0
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/once.h>
#include <linux/random.h>
#include <linux/module.h>
struct once_work {
struct work_struct work;
struct static_key_true *key;
struct module *module;
};
static void once_deferred(struct work_struct *w)
{
struct once_work *work;
work = container_of(w, struct once_work, work);
BUG_ON(!static_key_enabled(work->key));
static_branch_disable(work->key);
module_put(work->module);
kfree(work);
}
static void once_disable_jump(struct static_key_true *key, struct module *mod)
{
struct once_work *w;
w = kmalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return;
INIT_WORK(&w->work, once_deferred);
w->key = key;
w->module = mod;
__module_get(mod);
schedule_work(&w->work);
}
static DEFINE_SPINLOCK(once_lock);
bool __do_once_start(bool *done, unsigned long *flags)
__acquires(once_lock)
{
spin_lock_irqsave(&once_lock, *flags);
if (*done) {
spin_unlock_irqrestore(&once_lock, *flags);
/* Keep sparse happy by restoring an even lock count on
* this lock. In case we return here, we don't call into
* __do_once_done but return early in the DO_ONCE() macro.
*/
__acquire(once_lock);
return false;
}
return true;
}
EXPORT_SYMBOL(__do_once_start);
void __do_once_done(bool *done, struct static_key_true *once_key,
unsigned long *flags, struct module *mod)
__releases(once_lock)
{
*done = true;
spin_unlock_irqrestore(&once_lock, *flags);
once_disable_jump(once_key, mod);
}
EXPORT_SYMBOL(__do_once_done);