bitset(9): Introduce BIT_FOREACH_ISSET and BIT_FOREACH_ISCLR

These allow one to non-destructively iterate over the set or clear bits
in a bitset.  The motivation is that we have several code fragments
which iterate over a CPU set like this:

while ((cpu = CPU_FFS(&cpus)) != 0) {
	cpu--;
	CPU_CLR(cpu, &cpus);
	<do something>;
}

This is slow since CPU_FFS begins the search at the beginning of the
bitset each time.  On amd64 and arm64, CPU sets have size 256, so there
are four limbs in the bitset and we do a lot of unnecessary scanning.

A second problem is that this is destructive, so code which needs to
preserve the original set has to make a copy.  In particular, we have
quite a few functions which take a cpuset_t parameter by value, meaning
that each call has to copy the 32 byte cpuset_t.

The new macros address both problems.

Reviewed by:	cem, kib
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D32028
This commit is contained in:
Mark Johnston 2021-09-21 11:32:23 -04:00 committed by Sebastian Huber
parent 7c03cdf47e
commit 37a3e59636
1 changed files with 10 additions and 0 deletions

View File

@ -274,6 +274,16 @@
__count; \
})
/* Non-destructively loop over all set or clear bits in the set. */
#define _BIT_FOREACH(_s, i, p, op) \
for (__size_t __i = 0; __i < __bitset_words(_s); __i++) \
for (long __j = op((p)->__bits[__i]), __b = ffsl(__j); \
(i = (__b - 1) + __i * _BITSET_BITS), __j != 0; \
__j &= ~(1l << i), __b = ffsl(__j))
#define BIT_FOREACH_ISSET(_s, i, p) _BIT_FOREACH(_s, i, p, )
#define BIT_FOREACH_ISCLR(_s, i, p) _BIT_FOREACH(_s, i, p, ~)
#define BITSET_T_INITIALIZER(x) \
{ .__bits = { x } }