xref: /linux-6.15/include/linux/sbitmap.h (revision efe1f3a1)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  * Fast and scalable bitmaps.
4  *
5  * Copyright (C) 2016 Facebook
6  * Copyright (C) 2013-2014 Jens Axboe
7  */
8 
9 #ifndef __LINUX_SCALE_BITMAP_H
10 #define __LINUX_SCALE_BITMAP_H
11 
12 #include <linux/kernel.h>
13 #include <linux/slab.h>
14 
15 struct seq_file;
16 
17 /**
18  * struct sbitmap_word - Word in a &struct sbitmap.
19  */
20 struct sbitmap_word {
21 	/**
22 	 * @depth: Number of bits being used in @word/@cleared
23 	 */
24 	unsigned long depth;
25 
26 	/**
27 	 * @word: word holding free bits
28 	 */
29 	unsigned long word ____cacheline_aligned_in_smp;
30 
31 	/**
32 	 * @cleared: word holding cleared bits
33 	 */
34 	unsigned long cleared ____cacheline_aligned_in_smp;
35 } ____cacheline_aligned_in_smp;
36 
37 /**
38  * struct sbitmap - Scalable bitmap.
39  *
40  * A &struct sbitmap is spread over multiple cachelines to avoid ping-pong. This
41  * trades off higher memory usage for better scalability.
42  */
43 struct sbitmap {
44 	/**
45 	 * @depth: Number of bits used in the whole bitmap.
46 	 */
47 	unsigned int depth;
48 
49 	/**
50 	 * @shift: log2(number of bits used per word)
51 	 */
52 	unsigned int shift;
53 
54 	/**
55 	 * @map_nr: Number of words (cachelines) being used for the bitmap.
56 	 */
57 	unsigned int map_nr;
58 
59 	/**
60 	 * @round_robin: Allocate bits in strict round-robin order.
61 	 */
62 	bool round_robin;
63 
64 	/**
65 	 * @map: Allocated bitmap.
66 	 */
67 	struct sbitmap_word *map;
68 };
69 
70 #define SBQ_WAIT_QUEUES 8
71 #define SBQ_WAKE_BATCH 8
72 
73 /**
74  * struct sbq_wait_state - Wait queue in a &struct sbitmap_queue.
75  */
76 struct sbq_wait_state {
77 	/**
78 	 * @wait_cnt: Number of frees remaining before we wake up.
79 	 */
80 	atomic_t wait_cnt;
81 
82 	/**
83 	 * @wait: Wait queue.
84 	 */
85 	wait_queue_head_t wait;
86 } ____cacheline_aligned_in_smp;
87 
88 /**
89  * struct sbitmap_queue - Scalable bitmap with the added ability to wait on free
90  * bits.
91  *
92  * A &struct sbitmap_queue uses multiple wait queues and rolling wakeups to
93  * avoid contention on the wait queue spinlock. This ensures that we don't hit a
94  * scalability wall when we run out of free bits and have to start putting tasks
95  * to sleep.
96  */
97 struct sbitmap_queue {
98 	/**
99 	 * @sb: Scalable bitmap.
100 	 */
101 	struct sbitmap sb;
102 
103 	/*
104 	 * @alloc_hint: Cache of last successfully allocated or freed bit.
105 	 *
106 	 * This is per-cpu, which allows multiple users to stick to different
107 	 * cachelines until the map is exhausted.
108 	 */
109 	unsigned int __percpu *alloc_hint;
110 
111 	/**
112 	 * @wake_batch: Number of bits which must be freed before we wake up any
113 	 * waiters.
114 	 */
115 	unsigned int wake_batch;
116 
117 	/**
118 	 * @wake_index: Next wait queue in @ws to wake up.
119 	 */
120 	atomic_t wake_index;
121 
122 	/**
123 	 * @ws: Wait queues.
124 	 */
125 	struct sbq_wait_state *ws;
126 
127 	/*
128 	 * @ws_active: count of currently active ws waitqueues
129 	 */
130 	atomic_t ws_active;
131 
132 	/**
133 	 * @min_shallow_depth: The minimum shallow depth which may be passed to
134 	 * sbitmap_queue_get_shallow() or __sbitmap_queue_get_shallow().
135 	 */
136 	unsigned int min_shallow_depth;
137 };
138 
139 /**
140  * sbitmap_init_node() - Initialize a &struct sbitmap on a specific memory node.
141  * @sb: Bitmap to initialize.
142  * @depth: Number of bits to allocate.
143  * @shift: Use 2^@shift bits per word in the bitmap; if a negative number if
144  *         given, a good default is chosen.
145  * @flags: Allocation flags.
146  * @node: Memory node to allocate on.
147  * @round_robin: If true, be stricter about allocation order; always allocate
148  *               starting from the last allocated bit. This is less efficient
149  *               than the default behavior (false).
150  *
151  * Return: Zero on success or negative errno on failure.
152  */
153 int sbitmap_init_node(struct sbitmap *sb, unsigned int depth, int shift,
154 		      gfp_t flags, int node, bool round_robin);
155 
156 /**
157  * sbitmap_free() - Free memory used by a &struct sbitmap.
158  * @sb: Bitmap to free.
159  */
160 static inline void sbitmap_free(struct sbitmap *sb)
161 {
162 	kfree(sb->map);
163 	sb->map = NULL;
164 }
165 
166 /**
167  * sbitmap_resize() - Resize a &struct sbitmap.
168  * @sb: Bitmap to resize.
169  * @depth: New number of bits to resize to.
170  *
171  * Doesn't reallocate anything. It's up to the caller to ensure that the new
172  * depth doesn't exceed the depth that the sb was initialized with.
173  */
174 void sbitmap_resize(struct sbitmap *sb, unsigned int depth);
175 
176 /**
177  * sbitmap_get() - Try to allocate a free bit from a &struct sbitmap.
178  * @sb: Bitmap to allocate from.
179  * @alloc_hint: Hint for where to start searching for a free bit.
180  *
181  * This operation provides acquire barrier semantics if it succeeds.
182  *
183  * Return: Non-negative allocated bit number if successful, -1 otherwise.
184  */
185 int sbitmap_get(struct sbitmap *sb, unsigned int alloc_hint);
186 
187 /**
188  * sbitmap_get_shallow() - Try to allocate a free bit from a &struct sbitmap,
189  * limiting the depth used from each word.
190  * @sb: Bitmap to allocate from.
191  * @alloc_hint: Hint for where to start searching for a free bit.
192  * @shallow_depth: The maximum number of bits to allocate from a single word.
193  *
194  * This rather specific operation allows for having multiple users with
195  * different allocation limits. E.g., there can be a high-priority class that
196  * uses sbitmap_get() and a low-priority class that uses sbitmap_get_shallow()
197  * with a @shallow_depth of (1 << (@sb->shift - 1)). Then, the low-priority
198  * class can only allocate half of the total bits in the bitmap, preventing it
199  * from starving out the high-priority class.
200  *
201  * Return: Non-negative allocated bit number if successful, -1 otherwise.
202  */
203 int sbitmap_get_shallow(struct sbitmap *sb, unsigned int alloc_hint,
204 			unsigned long shallow_depth);
205 
206 /**
207  * sbitmap_any_bit_set() - Check for a set bit in a &struct sbitmap.
208  * @sb: Bitmap to check.
209  *
210  * Return: true if any bit in the bitmap is set, false otherwise.
211  */
212 bool sbitmap_any_bit_set(const struct sbitmap *sb);
213 
214 #define SB_NR_TO_INDEX(sb, bitnr) ((bitnr) >> (sb)->shift)
215 #define SB_NR_TO_BIT(sb, bitnr) ((bitnr) & ((1U << (sb)->shift) - 1U))
216 
217 typedef bool (*sb_for_each_fn)(struct sbitmap *, unsigned int, void *);
218 
219 /**
220  * __sbitmap_for_each_set() - Iterate over each set bit in a &struct sbitmap.
221  * @start: Where to start the iteration.
222  * @sb: Bitmap to iterate over.
223  * @fn: Callback. Should return true to continue or false to break early.
224  * @data: Pointer to pass to callback.
225  *
226  * This is inline even though it's non-trivial so that the function calls to the
227  * callback will hopefully get optimized away.
228  */
229 static inline void __sbitmap_for_each_set(struct sbitmap *sb,
230 					  unsigned int start,
231 					  sb_for_each_fn fn, void *data)
232 {
233 	unsigned int index;
234 	unsigned int nr;
235 	unsigned int scanned = 0;
236 
237 	if (start >= sb->depth)
238 		start = 0;
239 	index = SB_NR_TO_INDEX(sb, start);
240 	nr = SB_NR_TO_BIT(sb, start);
241 
242 	while (scanned < sb->depth) {
243 		unsigned long word;
244 		unsigned int depth = min_t(unsigned int,
245 					   sb->map[index].depth - nr,
246 					   sb->depth - scanned);
247 
248 		scanned += depth;
249 		word = sb->map[index].word & ~sb->map[index].cleared;
250 		if (!word)
251 			goto next;
252 
253 		/*
254 		 * On the first iteration of the outer loop, we need to add the
255 		 * bit offset back to the size of the word for find_next_bit().
256 		 * On all other iterations, nr is zero, so this is a noop.
257 		 */
258 		depth += nr;
259 		while (1) {
260 			nr = find_next_bit(&word, depth, nr);
261 			if (nr >= depth)
262 				break;
263 			if (!fn(sb, (index << sb->shift) + nr, data))
264 				return;
265 
266 			nr++;
267 		}
268 next:
269 		nr = 0;
270 		if (++index >= sb->map_nr)
271 			index = 0;
272 	}
273 }
274 
275 /**
276  * sbitmap_for_each_set() - Iterate over each set bit in a &struct sbitmap.
277  * @sb: Bitmap to iterate over.
278  * @fn: Callback. Should return true to continue or false to break early.
279  * @data: Pointer to pass to callback.
280  */
281 static inline void sbitmap_for_each_set(struct sbitmap *sb, sb_for_each_fn fn,
282 					void *data)
283 {
284 	__sbitmap_for_each_set(sb, 0, fn, data);
285 }
286 
287 static inline unsigned long *__sbitmap_word(struct sbitmap *sb,
288 					    unsigned int bitnr)
289 {
290 	return &sb->map[SB_NR_TO_INDEX(sb, bitnr)].word;
291 }
292 
293 /* Helpers equivalent to the operations in asm/bitops.h and linux/bitmap.h */
294 
295 static inline void sbitmap_set_bit(struct sbitmap *sb, unsigned int bitnr)
296 {
297 	set_bit(SB_NR_TO_BIT(sb, bitnr), __sbitmap_word(sb, bitnr));
298 }
299 
300 static inline void sbitmap_clear_bit(struct sbitmap *sb, unsigned int bitnr)
301 {
302 	clear_bit(SB_NR_TO_BIT(sb, bitnr), __sbitmap_word(sb, bitnr));
303 }
304 
305 /*
306  * This one is special, since it doesn't actually clear the bit, rather it
307  * sets the corresponding bit in the ->cleared mask instead. Paired with
308  * the caller doing sbitmap_deferred_clear() if a given index is full, which
309  * will clear the previously freed entries in the corresponding ->word.
310  */
311 static inline void sbitmap_deferred_clear_bit(struct sbitmap *sb, unsigned int bitnr)
312 {
313 	unsigned long *addr = &sb->map[SB_NR_TO_INDEX(sb, bitnr)].cleared;
314 
315 	set_bit(SB_NR_TO_BIT(sb, bitnr), addr);
316 }
317 
318 static inline int sbitmap_test_bit(struct sbitmap *sb, unsigned int bitnr)
319 {
320 	return test_bit(SB_NR_TO_BIT(sb, bitnr), __sbitmap_word(sb, bitnr));
321 }
322 
323 /**
324  * sbitmap_show() - Dump &struct sbitmap information to a &struct seq_file.
325  * @sb: Bitmap to show.
326  * @m: struct seq_file to write to.
327  *
328  * This is intended for debugging. The format may change at any time.
329  */
330 void sbitmap_show(struct sbitmap *sb, struct seq_file *m);
331 
332 /**
333  * sbitmap_bitmap_show() - Write a hex dump of a &struct sbitmap to a &struct
334  * seq_file.
335  * @sb: Bitmap to show.
336  * @m: struct seq_file to write to.
337  *
338  * This is intended for debugging. The output isn't guaranteed to be internally
339  * consistent.
340  */
341 void sbitmap_bitmap_show(struct sbitmap *sb, struct seq_file *m);
342 
343 /**
344  * sbitmap_queue_init_node() - Initialize a &struct sbitmap_queue on a specific
345  * memory node.
346  * @sbq: Bitmap queue to initialize.
347  * @depth: See sbitmap_init_node().
348  * @shift: See sbitmap_init_node().
349  * @round_robin: See sbitmap_get().
350  * @flags: Allocation flags.
351  * @node: Memory node to allocate on.
352  *
353  * Return: Zero on success or negative errno on failure.
354  */
355 int sbitmap_queue_init_node(struct sbitmap_queue *sbq, unsigned int depth,
356 			    int shift, bool round_robin, gfp_t flags, int node);
357 
358 /**
359  * sbitmap_queue_free() - Free memory used by a &struct sbitmap_queue.
360  *
361  * @sbq: Bitmap queue to free.
362  */
363 static inline void sbitmap_queue_free(struct sbitmap_queue *sbq)
364 {
365 	kfree(sbq->ws);
366 	free_percpu(sbq->alloc_hint);
367 	sbitmap_free(&sbq->sb);
368 }
369 
370 /**
371  * sbitmap_queue_resize() - Resize a &struct sbitmap_queue.
372  * @sbq: Bitmap queue to resize.
373  * @depth: New number of bits to resize to.
374  *
375  * Like sbitmap_resize(), this doesn't reallocate anything. It has to do
376  * some extra work on the &struct sbitmap_queue, so it's not safe to just
377  * resize the underlying &struct sbitmap.
378  */
379 void sbitmap_queue_resize(struct sbitmap_queue *sbq, unsigned int depth);
380 
381 /**
382  * __sbitmap_queue_get() - Try to allocate a free bit from a &struct
383  * sbitmap_queue with preemption already disabled.
384  * @sbq: Bitmap queue to allocate from.
385  *
386  * Return: Non-negative allocated bit number if successful, -1 otherwise.
387  */
388 int __sbitmap_queue_get(struct sbitmap_queue *sbq);
389 
390 /**
391  * __sbitmap_queue_get_shallow() - Try to allocate a free bit from a &struct
392  * sbitmap_queue, limiting the depth used from each word, with preemption
393  * already disabled.
394  * @sbq: Bitmap queue to allocate from.
395  * @shallow_depth: The maximum number of bits to allocate from a single word.
396  * See sbitmap_get_shallow().
397  *
398  * If you call this, make sure to call sbitmap_queue_min_shallow_depth() after
399  * initializing @sbq.
400  *
401  * Return: Non-negative allocated bit number if successful, -1 otherwise.
402  */
403 int __sbitmap_queue_get_shallow(struct sbitmap_queue *sbq,
404 				unsigned int shallow_depth);
405 
406 /**
407  * sbitmap_queue_get() - Try to allocate a free bit from a &struct
408  * sbitmap_queue.
409  * @sbq: Bitmap queue to allocate from.
410  * @cpu: Output parameter; will contain the CPU we ran on (e.g., to be passed to
411  *       sbitmap_queue_clear()).
412  *
413  * Return: Non-negative allocated bit number if successful, -1 otherwise.
414  */
415 static inline int sbitmap_queue_get(struct sbitmap_queue *sbq,
416 				    unsigned int *cpu)
417 {
418 	int nr;
419 
420 	*cpu = get_cpu();
421 	nr = __sbitmap_queue_get(sbq);
422 	put_cpu();
423 	return nr;
424 }
425 
426 /**
427  * sbitmap_queue_get_shallow() - Try to allocate a free bit from a &struct
428  * sbitmap_queue, limiting the depth used from each word.
429  * @sbq: Bitmap queue to allocate from.
430  * @cpu: Output parameter; will contain the CPU we ran on (e.g., to be passed to
431  *       sbitmap_queue_clear()).
432  * @shallow_depth: The maximum number of bits to allocate from a single word.
433  * See sbitmap_get_shallow().
434  *
435  * If you call this, make sure to call sbitmap_queue_min_shallow_depth() after
436  * initializing @sbq.
437  *
438  * Return: Non-negative allocated bit number if successful, -1 otherwise.
439  */
440 static inline int sbitmap_queue_get_shallow(struct sbitmap_queue *sbq,
441 					    unsigned int *cpu,
442 					    unsigned int shallow_depth)
443 {
444 	int nr;
445 
446 	*cpu = get_cpu();
447 	nr = __sbitmap_queue_get_shallow(sbq, shallow_depth);
448 	put_cpu();
449 	return nr;
450 }
451 
452 /**
453  * sbitmap_queue_min_shallow_depth() - Inform a &struct sbitmap_queue of the
454  * minimum shallow depth that will be used.
455  * @sbq: Bitmap queue in question.
456  * @min_shallow_depth: The minimum shallow depth that will be passed to
457  * sbitmap_queue_get_shallow() or __sbitmap_queue_get_shallow().
458  *
459  * sbitmap_queue_clear() batches wakeups as an optimization. The batch size
460  * depends on the depth of the bitmap. Since the shallow allocation functions
461  * effectively operate with a different depth, the shallow depth must be taken
462  * into account when calculating the batch size. This function must be called
463  * with the minimum shallow depth that will be used. Failure to do so can result
464  * in missed wakeups.
465  */
466 void sbitmap_queue_min_shallow_depth(struct sbitmap_queue *sbq,
467 				     unsigned int min_shallow_depth);
468 
469 /**
470  * sbitmap_queue_clear() - Free an allocated bit and wake up waiters on a
471  * &struct sbitmap_queue.
472  * @sbq: Bitmap to free from.
473  * @nr: Bit number to free.
474  * @cpu: CPU the bit was allocated on.
475  */
476 void sbitmap_queue_clear(struct sbitmap_queue *sbq, unsigned int nr,
477 			 unsigned int cpu);
478 
479 static inline int sbq_index_inc(int index)
480 {
481 	return (index + 1) & (SBQ_WAIT_QUEUES - 1);
482 }
483 
484 static inline void sbq_index_atomic_inc(atomic_t *index)
485 {
486 	int old = atomic_read(index);
487 	int new = sbq_index_inc(old);
488 	atomic_cmpxchg(index, old, new);
489 }
490 
491 /**
492  * sbq_wait_ptr() - Get the next wait queue to use for a &struct
493  * sbitmap_queue.
494  * @sbq: Bitmap queue to wait on.
495  * @wait_index: A counter per "user" of @sbq.
496  */
497 static inline struct sbq_wait_state *sbq_wait_ptr(struct sbitmap_queue *sbq,
498 						  atomic_t *wait_index)
499 {
500 	struct sbq_wait_state *ws;
501 
502 	ws = &sbq->ws[atomic_read(wait_index)];
503 	sbq_index_atomic_inc(wait_index);
504 	return ws;
505 }
506 
507 /**
508  * sbitmap_queue_wake_all() - Wake up everything waiting on a &struct
509  * sbitmap_queue.
510  * @sbq: Bitmap queue to wake up.
511  */
512 void sbitmap_queue_wake_all(struct sbitmap_queue *sbq);
513 
514 /**
515  * sbitmap_queue_wake_up() - Wake up some of waiters in one waitqueue
516  * on a &struct sbitmap_queue.
517  * @sbq: Bitmap queue to wake up.
518  */
519 void sbitmap_queue_wake_up(struct sbitmap_queue *sbq);
520 
521 /**
522  * sbitmap_queue_show() - Dump &struct sbitmap_queue information to a &struct
523  * seq_file.
524  * @sbq: Bitmap queue to show.
525  * @m: struct seq_file to write to.
526  *
527  * This is intended for debugging. The format may change at any time.
528  */
529 void sbitmap_queue_show(struct sbitmap_queue *sbq, struct seq_file *m);
530 
531 struct sbq_wait {
532 	struct sbitmap_queue *sbq;	/* if set, sbq_wait is accounted */
533 	struct wait_queue_entry wait;
534 };
535 
536 #define DEFINE_SBQ_WAIT(name)							\
537 	struct sbq_wait name = {						\
538 		.sbq = NULL,							\
539 		.wait = {							\
540 			.private	= current,				\
541 			.func		= autoremove_wake_function,		\
542 			.entry		= LIST_HEAD_INIT((name).wait.entry),	\
543 		}								\
544 	}
545 
546 /*
547  * Wrapper around prepare_to_wait_exclusive(), which maintains some extra
548  * internal state.
549  */
550 void sbitmap_prepare_to_wait(struct sbitmap_queue *sbq,
551 				struct sbq_wait_state *ws,
552 				struct sbq_wait *sbq_wait, int state);
553 
554 /*
555  * Must be paired with sbitmap_prepare_to_wait().
556  */
557 void sbitmap_finish_wait(struct sbitmap_queue *sbq, struct sbq_wait_state *ws,
558 				struct sbq_wait *sbq_wait);
559 
560 /*
561  * Wrapper around add_wait_queue(), which maintains some extra internal state
562  */
563 void sbitmap_add_wait_queue(struct sbitmap_queue *sbq,
564 			    struct sbq_wait_state *ws,
565 			    struct sbq_wait *sbq_wait);
566 
567 /*
568  * Must be paired with sbitmap_add_wait_queue()
569  */
570 void sbitmap_del_wait_queue(struct sbq_wait *sbq_wait);
571 
572 #endif /* __LINUX_SCALE_BITMAP_H */
573