1 /* SPDX-License-Identifier: GPL-2.0-only */
3 * Fast and scalable bitmaps.
5 * Copyright (C) 2016 Facebook
6 * Copyright (C) 2013-2014 Jens Axboe
9 #ifndef __LINUX_SCALE_BITMAP_H
10 #define __LINUX_SCALE_BITMAP_H
12 #include <linux/atomic.h>
13 #include <linux/bitops.h>
14 #include <linux/cache.h>
15 #include <linux/list.h>
16 #include <linux/log2.h>
17 #include <linux/minmax.h>
18 #include <linux/percpu.h>
19 #include <linux/slab.h>
20 #include <linux/smp.h>
21 #include <linux/types.h>
22 #include <linux/wait.h>
27 * struct sbitmap_word - Word in a &struct sbitmap.
31 * @word: word holding free bits
36 * @cleared: word holding cleared bits
38 unsigned long cleared ____cacheline_aligned_in_smp;
39 } ____cacheline_aligned_in_smp;
42 * struct sbitmap - Scalable bitmap.
44 * A &struct sbitmap is spread over multiple cachelines to avoid ping-pong. This
45 * trades off higher memory usage for better scalability.
49 * @depth: Number of bits used in the whole bitmap.
54 * @shift: log2(number of bits used per word)
59 * @map_nr: Number of words (cachelines) being used for the bitmap.
64 * @round_robin: Allocate bits in strict round-robin order.
69 * @map: Allocated bitmap.
71 struct sbitmap_word *map;
74 * @alloc_hint: Cache of last successfully allocated or freed bit.
76 * This is per-cpu, which allows multiple users to stick to different
77 * cachelines until the map is exhausted.
79 unsigned int __percpu *alloc_hint;
82 #define SBQ_WAIT_QUEUES 8
83 #define SBQ_WAKE_BATCH 8
86 * struct sbq_wait_state - Wait queue in a &struct sbitmap_queue.
88 struct sbq_wait_state {
92 wait_queue_head_t wait;
93 } ____cacheline_aligned_in_smp;
96 * struct sbitmap_queue - Scalable bitmap with the added ability to wait on free
99 * A &struct sbitmap_queue uses multiple wait queues and rolling wakeups to
100 * avoid contention on the wait queue spinlock. This ensures that we don't hit a
101 * scalability wall when we run out of free bits and have to start putting tasks
104 struct sbitmap_queue {
106 * @sb: Scalable bitmap.
111 * @wake_batch: Number of bits which must be freed before we wake up any
114 unsigned int wake_batch;
117 * @wake_index: Next wait queue in @ws to wake up.
124 struct sbq_wait_state *ws;
127 * @ws_active: count of currently active ws waitqueues
132 * @min_shallow_depth: The minimum shallow depth which may be passed to
133 * sbitmap_queue_get_shallow()
135 unsigned int min_shallow_depth;
138 * @completion_cnt: Number of bits cleared passed to the
141 atomic_t completion_cnt;
144 * @wakeup_cnt: Number of thread wake ups issued.
150 * sbitmap_init_node() - Initialize a &struct sbitmap on a specific memory node.
151 * @sb: Bitmap to initialize.
152 * @depth: Number of bits to allocate.
153 * @shift: Use 2^@shift bits per word in the bitmap; if a negative number if
154 * given, a good default is chosen.
155 * @flags: Allocation flags.
156 * @node: Memory node to allocate on.
157 * @round_robin: If true, be stricter about allocation order; always allocate
158 * starting from the last allocated bit. This is less efficient
159 * than the default behavior (false).
160 * @alloc_hint: If true, apply percpu hint for where to start searching for
163 * Return: Zero on success or negative errno on failure.
165 int sbitmap_init_node(struct sbitmap *sb, unsigned int depth, int shift,
166 gfp_t flags, int node, bool round_robin, bool alloc_hint);
168 /* sbitmap internal helper */
169 static inline unsigned int __map_depth(const struct sbitmap *sb, int index)
171 if (index == sb->map_nr - 1)
172 return sb->depth - (index << sb->shift);
173 return 1U << sb->shift;
177 * sbitmap_free() - Free memory used by a &struct sbitmap.
178 * @sb: Bitmap to free.
180 static inline void sbitmap_free(struct sbitmap *sb)
182 free_percpu(sb->alloc_hint);
188 * sbitmap_resize() - Resize a &struct sbitmap.
189 * @sb: Bitmap to resize.
190 * @depth: New number of bits to resize to.
192 * Doesn't reallocate anything. It's up to the caller to ensure that the new
193 * depth doesn't exceed the depth that the sb was initialized with.
195 void sbitmap_resize(struct sbitmap *sb, unsigned int depth);
198 * sbitmap_get() - Try to allocate a free bit from a &struct sbitmap.
199 * @sb: Bitmap to allocate from.
201 * This operation provides acquire barrier semantics if it succeeds.
203 * Return: Non-negative allocated bit number if successful, -1 otherwise.
205 int sbitmap_get(struct sbitmap *sb);
208 * sbitmap_get_shallow() - Try to allocate a free bit from a &struct sbitmap,
209 * limiting the depth used from each word.
210 * @sb: Bitmap to allocate from.
211 * @shallow_depth: The maximum number of bits to allocate from a single word.
213 * This rather specific operation allows for having multiple users with
214 * different allocation limits. E.g., there can be a high-priority class that
215 * uses sbitmap_get() and a low-priority class that uses sbitmap_get_shallow()
216 * with a @shallow_depth of (1 << (@sb->shift - 1)). Then, the low-priority
217 * class can only allocate half of the total bits in the bitmap, preventing it
218 * from starving out the high-priority class.
220 * Return: Non-negative allocated bit number if successful, -1 otherwise.
222 int sbitmap_get_shallow(struct sbitmap *sb, unsigned long shallow_depth);
225 * sbitmap_any_bit_set() - Check for a set bit in a &struct sbitmap.
226 * @sb: Bitmap to check.
228 * Return: true if any bit in the bitmap is set, false otherwise.
230 bool sbitmap_any_bit_set(const struct sbitmap *sb);
232 #define SB_NR_TO_INDEX(sb, bitnr) ((bitnr) >> (sb)->shift)
233 #define SB_NR_TO_BIT(sb, bitnr) ((bitnr) & ((1U << (sb)->shift) - 1U))
235 typedef bool (*sb_for_each_fn)(struct sbitmap *, unsigned int, void *);
238 * __sbitmap_for_each_set() - Iterate over each set bit in a &struct sbitmap.
239 * @start: Where to start the iteration.
240 * @sb: Bitmap to iterate over.
241 * @fn: Callback. Should return true to continue or false to break early.
242 * @data: Pointer to pass to callback.
244 * This is inline even though it's non-trivial so that the function calls to the
245 * callback will hopefully get optimized away.
247 static inline void __sbitmap_for_each_set(struct sbitmap *sb,
249 sb_for_each_fn fn, void *data)
253 unsigned int scanned = 0;
255 if (start >= sb->depth)
257 index = SB_NR_TO_INDEX(sb, start);
258 nr = SB_NR_TO_BIT(sb, start);
260 while (scanned < sb->depth) {
262 unsigned int depth = min_t(unsigned int,
263 __map_depth(sb, index) - nr,
264 sb->depth - scanned);
267 word = sb->map[index].word & ~sb->map[index].cleared;
272 * On the first iteration of the outer loop, we need to add the
273 * bit offset back to the size of the word for find_next_bit().
274 * On all other iterations, nr is zero, so this is a noop.
278 nr = find_next_bit(&word, depth, nr);
281 if (!fn(sb, (index << sb->shift) + nr, data))
288 if (++index >= sb->map_nr)
294 * sbitmap_for_each_set() - Iterate over each set bit in a &struct sbitmap.
295 * @sb: Bitmap to iterate over.
296 * @fn: Callback. Should return true to continue or false to break early.
297 * @data: Pointer to pass to callback.
299 static inline void sbitmap_for_each_set(struct sbitmap *sb, sb_for_each_fn fn,
302 __sbitmap_for_each_set(sb, 0, fn, data);
305 static inline unsigned long *__sbitmap_word(struct sbitmap *sb,
308 return &sb->map[SB_NR_TO_INDEX(sb, bitnr)].word;
311 /* Helpers equivalent to the operations in asm/bitops.h and linux/bitmap.h */
313 static inline void sbitmap_set_bit(struct sbitmap *sb, unsigned int bitnr)
315 set_bit(SB_NR_TO_BIT(sb, bitnr), __sbitmap_word(sb, bitnr));
318 static inline void sbitmap_clear_bit(struct sbitmap *sb, unsigned int bitnr)
320 clear_bit(SB_NR_TO_BIT(sb, bitnr), __sbitmap_word(sb, bitnr));
324 * This one is special, since it doesn't actually clear the bit, rather it
325 * sets the corresponding bit in the ->cleared mask instead. Paired with
326 * the caller doing sbitmap_deferred_clear() if a given index is full, which
327 * will clear the previously freed entries in the corresponding ->word.
329 static inline void sbitmap_deferred_clear_bit(struct sbitmap *sb, unsigned int bitnr)
331 unsigned long *addr = &sb->map[SB_NR_TO_INDEX(sb, bitnr)].cleared;
333 set_bit(SB_NR_TO_BIT(sb, bitnr), addr);
337 * Pair of sbitmap_get, and this one applies both cleared bit and
340 static inline void sbitmap_put(struct sbitmap *sb, unsigned int bitnr)
342 sbitmap_deferred_clear_bit(sb, bitnr);
344 if (likely(sb->alloc_hint && !sb->round_robin && bitnr < sb->depth))
345 *raw_cpu_ptr(sb->alloc_hint) = bitnr;
348 static inline int sbitmap_test_bit(struct sbitmap *sb, unsigned int bitnr)
350 return test_bit(SB_NR_TO_BIT(sb, bitnr), __sbitmap_word(sb, bitnr));
353 static inline int sbitmap_calculate_shift(unsigned int depth)
355 int shift = ilog2(BITS_PER_LONG);
358 * If the bitmap is small, shrink the number of bits per word so
359 * we spread over a few cachelines, at least. If less than 4
360 * bits, just forget about it, it's not going to work optimally
364 while ((4U << shift) > depth)
372 * sbitmap_show() - Dump &struct sbitmap information to a &struct seq_file.
373 * @sb: Bitmap to show.
374 * @m: struct seq_file to write to.
376 * This is intended for debugging. The format may change at any time.
378 void sbitmap_show(struct sbitmap *sb, struct seq_file *m);
382 * sbitmap_weight() - Return how many set and not cleared bits in a &struct
384 * @sb: Bitmap to check.
386 * Return: How many set and not cleared bits set
388 unsigned int sbitmap_weight(const struct sbitmap *sb);
391 * sbitmap_bitmap_show() - Write a hex dump of a &struct sbitmap to a &struct
393 * @sb: Bitmap to show.
394 * @m: struct seq_file to write to.
396 * This is intended for debugging. The output isn't guaranteed to be internally
399 void sbitmap_bitmap_show(struct sbitmap *sb, struct seq_file *m);
402 * sbitmap_queue_init_node() - Initialize a &struct sbitmap_queue on a specific
404 * @sbq: Bitmap queue to initialize.
405 * @depth: See sbitmap_init_node().
406 * @shift: See sbitmap_init_node().
407 * @round_robin: See sbitmap_get().
408 * @flags: Allocation flags.
409 * @node: Memory node to allocate on.
411 * Return: Zero on success or negative errno on failure.
413 int sbitmap_queue_init_node(struct sbitmap_queue *sbq, unsigned int depth,
414 int shift, bool round_robin, gfp_t flags, int node);
417 * sbitmap_queue_free() - Free memory used by a &struct sbitmap_queue.
419 * @sbq: Bitmap queue to free.
421 static inline void sbitmap_queue_free(struct sbitmap_queue *sbq)
424 sbitmap_free(&sbq->sb);
428 * sbitmap_queue_recalculate_wake_batch() - Recalculate wake batch
429 * @sbq: Bitmap queue to recalculate wake batch.
430 * @users: Number of shares.
432 * Like sbitmap_queue_update_wake_batch(), this will calculate wake batch
433 * by depth. This interface is for HCTX shared tags or queue shared tags.
435 void sbitmap_queue_recalculate_wake_batch(struct sbitmap_queue *sbq,
439 * sbitmap_queue_resize() - Resize a &struct sbitmap_queue.
440 * @sbq: Bitmap queue to resize.
441 * @depth: New number of bits to resize to.
443 * Like sbitmap_resize(), this doesn't reallocate anything. It has to do
444 * some extra work on the &struct sbitmap_queue, so it's not safe to just
445 * resize the underlying &struct sbitmap.
447 void sbitmap_queue_resize(struct sbitmap_queue *sbq, unsigned int depth);
450 * __sbitmap_queue_get() - Try to allocate a free bit from a &struct
451 * sbitmap_queue with preemption already disabled.
452 * @sbq: Bitmap queue to allocate from.
454 * Return: Non-negative allocated bit number if successful, -1 otherwise.
456 int __sbitmap_queue_get(struct sbitmap_queue *sbq);
459 * __sbitmap_queue_get_batch() - Try to allocate a batch of free bits
460 * @sbq: Bitmap queue to allocate from.
461 * @nr_tags: number of tags requested
462 * @offset: offset to add to returned bits
464 * Return: Mask of allocated tags, 0 if none are found. Each tag allocated is
465 * a bit in the mask returned, and the caller must add @offset to the value to
466 * get the absolute tag value.
468 unsigned long __sbitmap_queue_get_batch(struct sbitmap_queue *sbq, int nr_tags,
469 unsigned int *offset);
472 * sbitmap_queue_get_shallow() - Try to allocate a free bit from a &struct
473 * sbitmap_queue, limiting the depth used from each word, with preemption
475 * @sbq: Bitmap queue to allocate from.
476 * @shallow_depth: The maximum number of bits to allocate from a single word.
477 * See sbitmap_get_shallow().
479 * If you call this, make sure to call sbitmap_queue_min_shallow_depth() after
482 * Return: Non-negative allocated bit number if successful, -1 otherwise.
484 int sbitmap_queue_get_shallow(struct sbitmap_queue *sbq,
485 unsigned int shallow_depth);
488 * sbitmap_queue_get() - Try to allocate a free bit from a &struct
490 * @sbq: Bitmap queue to allocate from.
491 * @cpu: Output parameter; will contain the CPU we ran on (e.g., to be passed to
492 * sbitmap_queue_clear()).
494 * Return: Non-negative allocated bit number if successful, -1 otherwise.
496 static inline int sbitmap_queue_get(struct sbitmap_queue *sbq,
502 nr = __sbitmap_queue_get(sbq);
508 * sbitmap_queue_min_shallow_depth() - Inform a &struct sbitmap_queue of the
509 * minimum shallow depth that will be used.
510 * @sbq: Bitmap queue in question.
511 * @min_shallow_depth: The minimum shallow depth that will be passed to
512 * sbitmap_queue_get_shallow() or __sbitmap_queue_get_shallow().
514 * sbitmap_queue_clear() batches wakeups as an optimization. The batch size
515 * depends on the depth of the bitmap. Since the shallow allocation functions
516 * effectively operate with a different depth, the shallow depth must be taken
517 * into account when calculating the batch size. This function must be called
518 * with the minimum shallow depth that will be used. Failure to do so can result
521 void sbitmap_queue_min_shallow_depth(struct sbitmap_queue *sbq,
522 unsigned int min_shallow_depth);
525 * sbitmap_queue_clear() - Free an allocated bit and wake up waiters on a
526 * &struct sbitmap_queue.
527 * @sbq: Bitmap to free from.
528 * @nr: Bit number to free.
529 * @cpu: CPU the bit was allocated on.
531 void sbitmap_queue_clear(struct sbitmap_queue *sbq, unsigned int nr,
535 * sbitmap_queue_clear_batch() - Free a batch of allocated bits
536 * &struct sbitmap_queue.
537 * @sbq: Bitmap to free from.
538 * @offset: offset for each tag in array
539 * @tags: array of tags
540 * @nr_tags: number of tags in array
542 void sbitmap_queue_clear_batch(struct sbitmap_queue *sbq, int offset,
543 int *tags, int nr_tags);
545 static inline int sbq_index_inc(int index)
547 return (index + 1) & (SBQ_WAIT_QUEUES - 1);
550 static inline void sbq_index_atomic_inc(atomic_t *index)
552 int old = atomic_read(index);
553 int new = sbq_index_inc(old);
554 atomic_cmpxchg(index, old, new);
558 * sbq_wait_ptr() - Get the next wait queue to use for a &struct
560 * @sbq: Bitmap queue to wait on.
561 * @wait_index: A counter per "user" of @sbq.
563 static inline struct sbq_wait_state *sbq_wait_ptr(struct sbitmap_queue *sbq,
564 atomic_t *wait_index)
566 struct sbq_wait_state *ws;
568 ws = &sbq->ws[atomic_read(wait_index)];
569 sbq_index_atomic_inc(wait_index);
574 * sbitmap_queue_wake_all() - Wake up everything waiting on a &struct
576 * @sbq: Bitmap queue to wake up.
578 void sbitmap_queue_wake_all(struct sbitmap_queue *sbq);
581 * sbitmap_queue_wake_up() - Wake up some of waiters in one waitqueue
582 * on a &struct sbitmap_queue.
583 * @sbq: Bitmap queue to wake up.
584 * @nr: Number of bits cleared.
586 void sbitmap_queue_wake_up(struct sbitmap_queue *sbq, int nr);
589 * sbitmap_queue_show() - Dump &struct sbitmap_queue information to a &struct
591 * @sbq: Bitmap queue to show.
592 * @m: struct seq_file to write to.
594 * This is intended for debugging. The format may change at any time.
596 void sbitmap_queue_show(struct sbitmap_queue *sbq, struct seq_file *m);
599 struct sbitmap_queue *sbq; /* if set, sbq_wait is accounted */
600 struct wait_queue_entry wait;
603 #define DEFINE_SBQ_WAIT(name) \
604 struct sbq_wait name = { \
607 .private = current, \
608 .func = autoremove_wake_function, \
609 .entry = LIST_HEAD_INIT((name).wait.entry), \
614 * Wrapper around prepare_to_wait_exclusive(), which maintains some extra
617 void sbitmap_prepare_to_wait(struct sbitmap_queue *sbq,
618 struct sbq_wait_state *ws,
619 struct sbq_wait *sbq_wait, int state);
622 * Must be paired with sbitmap_prepare_to_wait().
624 void sbitmap_finish_wait(struct sbitmap_queue *sbq, struct sbq_wait_state *ws,
625 struct sbq_wait *sbq_wait);
628 * Wrapper around add_wait_queue(), which maintains some extra internal state
630 void sbitmap_add_wait_queue(struct sbitmap_queue *sbq,
631 struct sbq_wait_state *ws,
632 struct sbq_wait *sbq_wait);
635 * Must be paired with sbitmap_add_wait_queue()
637 void sbitmap_del_wait_queue(struct sbq_wait *sbq_wait);
639 #endif /* __LINUX_SCALE_BITMAP_H */