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
;
41 * @swap_lock: serializes simultaneous updates of ->word and ->cleared
43 raw_spinlock_t swap_lock
;
44 } ____cacheline_aligned_in_smp
;
47 * struct sbitmap - Scalable bitmap.
49 * A &struct sbitmap is spread over multiple cachelines to avoid ping-pong. This
50 * trades off higher memory usage for better scalability.
54 * @depth: Number of bits used in the whole bitmap.
59 * @shift: log2(number of bits used per word)
64 * @map_nr: Number of words (cachelines) being used for the bitmap.
69 * @round_robin: Allocate bits in strict round-robin order.
74 * @map: Allocated bitmap.
76 struct sbitmap_word
*map
;
79 * @alloc_hint: Cache of last successfully allocated or freed bit.
81 * This is per-cpu, which allows multiple users to stick to different
82 * cachelines until the map is exhausted.
84 unsigned int __percpu
*alloc_hint
;
87 #define SBQ_WAIT_QUEUES 8
88 #define SBQ_WAKE_BATCH 8
91 * struct sbq_wait_state - Wait queue in a &struct sbitmap_queue.
93 struct sbq_wait_state
{
97 wait_queue_head_t wait
;
98 } ____cacheline_aligned_in_smp
;
101 * struct sbitmap_queue - Scalable bitmap with the added ability to wait on free
104 * A &struct sbitmap_queue uses multiple wait queues and rolling wakeups to
105 * avoid contention on the wait queue spinlock. This ensures that we don't hit a
106 * scalability wall when we run out of free bits and have to start putting tasks
109 struct sbitmap_queue
{
111 * @sb: Scalable bitmap.
116 * @wake_batch: Number of bits which must be freed before we wake up any
119 unsigned int wake_batch
;
122 * @wake_index: Next wait queue in @ws to wake up.
129 struct sbq_wait_state
*ws
;
132 * @ws_active: count of currently active ws waitqueues
137 * @min_shallow_depth: The minimum shallow depth which may be passed to
138 * sbitmap_queue_get_shallow()
140 unsigned int min_shallow_depth
;
143 * @completion_cnt: Number of bits cleared passed to the
146 atomic_t completion_cnt
;
149 * @wakeup_cnt: Number of thread wake ups issued.
155 * sbitmap_init_node() - Initialize a &struct sbitmap on a specific memory node.
156 * @sb: Bitmap to initialize.
157 * @depth: Number of bits to allocate.
158 * @shift: Use 2^@shift bits per word in the bitmap; if a negative number if
159 * given, a good default is chosen.
160 * @flags: Allocation flags.
161 * @node: Memory node to allocate on.
162 * @round_robin: If true, be stricter about allocation order; always allocate
163 * starting from the last allocated bit. This is less efficient
164 * than the default behavior (false).
165 * @alloc_hint: If true, apply percpu hint for where to start searching for
168 * Return: Zero on success or negative errno on failure.
170 int sbitmap_init_node(struct sbitmap
*sb
, unsigned int depth
, int shift
,
171 gfp_t flags
, int node
, bool round_robin
, bool alloc_hint
);
173 /* sbitmap internal helper */
174 static inline unsigned int __map_depth(const struct sbitmap
*sb
, int index
)
176 if (index
== sb
->map_nr
- 1)
177 return sb
->depth
- (index
<< sb
->shift
);
178 return 1U << sb
->shift
;
182 * sbitmap_free() - Free memory used by a &struct sbitmap.
183 * @sb: Bitmap to free.
185 static inline void sbitmap_free(struct sbitmap
*sb
)
187 free_percpu(sb
->alloc_hint
);
193 * sbitmap_resize() - Resize a &struct sbitmap.
194 * @sb: Bitmap to resize.
195 * @depth: New number of bits to resize to.
197 * Doesn't reallocate anything. It's up to the caller to ensure that the new
198 * depth doesn't exceed the depth that the sb was initialized with.
200 void sbitmap_resize(struct sbitmap
*sb
, unsigned int depth
);
203 * sbitmap_get() - Try to allocate a free bit from a &struct sbitmap.
204 * @sb: Bitmap to allocate from.
206 * This operation provides acquire barrier semantics if it succeeds.
208 * Return: Non-negative allocated bit number if successful, -1 otherwise.
210 int sbitmap_get(struct sbitmap
*sb
);
213 * sbitmap_get_shallow() - Try to allocate a free bit from a &struct sbitmap,
214 * limiting the depth used from each word.
215 * @sb: Bitmap to allocate from.
216 * @shallow_depth: The maximum number of bits to allocate from a single word.
218 * This rather specific operation allows for having multiple users with
219 * different allocation limits. E.g., there can be a high-priority class that
220 * uses sbitmap_get() and a low-priority class that uses sbitmap_get_shallow()
221 * with a @shallow_depth of (1 << (@sb->shift - 1)). Then, the low-priority
222 * class can only allocate half of the total bits in the bitmap, preventing it
223 * from starving out the high-priority class.
225 * Return: Non-negative allocated bit number if successful, -1 otherwise.
227 int sbitmap_get_shallow(struct sbitmap
*sb
, unsigned long shallow_depth
);
230 * sbitmap_any_bit_set() - Check for a set bit in a &struct sbitmap.
231 * @sb: Bitmap to check.
233 * Return: true if any bit in the bitmap is set, false otherwise.
235 bool sbitmap_any_bit_set(const struct sbitmap
*sb
);
237 #define SB_NR_TO_INDEX(sb, bitnr) ((bitnr) >> (sb)->shift)
238 #define SB_NR_TO_BIT(sb, bitnr) ((bitnr) & ((1U << (sb)->shift) - 1U))
240 typedef bool (*sb_for_each_fn
)(struct sbitmap
*, unsigned int, void *);
243 * __sbitmap_for_each_set() - Iterate over each set bit in a &struct sbitmap.
244 * @start: Where to start the iteration.
245 * @sb: Bitmap to iterate over.
246 * @fn: Callback. Should return true to continue or false to break early.
247 * @data: Pointer to pass to callback.
249 * This is inline even though it's non-trivial so that the function calls to the
250 * callback will hopefully get optimized away.
252 static inline void __sbitmap_for_each_set(struct sbitmap
*sb
,
254 sb_for_each_fn fn
, void *data
)
258 unsigned int scanned
= 0;
260 if (start
>= sb
->depth
)
262 index
= SB_NR_TO_INDEX(sb
, start
);
263 nr
= SB_NR_TO_BIT(sb
, start
);
265 while (scanned
< sb
->depth
) {
267 unsigned int depth
= min_t(unsigned int,
268 __map_depth(sb
, index
) - nr
,
269 sb
->depth
- scanned
);
272 word
= sb
->map
[index
].word
& ~sb
->map
[index
].cleared
;
277 * On the first iteration of the outer loop, we need to add the
278 * bit offset back to the size of the word for find_next_bit().
279 * On all other iterations, nr is zero, so this is a noop.
283 nr
= find_next_bit(&word
, depth
, nr
);
286 if (!fn(sb
, (index
<< sb
->shift
) + nr
, data
))
293 if (++index
>= sb
->map_nr
)
299 * sbitmap_for_each_set() - Iterate over each set bit in a &struct sbitmap.
300 * @sb: Bitmap to iterate over.
301 * @fn: Callback. Should return true to continue or false to break early.
302 * @data: Pointer to pass to callback.
304 static inline void sbitmap_for_each_set(struct sbitmap
*sb
, sb_for_each_fn fn
,
307 __sbitmap_for_each_set(sb
, 0, fn
, data
);
310 static inline unsigned long *__sbitmap_word(struct sbitmap
*sb
,
313 return &sb
->map
[SB_NR_TO_INDEX(sb
, bitnr
)].word
;
316 /* Helpers equivalent to the operations in asm/bitops.h and linux/bitmap.h */
318 static inline void sbitmap_set_bit(struct sbitmap
*sb
, unsigned int bitnr
)
320 set_bit(SB_NR_TO_BIT(sb
, bitnr
), __sbitmap_word(sb
, bitnr
));
323 static inline void sbitmap_clear_bit(struct sbitmap
*sb
, unsigned int bitnr
)
325 clear_bit(SB_NR_TO_BIT(sb
, bitnr
), __sbitmap_word(sb
, bitnr
));
329 * This one is special, since it doesn't actually clear the bit, rather it
330 * sets the corresponding bit in the ->cleared mask instead. Paired with
331 * the caller doing sbitmap_deferred_clear() if a given index is full, which
332 * will clear the previously freed entries in the corresponding ->word.
334 static inline void sbitmap_deferred_clear_bit(struct sbitmap
*sb
, unsigned int bitnr
)
336 unsigned long *addr
= &sb
->map
[SB_NR_TO_INDEX(sb
, bitnr
)].cleared
;
338 set_bit(SB_NR_TO_BIT(sb
, bitnr
), addr
);
342 * Pair of sbitmap_get, and this one applies both cleared bit and
345 static inline void sbitmap_put(struct sbitmap
*sb
, unsigned int bitnr
)
347 sbitmap_deferred_clear_bit(sb
, bitnr
);
349 if (likely(sb
->alloc_hint
&& !sb
->round_robin
&& bitnr
< sb
->depth
))
350 *raw_cpu_ptr(sb
->alloc_hint
) = bitnr
;
353 static inline int sbitmap_test_bit(struct sbitmap
*sb
, unsigned int bitnr
)
355 return test_bit(SB_NR_TO_BIT(sb
, bitnr
), __sbitmap_word(sb
, bitnr
));
358 static inline int sbitmap_calculate_shift(unsigned int depth
)
360 int shift
= ilog2(BITS_PER_LONG
);
363 * If the bitmap is small, shrink the number of bits per word so
364 * we spread over a few cachelines, at least. If less than 4
365 * bits, just forget about it, it's not going to work optimally
369 while ((4U << shift
) > depth
)
377 * sbitmap_show() - Dump &struct sbitmap information to a &struct seq_file.
378 * @sb: Bitmap to show.
379 * @m: struct seq_file to write to.
381 * This is intended for debugging. The format may change at any time.
383 void sbitmap_show(struct sbitmap
*sb
, struct seq_file
*m
);
387 * sbitmap_weight() - Return how many set and not cleared bits in a &struct
389 * @sb: Bitmap to check.
391 * Return: How many set and not cleared bits set
393 unsigned int sbitmap_weight(const struct sbitmap
*sb
);
396 * sbitmap_bitmap_show() - Write a hex dump of a &struct sbitmap to a &struct
398 * @sb: Bitmap to show.
399 * @m: struct seq_file to write to.
401 * This is intended for debugging. The output isn't guaranteed to be internally
404 void sbitmap_bitmap_show(struct sbitmap
*sb
, struct seq_file
*m
);
407 * sbitmap_queue_init_node() - Initialize a &struct sbitmap_queue on a specific
409 * @sbq: Bitmap queue to initialize.
410 * @depth: See sbitmap_init_node().
411 * @shift: See sbitmap_init_node().
412 * @round_robin: See sbitmap_get().
413 * @flags: Allocation flags.
414 * @node: Memory node to allocate on.
416 * Return: Zero on success or negative errno on failure.
418 int sbitmap_queue_init_node(struct sbitmap_queue
*sbq
, unsigned int depth
,
419 int shift
, bool round_robin
, gfp_t flags
, int node
);
422 * sbitmap_queue_free() - Free memory used by a &struct sbitmap_queue.
424 * @sbq: Bitmap queue to free.
426 static inline void sbitmap_queue_free(struct sbitmap_queue
*sbq
)
429 sbitmap_free(&sbq
->sb
);
433 * sbitmap_queue_recalculate_wake_batch() - Recalculate wake batch
434 * @sbq: Bitmap queue to recalculate wake batch.
435 * @users: Number of shares.
437 * Like sbitmap_queue_update_wake_batch(), this will calculate wake batch
438 * by depth. This interface is for HCTX shared tags or queue shared tags.
440 void sbitmap_queue_recalculate_wake_batch(struct sbitmap_queue
*sbq
,
444 * sbitmap_queue_resize() - Resize a &struct sbitmap_queue.
445 * @sbq: Bitmap queue to resize.
446 * @depth: New number of bits to resize to.
448 * Like sbitmap_resize(), this doesn't reallocate anything. It has to do
449 * some extra work on the &struct sbitmap_queue, so it's not safe to just
450 * resize the underlying &struct sbitmap.
452 void sbitmap_queue_resize(struct sbitmap_queue
*sbq
, unsigned int depth
);
455 * __sbitmap_queue_get() - Try to allocate a free bit from a &struct
456 * sbitmap_queue with preemption already disabled.
457 * @sbq: Bitmap queue to allocate from.
459 * Return: Non-negative allocated bit number if successful, -1 otherwise.
461 int __sbitmap_queue_get(struct sbitmap_queue
*sbq
);
464 * __sbitmap_queue_get_batch() - Try to allocate a batch of free bits
465 * @sbq: Bitmap queue to allocate from.
466 * @nr_tags: number of tags requested
467 * @offset: offset to add to returned bits
469 * Return: Mask of allocated tags, 0 if none are found. Each tag allocated is
470 * a bit in the mask returned, and the caller must add @offset to the value to
471 * get the absolute tag value.
473 unsigned long __sbitmap_queue_get_batch(struct sbitmap_queue
*sbq
, int nr_tags
,
474 unsigned int *offset
);
477 * sbitmap_queue_get_shallow() - Try to allocate a free bit from a &struct
478 * sbitmap_queue, limiting the depth used from each word, with preemption
480 * @sbq: Bitmap queue to allocate from.
481 * @shallow_depth: The maximum number of bits to allocate from a single word.
482 * See sbitmap_get_shallow().
484 * If you call this, make sure to call sbitmap_queue_min_shallow_depth() after
487 * Return: Non-negative allocated bit number if successful, -1 otherwise.
489 int sbitmap_queue_get_shallow(struct sbitmap_queue
*sbq
,
490 unsigned int shallow_depth
);
493 * sbitmap_queue_get() - Try to allocate a free bit from a &struct
495 * @sbq: Bitmap queue to allocate from.
496 * @cpu: Output parameter; will contain the CPU we ran on (e.g., to be passed to
497 * sbitmap_queue_clear()).
499 * Return: Non-negative allocated bit number if successful, -1 otherwise.
501 static inline int sbitmap_queue_get(struct sbitmap_queue
*sbq
,
507 nr
= __sbitmap_queue_get(sbq
);
513 * sbitmap_queue_min_shallow_depth() - Inform a &struct sbitmap_queue of the
514 * minimum shallow depth that will be used.
515 * @sbq: Bitmap queue in question.
516 * @min_shallow_depth: The minimum shallow depth that will be passed to
517 * sbitmap_queue_get_shallow() or __sbitmap_queue_get_shallow().
519 * sbitmap_queue_clear() batches wakeups as an optimization. The batch size
520 * depends on the depth of the bitmap. Since the shallow allocation functions
521 * effectively operate with a different depth, the shallow depth must be taken
522 * into account when calculating the batch size. This function must be called
523 * with the minimum shallow depth that will be used. Failure to do so can result
526 void sbitmap_queue_min_shallow_depth(struct sbitmap_queue
*sbq
,
527 unsigned int min_shallow_depth
);
530 * sbitmap_queue_clear() - Free an allocated bit and wake up waiters on a
531 * &struct sbitmap_queue.
532 * @sbq: Bitmap to free from.
533 * @nr: Bit number to free.
534 * @cpu: CPU the bit was allocated on.
536 void sbitmap_queue_clear(struct sbitmap_queue
*sbq
, unsigned int nr
,
540 * sbitmap_queue_clear_batch() - Free a batch of allocated bits
541 * &struct sbitmap_queue.
542 * @sbq: Bitmap to free from.
543 * @offset: offset for each tag in array
544 * @tags: array of tags
545 * @nr_tags: number of tags in array
547 void sbitmap_queue_clear_batch(struct sbitmap_queue
*sbq
, int offset
,
548 int *tags
, int nr_tags
);
550 static inline int sbq_index_inc(int index
)
552 return (index
+ 1) & (SBQ_WAIT_QUEUES
- 1);
555 static inline void sbq_index_atomic_inc(atomic_t
*index
)
557 int old
= atomic_read(index
);
558 int new = sbq_index_inc(old
);
559 atomic_cmpxchg(index
, old
, new);
563 * sbq_wait_ptr() - Get the next wait queue to use for a &struct
565 * @sbq: Bitmap queue to wait on.
566 * @wait_index: A counter per "user" of @sbq.
568 static inline struct sbq_wait_state
*sbq_wait_ptr(struct sbitmap_queue
*sbq
,
569 atomic_t
*wait_index
)
571 struct sbq_wait_state
*ws
;
573 ws
= &sbq
->ws
[atomic_read(wait_index
)];
574 sbq_index_atomic_inc(wait_index
);
579 * sbitmap_queue_wake_all() - Wake up everything waiting on a &struct
581 * @sbq: Bitmap queue to wake up.
583 void sbitmap_queue_wake_all(struct sbitmap_queue
*sbq
);
586 * sbitmap_queue_wake_up() - Wake up some of waiters in one waitqueue
587 * on a &struct sbitmap_queue.
588 * @sbq: Bitmap queue to wake up.
589 * @nr: Number of bits cleared.
591 void sbitmap_queue_wake_up(struct sbitmap_queue
*sbq
, int nr
);
594 * sbitmap_queue_show() - Dump &struct sbitmap_queue information to a &struct
596 * @sbq: Bitmap queue to show.
597 * @m: struct seq_file to write to.
599 * This is intended for debugging. The format may change at any time.
601 void sbitmap_queue_show(struct sbitmap_queue
*sbq
, struct seq_file
*m
);
604 struct sbitmap_queue
*sbq
; /* if set, sbq_wait is accounted */
605 struct wait_queue_entry wait
;
608 #define DEFINE_SBQ_WAIT(name) \
609 struct sbq_wait name = { \
612 .private = current, \
613 .func = autoremove_wake_function, \
614 .entry = LIST_HEAD_INIT((name).wait.entry), \
619 * Wrapper around prepare_to_wait_exclusive(), which maintains some extra
622 void sbitmap_prepare_to_wait(struct sbitmap_queue
*sbq
,
623 struct sbq_wait_state
*ws
,
624 struct sbq_wait
*sbq_wait
, int state
);
627 * Must be paired with sbitmap_prepare_to_wait().
629 void sbitmap_finish_wait(struct sbitmap_queue
*sbq
, struct sbq_wait_state
*ws
,
630 struct sbq_wait
*sbq_wait
);
633 * Wrapper around add_wait_queue(), which maintains some extra internal state
635 void sbitmap_add_wait_queue(struct sbitmap_queue
*sbq
,
636 struct sbq_wait_state
*ws
,
637 struct sbq_wait
*sbq_wait
);
640 * Must be paired with sbitmap_add_wait_queue()
642 void sbitmap_del_wait_queue(struct sbq_wait
*sbq_wait
);
644 #endif /* __LINUX_SCALE_BITMAP_H */