xref: /linux-6.15/include/linux/jump_label.h (revision c017c71c)
1 #ifndef _LINUX_JUMP_LABEL_H
2 #define _LINUX_JUMP_LABEL_H
3 
4 /*
5  * Jump label support
6  *
7  * Copyright (C) 2009-2012 Jason Baron <[email protected]>
8  * Copyright (C) 2011-2012 Red Hat, Inc., Peter Zijlstra
9  *
10  * DEPRECATED API:
11  *
12  * The use of 'struct static_key' directly, is now DEPRECATED. In addition
13  * static_key_{true,false}() is also DEPRECATED. IE DO NOT use the following:
14  *
15  * struct static_key false = STATIC_KEY_INIT_FALSE;
16  * struct static_key true = STATIC_KEY_INIT_TRUE;
17  * static_key_true()
18  * static_key_false()
19  *
20  * The updated API replacements are:
21  *
22  * DEFINE_STATIC_KEY_TRUE(key);
23  * DEFINE_STATIC_KEY_FALSE(key);
24  * DEFINE_STATIC_KEY_ARRAY_TRUE(keys, count);
25  * DEFINE_STATIC_KEY_ARRAY_FALSE(keys, count);
26  * static_branch_likely()
27  * static_branch_unlikely()
28  *
29  * Jump labels provide an interface to generate dynamic branches using
30  * self-modifying code. Assuming toolchain and architecture support, if we
31  * define a "key" that is initially false via "DEFINE_STATIC_KEY_FALSE(key)",
32  * an "if (static_branch_unlikely(&key))" statement is an unconditional branch
33  * (which defaults to false - and the true block is placed out of line).
34  * Similarly, we can define an initially true key via
35  * "DEFINE_STATIC_KEY_TRUE(key)", and use it in the same
36  * "if (static_branch_unlikely(&key))", in which case we will generate an
37  * unconditional branch to the out-of-line true branch. Keys that are
38  * initially true or false can be using in both static_branch_unlikely()
39  * and static_branch_likely() statements.
40  *
41  * At runtime we can change the branch target by setting the key
42  * to true via a call to static_branch_enable(), or false using
43  * static_branch_disable(). If the direction of the branch is switched by
44  * these calls then we run-time modify the branch target via a
45  * no-op -> jump or jump -> no-op conversion. For example, for an
46  * initially false key that is used in an "if (static_branch_unlikely(&key))"
47  * statement, setting the key to true requires us to patch in a jump
48  * to the out-of-line of true branch.
49  *
50  * In addition to static_branch_{enable,disable}, we can also reference count
51  * the key or branch direction via static_branch_{inc,dec}. Thus,
52  * static_branch_inc() can be thought of as a 'make more true' and
53  * static_branch_dec() as a 'make more false'.
54  *
55  * Since this relies on modifying code, the branch modifying functions
56  * must be considered absolute slow paths (machine wide synchronization etc.).
57  * OTOH, since the affected branches are unconditional, their runtime overhead
58  * will be absolutely minimal, esp. in the default (off) case where the total
59  * effect is a single NOP of appropriate size. The on case will patch in a jump
60  * to the out-of-line block.
61  *
62  * When the control is directly exposed to userspace, it is prudent to delay the
63  * decrement to avoid high frequency code modifications which can (and do)
64  * cause significant performance degradation. Struct static_key_deferred and
65  * static_key_slow_dec_deferred() provide for this.
66  *
67  * Lacking toolchain and or architecture support, static keys fall back to a
68  * simple conditional branch.
69  *
70  * Additional babbling in: Documentation/static-keys.txt
71  */
72 
73 #if defined(CC_HAVE_ASM_GOTO) && defined(CONFIG_JUMP_LABEL)
74 # define HAVE_JUMP_LABEL
75 #endif
76 
77 #ifndef __ASSEMBLY__
78 
79 #include <linux/types.h>
80 #include <linux/compiler.h>
81 
82 extern bool static_key_initialized;
83 
84 #define STATIC_KEY_CHECK_USE() WARN(!static_key_initialized,		      \
85 				    "%s used before call to jump_label_init", \
86 				    __func__)
87 
88 #ifdef HAVE_JUMP_LABEL
89 
90 struct static_key {
91 	atomic_t enabled;
92 /*
93  * bit 0 => 1 if key is initially true
94  *	    0 if initially false
95  * bit 1 => 1 if points to struct static_key_mod
96  *	    0 if points to struct jump_entry
97  */
98 	union {
99 		unsigned long type;
100 		struct jump_entry *entries;
101 		struct static_key_mod *next;
102 	};
103 };
104 
105 #else
106 struct static_key {
107 	atomic_t enabled;
108 };
109 #endif	/* HAVE_JUMP_LABEL */
110 #endif /* __ASSEMBLY__ */
111 
112 #ifdef HAVE_JUMP_LABEL
113 #include <asm/jump_label.h>
114 #endif
115 
116 #ifndef __ASSEMBLY__
117 
118 enum jump_label_type {
119 	JUMP_LABEL_NOP = 0,
120 	JUMP_LABEL_JMP,
121 };
122 
123 struct module;
124 
125 #ifdef HAVE_JUMP_LABEL
126 
127 #define JUMP_TYPE_FALSE		0UL
128 #define JUMP_TYPE_TRUE		1UL
129 #define JUMP_TYPE_LINKED	2UL
130 #define JUMP_TYPE_MASK		3UL
131 
132 static __always_inline bool static_key_false(struct static_key *key)
133 {
134 	return arch_static_branch(key, false);
135 }
136 
137 static __always_inline bool static_key_true(struct static_key *key)
138 {
139 	return !arch_static_branch(key, true);
140 }
141 
142 extern struct jump_entry __start___jump_table[];
143 extern struct jump_entry __stop___jump_table[];
144 
145 extern void jump_label_init(void);
146 extern void jump_label_lock(void);
147 extern void jump_label_unlock(void);
148 extern void arch_jump_label_transform(struct jump_entry *entry,
149 				      enum jump_label_type type);
150 extern void arch_jump_label_transform_static(struct jump_entry *entry,
151 					     enum jump_label_type type);
152 extern int jump_label_text_reserved(void *start, void *end);
153 extern void static_key_slow_inc(struct static_key *key);
154 extern void static_key_slow_dec(struct static_key *key);
155 extern void jump_label_apply_nops(struct module *mod);
156 extern int static_key_count(struct static_key *key);
157 extern void static_key_enable(struct static_key *key);
158 extern void static_key_disable(struct static_key *key);
159 
160 /*
161  * We should be using ATOMIC_INIT() for initializing .enabled, but
162  * the inclusion of atomic.h is problematic for inclusion of jump_label.h
163  * in 'low-level' headers. Thus, we are initializing .enabled with a
164  * raw value, but have added a BUILD_BUG_ON() to catch any issues in
165  * jump_label_init() see: kernel/jump_label.c.
166  */
167 #define STATIC_KEY_INIT_TRUE					\
168 	{ .enabled = { 1 },					\
169 	  .entries = (void *)JUMP_TYPE_TRUE }
170 #define STATIC_KEY_INIT_FALSE					\
171 	{ .enabled = { 0 },					\
172 	  .entries = (void *)JUMP_TYPE_FALSE }
173 
174 #else  /* !HAVE_JUMP_LABEL */
175 
176 #include <linux/atomic.h>
177 #include <linux/bug.h>
178 
179 static inline int static_key_count(struct static_key *key)
180 {
181 	return atomic_read(&key->enabled);
182 }
183 
184 static __always_inline void jump_label_init(void)
185 {
186 	static_key_initialized = true;
187 }
188 
189 static __always_inline bool static_key_false(struct static_key *key)
190 {
191 	if (unlikely(static_key_count(key) > 0))
192 		return true;
193 	return false;
194 }
195 
196 static __always_inline bool static_key_true(struct static_key *key)
197 {
198 	if (likely(static_key_count(key) > 0))
199 		return true;
200 	return false;
201 }
202 
203 static inline void static_key_slow_inc(struct static_key *key)
204 {
205 	STATIC_KEY_CHECK_USE();
206 	atomic_inc(&key->enabled);
207 }
208 
209 static inline void static_key_slow_dec(struct static_key *key)
210 {
211 	STATIC_KEY_CHECK_USE();
212 	atomic_dec(&key->enabled);
213 }
214 
215 static inline int jump_label_text_reserved(void *start, void *end)
216 {
217 	return 0;
218 }
219 
220 static inline void jump_label_lock(void) {}
221 static inline void jump_label_unlock(void) {}
222 
223 static inline int jump_label_apply_nops(struct module *mod)
224 {
225 	return 0;
226 }
227 
228 static inline void static_key_enable(struct static_key *key)
229 {
230 	int count = static_key_count(key);
231 
232 	WARN_ON_ONCE(count < 0 || count > 1);
233 
234 	if (!count)
235 		static_key_slow_inc(key);
236 }
237 
238 static inline void static_key_disable(struct static_key *key)
239 {
240 	int count = static_key_count(key);
241 
242 	WARN_ON_ONCE(count < 0 || count > 1);
243 
244 	if (count)
245 		static_key_slow_dec(key);
246 }
247 
248 #define STATIC_KEY_INIT_TRUE	{ .enabled = ATOMIC_INIT(1) }
249 #define STATIC_KEY_INIT_FALSE	{ .enabled = ATOMIC_INIT(0) }
250 
251 #endif	/* HAVE_JUMP_LABEL */
252 
253 #define STATIC_KEY_INIT STATIC_KEY_INIT_FALSE
254 #define jump_label_enabled static_key_enabled
255 
256 /* -------------------------------------------------------------------------- */
257 
258 /*
259  * Two type wrappers around static_key, such that we can use compile time
260  * type differentiation to emit the right code.
261  *
262  * All the below code is macros in order to play type games.
263  */
264 
265 struct static_key_true {
266 	struct static_key key;
267 };
268 
269 struct static_key_false {
270 	struct static_key key;
271 };
272 
273 #define STATIC_KEY_TRUE_INIT  (struct static_key_true) { .key = STATIC_KEY_INIT_TRUE,  }
274 #define STATIC_KEY_FALSE_INIT (struct static_key_false){ .key = STATIC_KEY_INIT_FALSE, }
275 
276 #define DEFINE_STATIC_KEY_TRUE(name)	\
277 	struct static_key_true name = STATIC_KEY_TRUE_INIT
278 
279 #define DECLARE_STATIC_KEY_TRUE(name)	\
280 	extern struct static_key_true name
281 
282 #define DEFINE_STATIC_KEY_FALSE(name)	\
283 	struct static_key_false name = STATIC_KEY_FALSE_INIT
284 
285 #define DECLARE_STATIC_KEY_FALSE(name)	\
286 	extern struct static_key_false name
287 
288 #define DEFINE_STATIC_KEY_ARRAY_TRUE(name, count)		\
289 	struct static_key_true name[count] = {			\
290 		[0 ... (count) - 1] = STATIC_KEY_TRUE_INIT,	\
291 	}
292 
293 #define DEFINE_STATIC_KEY_ARRAY_FALSE(name, count)		\
294 	struct static_key_false name[count] = {			\
295 		[0 ... (count) - 1] = STATIC_KEY_FALSE_INIT,	\
296 	}
297 
298 extern bool ____wrong_branch_error(void);
299 
300 #define static_key_enabled(x)							\
301 ({										\
302 	if (!__builtin_types_compatible_p(typeof(*x), struct static_key) &&	\
303 	    !__builtin_types_compatible_p(typeof(*x), struct static_key_true) &&\
304 	    !__builtin_types_compatible_p(typeof(*x), struct static_key_false))	\
305 		____wrong_branch_error();					\
306 	static_key_count((struct static_key *)x) > 0;				\
307 })
308 
309 #ifdef HAVE_JUMP_LABEL
310 
311 /*
312  * Combine the right initial value (type) with the right branch order
313  * to generate the desired result.
314  *
315  *
316  * type\branch|	likely (1)	      |	unlikely (0)
317  * -----------+-----------------------+------------------
318  *            |                       |
319  *  true (1)  |	   ...		      |	   ...
320  *            |    NOP		      |	   JMP L
321  *            |    <br-stmts>	      |	1: ...
322  *            |	L: ...		      |
323  *            |			      |
324  *            |			      |	L: <br-stmts>
325  *            |			      |	   jmp 1b
326  *            |                       |
327  * -----------+-----------------------+------------------
328  *            |                       |
329  *  false (0) |	   ...		      |	   ...
330  *            |    JMP L	      |	   NOP
331  *            |    <br-stmts>	      |	1: ...
332  *            |	L: ...		      |
333  *            |			      |
334  *            |			      |	L: <br-stmts>
335  *            |			      |	   jmp 1b
336  *            |                       |
337  * -----------+-----------------------+------------------
338  *
339  * The initial value is encoded in the LSB of static_key::entries,
340  * type: 0 = false, 1 = true.
341  *
342  * The branch type is encoded in the LSB of jump_entry::key,
343  * branch: 0 = unlikely, 1 = likely.
344  *
345  * This gives the following logic table:
346  *
347  *	enabled	type	branch	  instuction
348  * -----------------------------+-----------
349  *	0	0	0	| NOP
350  *	0	0	1	| JMP
351  *	0	1	0	| NOP
352  *	0	1	1	| JMP
353  *
354  *	1	0	0	| JMP
355  *	1	0	1	| NOP
356  *	1	1	0	| JMP
357  *	1	1	1	| NOP
358  *
359  * Which gives the following functions:
360  *
361  *   dynamic: instruction = enabled ^ branch
362  *   static:  instruction = type ^ branch
363  *
364  * See jump_label_type() / jump_label_init_type().
365  */
366 
367 #define static_branch_likely(x)							\
368 ({										\
369 	bool branch;								\
370 	if (__builtin_types_compatible_p(typeof(*x), struct static_key_true))	\
371 		branch = !arch_static_branch(&(x)->key, true);			\
372 	else if (__builtin_types_compatible_p(typeof(*x), struct static_key_false)) \
373 		branch = !arch_static_branch_jump(&(x)->key, true);		\
374 	else									\
375 		branch = ____wrong_branch_error();				\
376 	branch;									\
377 })
378 
379 #define static_branch_unlikely(x)						\
380 ({										\
381 	bool branch;								\
382 	if (__builtin_types_compatible_p(typeof(*x), struct static_key_true))	\
383 		branch = arch_static_branch_jump(&(x)->key, false);		\
384 	else if (__builtin_types_compatible_p(typeof(*x), struct static_key_false)) \
385 		branch = arch_static_branch(&(x)->key, false);			\
386 	else									\
387 		branch = ____wrong_branch_error();				\
388 	branch;									\
389 })
390 
391 #else /* !HAVE_JUMP_LABEL */
392 
393 #define static_branch_likely(x)		likely(static_key_enabled(&(x)->key))
394 #define static_branch_unlikely(x)	unlikely(static_key_enabled(&(x)->key))
395 
396 #endif /* HAVE_JUMP_LABEL */
397 
398 /*
399  * Advanced usage; refcount, branch is enabled when: count != 0
400  */
401 
402 #define static_branch_inc(x)		static_key_slow_inc(&(x)->key)
403 #define static_branch_dec(x)		static_key_slow_dec(&(x)->key)
404 
405 /*
406  * Normal usage; boolean enable/disable.
407  */
408 
409 #define static_branch_enable(x)		static_key_enable(&(x)->key)
410 #define static_branch_disable(x)	static_key_disable(&(x)->key)
411 
412 #endif /* __ASSEMBLY__ */
413 
414 #endif	/* _LINUX_JUMP_LABEL_H */
415