once.c 1.35 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4 5 6
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/once.h>
#include <linux/random.h>

7
struct once_work {
8 9 10 11
	struct work_struct work;
	struct static_key *key;
};

12
static void once_deferred(struct work_struct *w)
13
{
14
	struct once_work *work;
15

16
	work = container_of(w, struct once_work, work);
17 18 19 20 21
	BUG_ON(!static_key_enabled(work->key));
	static_key_slow_dec(work->key);
	kfree(work);
}

22
static void once_disable_jump(struct static_key *key)
23
{
24
	struct once_work *w;
25 26 27 28 29

	w = kmalloc(sizeof(*w), GFP_ATOMIC);
	if (!w)
		return;

30
	INIT_WORK(&w->work, once_deferred);
31 32 33 34
	w->key = key;
	schedule_work(&w->work);
}

35
static DEFINE_SPINLOCK(once_lock);
36

37 38 39 40
bool __do_once_start(bool *done, unsigned long *flags)
	__acquires(once_lock)
{
	spin_lock_irqsave(&once_lock, *flags);
41
	if (*done) {
42 43 44 45 46 47
		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);
48 49 50 51 52
		return false;
	}

	return true;
}
53 54 55 56 57 58 59 60 61 62 63
EXPORT_SYMBOL(__do_once_start);

void __do_once_done(bool *done, struct static_key *once_key,
		    unsigned long *flags)
	__releases(once_lock)
{
	*done = true;
	spin_unlock_irqrestore(&once_lock, *flags);
	once_disable_jump(once_key);
}
EXPORT_SYMBOL(__do_once_done);