Linux Bit Operations: __ffs and __fls on 0x1c0000000, the highest set bit 32 and the lowest set bit 30

Linux Bit Operations: __ffs, __fls and Alignment

Share this post on:

While upstreaming PCIe host support for the RZ/G3E SoC on behalf of Renesas, merged in Linux 7.1, we had to rework the algorithm that programs the inbound DMA windows of the controller. The existing code did not fully respect the alignment constraints of the hardware, and the fix uses two Linux kernel helpers, __ffs() and __fls().

__ffs() returns the position of the lowest set bit of a value and __fls() that of the highest. For an address, 1 << __ffs() is its alignment, and in an interrupt status bitmap, __ffs() is the number of the next pending interrupt. For a size, __fls() is its base-2 logarithm and 1 << __fls() the largest power of two it contains, on which allocation orders are built.

Starting from powers of two, masks and alignment, the binary rules behind these operations, this article shows how the kernel uses them in bitmap walks, logarithms and page orders, then how the RZ/G3E driver uses them to split a DMA range into aligned windows. The article on the Linux bitfield macros covers the register fields of the same driver.

Contents
  1. Bits and Powers of Two
  2. Alignment in Binary
  3. Finding Bits with __ffs and __fls
  4. Where the Kernel Uses Them
  5. Example: Splitting a PCIe DMA Range
  6. Summing Up

Bits and Powers of Two

Bit k of a value is worth 2k when it is set, and the value is the sum of its set bits. A value with a single bit set is therefore a power of two, and the position of that bit is the exponent. The addresses and sizes of this article read easily in that form. 0x40000000 is bit 30 alone, 230 or 1 GiB. 0x100000000 is bit 32, 4 GiB, and 0x200000000 is bit 33, 8 GiB. A 6 GiB range, 0x180000000, has two bits set, 32 and 31, so it is not a power of two.

A left shift by n multiplies by 2n and a right shift of an unsigned value divides by 2n, so 1 << n is 2n and x & (2^n - 1), the n low bits, is the remainder of that division. A plain 1 in C is a 32-bit int, though.

1 << 31 moves it into the sign bit, which C11 leaves undefined and UBSAN reports as “left shift of 1 by 31 places cannot be represented in type ‘int'”. 1 << 33 shifts past the width of the type. GCC 15 warns “left shift count >= width of type”, and a test program on x86-64 printed 0. 1ULL << 33 is computed on 64 bits and gives 0x200000000, 8 GiB, which is why the driver writes 1ULL.

Subtracting 1 from a value borrows from its lowest set bit. That bit becomes 0 and every bit below it becomes 1, while the bits above it do not change. For a power of two, the result is N ones from bit 0, so 2N − 1 is the mask of the N low bits:

Binary subtraction 0x40000000 - 1 = 0x3fffffff: bit 30 cleared, bits 29 to 0 set by the borrow
Figure 1. 0x40000000 minus 1, bit by bit.

The same borrow gives a test for powers of two. x & (x - 1) clears the lowest set bit of x, so it is zero only when x had a single bit set. For 8 GiB, 0x200000000 & 0x1ffffffff is 0. For 6 GiB, 0x180000000 & 0x17fffffff is 0x100000000, bit 32 still set. is_power_of_2() of <linux/log2.h> wraps this test and returns false for 0.

Alignment in Binary

An address is aligned to 2N when it is a multiple of 2N, which in binary means that its N low bits are zero. x & (2^N - 1) keeps those N bits, so x is aligned when the result is zero. IS_ALIGNED(x, a) of <linux/align.h> does exactly that for a power of two a. 0x40000000 has its 30 low bits clear and bit 30 set, so it is aligned to 1 GiB and to every smaller power of two, but not to 2 GiB. 0x100000000 has 32 low bits clear and is aligned to 4 GiB.

ALIGN(x, a) rounds x up to the next multiple of a, as (x + a - 1) & ~(a - 1). Adding a − 1 pushes any value that is not aligned past the next boundary, and the AND with the inverted mask clears the low bits. ALIGN(0x40000001, SZ_4K) is 0x40001000. ALIGN_DOWN() only clears the low bits and rounds down. The largest power of two an address is aligned to is its lowest set bit, 230 for 0x40000000, which is what __ffs() finds below.

Finding Bits with __ffs and __fls

<linux/bitops.h> provides both. __ffs(x), find first set, returns the index of the least significant set bit of x, and __fls(x), find last set, the index of the most significant one, both counting from 0:

__ffs(0x105)       = 0    bits 8, 2 and 0 are set, bit 0 is the lowest
__fls(0x105)       = 8    and bit 8 the highest
__ffs(0x40000000)  = 30   0x40000000 is aligned to 1 GiB, not more
__ffs(0x100000000) = 32   0x100000000 is aligned to 4 GiB
__fls(0x200000000) = 33   1ULL << 33 = 8 GiB
__fls(0x1c0000000) = 32   the largest power of two in 7 GiB is 4 GiB

On 0x1c0000000, 7 GiB, with bits 32, 31 and 30 set, the two answers differ. The highest set bit gives the largest power of two the value contains, and the lowest set bit the largest power of two it is a multiple of.

Bits of 0x1c0000000: __fls gives bit 32, 4 GiB, the largest power of two; __ffs gives bit 30, 1 GiB alignment
Figure 2. __fls() and __ffs() on 0x1c0000000, 7 GiB.

1ULL << __fls(x) is what rounddown_pow_of_two() returns, and __fls() equals ilog2() for a non-zero value. Both helpers are undefined for 0, which has no set bit. The generic versions are __builtin_ctzl() and __builtin_clzl() of the compiler. On arm64, GCC turns __ffs() into rbit and clz and __fls() into clz and a subtraction. ffs() and fls(), without underscores, count from 1 and return 0 for 0, which is why drivers write ffs(mask) - 1 to get a shift.

The double-underscore helpers take an unsigned long. That is 64 bits on arm64, so arm64 code can pass u64 addresses directly. A driver built for 32-bit CPUs must use __ffs64() and fls64(), otherwise bits 63:32 are lost and __ffs((unsigned long)0x100000000) becomes __ffs(0). There is no __fls64(), and fls64(x) - 1 gives the same index.

Where the Kernel Uses Them

Most drivers call __ffs() and __fls() through other helpers. The RZ/G3E PCIe driver shows two of them in its MSI support. The controller receives up to 32 MSIs and reports the pending ones in a status register, which the interrupt handler copies into a bitmap and walks with for_each_set_bit():

	for_each_set_bit(bit, bitmap, RZG3S_PCI_MSI_INT_NR) {
		int ret;

		ret = generic_handle_domain_irq(msi->domain, bit);
		[...]
	}

for_each_set_bit() calls find_next_bit() for each step, and for a bitmap that fits in one word, find_next_bit() in <linux/find.h> masks off the bits already visited and returns __ffs() of what is left. With MSIs 8, 2 and 0 pending, a status of 0x105, the loop handles 0, then 2, then 8, one __ffs() per pending interrupt instead of a test of all 32 bits.

When a device asks for several MSIs, the driver reserves them in a bitmap of free vectors:

		hwirq = bitmap_find_free_region(msi->map, RZG3S_PCI_MSI_INT_NR,
						order_base_2(nr_irqs));

bitmap_find_free_region() only considers regions whose length is a power of two, aligned to that power of two, and takes the power as an order, its base-2 logarithm. order_base_2(n) is the order of the smallest power of two that holds n, ilog2(n - 1) + 1, and ilog2() is fls() - 1, or fls64() - 1 for a 64-bit value, in <linux/log2.h>. order_base_2(3) and order_base_2(4) are both 2, so a request for 3 or 4 vectors reserves a block of 4 that starts at a multiple of 4.

Page allocations follow the same pattern. get_order(size) in <asm-generic/getorder.h> returns the order of the number of pages a buffer needs, computed with fls64() on (size - 1) >> PAGE_SHIFT. With 4 KiB pages, get_order(4096) is 0, get_order(5000) is 1, two pages, and get_order(SZ_1M) is 8. The field_prep() helper of the bitfield macros article uses __ffs() too, to find the shift of a field from its mask.

Example: Splitting a PCIe DMA Range

The inbound windows of the RZ/G3E PCIe controller need __ffs() and __fls() directly, together with the power-of-two and alignment rules above, because the hardware puts a constraint on each window that the old code of the driver did not respect.

Inbound Windows and dma-ranges

When a PCIe device reads or writes memory by DMA, it sends a PCI bus address over the link. The root complex, the PCIe controller of the SoC at the top of the PCIe hierarchy, translates it into a CPU address through inbound windows, which the RZ/G3S and RZ/G3E manuals call AXI windows. The controller has eight of them.

Each window is three pairs of 32-bit registers. AXI Window Base (AWBASE) holds the PCI address where the window starts, with bit 0 as the enable bit; AXI Window Mask (AWMASK) holds the size of the window minus one; AXI Destination (ADEST) holds the CPU address the window maps to. The driver writes them in one function:

static void rzg3s_pcie_set_inbound_window(struct rzg3s_pcie_host *host,
					  u64 cpu_addr, u64 pci_addr, u64 size,
					  int id)
{
	/* Set CPU window base address */
	writel_relaxed(upper_32_bits(cpu_addr),
		       host->axi + RZG3S_PCI_ADESTU(id));
	writel_relaxed(lower_32_bits(cpu_addr),
		       host->axi + RZG3S_PCI_ADESTL(id));

	/* Set window size */
	writel_relaxed(upper_32_bits(size), host->axi + RZG3S_PCI_AWMASKU(id));
	writel_relaxed(lower_32_bits(size), host->axi + RZG3S_PCI_AWMASKL(id));

	/* Set PCIe window base address and enable the window */
	writel_relaxed(upper_32_bits(pci_addr),
		       host->axi + RZG3S_PCI_AWBASEU(id));
	writel_relaxed(lower_32_bits(pci_addr) | RZG3S_PCI_AWBASEL_WIN_ENA,
		       host->axi + RZG3S_PCI_AWBASEL(id));
}

Despite its name, the size argument is the mask, the caller passes the size minus one. The windows to program come from the dma-ranges property of the PCIe node, in r9a09g047.dtsi for the RZ/G3E:

dma-ranges = <0x43000000 0 0x40000000 0 0x40000000 2 0x00000000>;

The first cell describes the PCI address space. In 0x43000000, bit 30 marks prefetchable memory and the value 11 in bits 25:24 means 64-bit memory. Linux 7.1 shipped 0x42000000, the code of 32-bit memory, for a range that goes beyond 4 GiB, and Lad Prabhakar corrected it for Linux 7.3. The window computation below does not depend on this cell.

Then come the PCI address 0x40000000 and the CPU address 0x40000000, two cells each, and the size, two cells, 0x2_0000_0000 or 8 GiB. PCI addresses equal CPU addresses, and the range runs from 0x40000000 to 0x23fffffff. The RZ/G3S device tree maps 4 GiB from the same address. The PCI core turns each entry into a resource in bridge->dma_ranges, and at probe time the driver hands each one to rzg3s_pcie_set_inbound_windows(), which splits it into windows.

A PCIe DMA address matched by AWBASE and AWMASK and translated to the CPU address in ADEST
Figure 3. Inbound window 2 of the RZ/G3E, with the values the new loop writes.

Window Masks and the No-Carry Rule

An inbound window has one mask register and no end address, so its size must be a power of two, 2N bytes, and the mask is 2N − 1. A 4 KiB window has the mask 0xfff, a 1 GiB window 0x3fffffff, an 8 GiB window 0x1ffffffff. The manuals set the minimum size to 4 KiB, which keeps bits 11:0 of the base free, and the driver uses bit 0 of AWBASEL as the enable bit.

A base and a power-of-two mask are cheap to decode. An address belongs to the window when its bits above the mask equal those of the base, (addr & ~mask) == base, one AND and one comparison per window, with no end address to compute and compare. A window of any size would need two comparisons, against its start and its end.

Window 2 test: 0x123456789 AND ~mask gives 0x100000000, equal to the base; 0x80001000 gives 0, outside
Figure 4. The test (addr & ~mask) == base on window 2.

The window starts at the base and ends at base + mask. When the base is a multiple of the window size, its N low bits are zero, the addition never carries, and base + mask equals base | mask, the base with its N low bits set. A base aligned to the size of its window is said to be naturally aligned.

The RZ/G3S manual (Rev.1.10, section 34.6.6.7) and the RZ/G3E manual (Rev.1.15, section 6.6.7.6) state that no bit carry, a 1 pushed into a higher bit by the addition, may occur when the AXI Window Base and AXI Window Mask registers are added. A carry happens when the base has a bit set that the mask also covers, that is when base & mask is not zero. The rule therefore requires a naturally aligned base, and it applies to the PCI address in AWBASE. The reworked driver aligns the CPU address in ADEST to the window size as well.

An 8 GiB window at 0x40000000 breaks the rule. Bit 30 of the base is set and the mask 0x1ffffffff covers bits 32:0, so the sum carries into bit 33 and ends the window at 0x23fffffff. The bits of the base above the mask, base & ~mask, are all zero and describe a window from 0 to 0x1ffffffff instead, so the two readings of the same registers disagree. A 4 GiB window at 0x100000000 respects the rule, since bits 31:0 of the base are zero, and the sum equals the OR.

Binary addition of base and mask: carry for 0x40000000 + 0x1ffffffff, none for 0x100000000 + 0xffffffff
Figure 5. Base plus mask for the 8 GiB window at 0x40000000 and the 4 GiB window at 0x100000000.

What the RZ/G3S Loop Programmed

The loop of the RZ/G3S driver, before the series, took the size of the whole resource, rounded it up and aligned the addresses to 4 KiB:

	while (cpu_addr < cpu_end) {
		[...]
		size = resource_size(entry->res) - size_id;
		size = max(size, SZ_4K);
		size = ALIGN(size, SZ_4K);
		size = roundup_pow_of_two(size);

		cpu_addr = ALIGN(cpu_addr, SZ_4K);
		pci_addr = ALIGN(pci_addr, SZ_4K);

		rzg3s_pcie_set_inbound_window(host, cpu_addr, pci_addr,
					      size - 1, id);

		pci_addr += size;
		cpu_addr += size;
		size_id = size;
		id++;
	}

roundup_pow_of_two() returns the smallest power of two greater than or equal to its argument. The loop body, compiled on a PC with the two device tree ranges and with a 6 GiB range, gives one window each time:

RZ/G3S, 0x40000000 + 4 GiB
  window 0: base 0x040000000 mask 0x0ffffffff end 0x13fffffff  base & mask = 0x40000000  (carry)
RZ/G3E, 0x40000000 + 8 GiB
  window 0: base 0x040000000 mask 0x1ffffffff end 0x23fffffff  base & mask = 0x40000000  (carry)
0x40000000 + 6 GiB
  window 0: base 0x040000000 mask 0x1ffffffff end 0x23fffffff  base & mask = 0x40000000  (carry)

Both device tree ranges have a power-of-two size, so nothing is rounded, but their base is only 1 GiB aligned and every window carries. The RZ/G3S driver ran with these windows, and the RZ/G3E enforces the rule. A range whose size is not a power of two shows the second defect.

The 6 GiB range is rounded up to 8 GiB, and the window maps 2 GiB above the end of the range, memory that the device tree never gave to PCIe devices. A correct loop must split the range into several windows, each a power of two in size, naturally aligned, and inside the range.

The Reworked Loop

The loop merged for the RZ/G3E takes, at each step, the largest window that fits in the remaining range and that both addresses are aligned to:

	while (cpu_addr <= cpu_end) {
		u64 remaining_size = cpu_end - cpu_addr + 1;
		u64 align_limit;

		if (id >= RZG3S_MAX_WINDOWS)
			return dev_err_probe(host->dev, -ENOSPC,
					     "Failed to map inbound window for resource (%s)\n",
					     entry->res->name);

		/* Start with largest power-of-two that fits in remaining size */
		size = 1ULL << __fls(remaining_size);

		align_limit = min(cpu_addr ? (1ULL << __ffs(cpu_addr)) : ~0ULL,
				  pci_addr ? (1ULL << __ffs(pci_addr)) : ~0ULL);

		size = min(size, align_limit);

		/* Minimum window size is 4KB. */
		size = max(size, SZ_4K);

		rzg3s_pcie_set_inbound_window(host, cpu_addr, pci_addr,
					      size - 1, id);

		pci_addr += size;
		cpu_addr += size;
		id++;
	}

cpu_end is the last byte of the range, so the remaining size is cpu_end - cpu_addr + 1 and the loop runs while cpu_addr <= cpu_end. Address 0 is aligned to every power of two and has no set bit for __ffs(), so it puts no limit, ~0ULL, on the size. min() of the three limits gives a power of two that fits, keeps both bases naturally aligned, and never goes past the end of the range.

The final max() raises a smaller result to the 4 KiB minimum, which would map past the end of a range, or misalign a window, if the range did not start and end on 4 KiB boundaries. The dma-ranges of both SoCs do, so the max() never changes the size there. A range that would need more than eight windows makes the probe fail with -ENOSPC. The same program as before shows each step for the RZ/G3E range:

RZ/G3E, 0x40000000 + 8 GiB
  remaining 0x200000000 __fls 33  __ffs(cpu) 30 -> size 0x040000000
  window 0: base 0x040000000 mask 0x03fffffff end 0x07fffffff  base & mask = 0x0
  remaining 0x1c0000000 __fls 32  __ffs(cpu) 31 -> size 0x080000000
  window 1: base 0x080000000 mask 0x07fffffff end 0x0ffffffff  base & mask = 0x0
  remaining 0x140000000 __fls 32  __ffs(cpu) 32 -> size 0x100000000
  window 2: base 0x100000000 mask 0x0ffffffff end 0x1ffffffff  base & mask = 0x0
  remaining 0x040000000 __fls 30  __ffs(cpu) 33 -> size 0x040000000
  window 3: base 0x200000000 mask 0x03fffffff end 0x23fffffff  base & mask = 0x0

The alignment of the address limits the first two windows to 1 GiB and 2 GiB. At 0x100000000, the address and the remaining 5 GiB both allow 4 GiB. The last window takes the remaining 1 GiB. Four windows cover the 8 GiB exactly, with no carry. The RZ/G3S range gives three windows of 1, 2 and 1 GiB, and the 6 GiB range four windows ending at 0x1bfffffff, with nothing mapped beyond it.

8 GiB range from 0x40000000 split into windows of 1, 2, 4 and 1 GiB instead of one carrying window
Figure 6. The 8 GiB range of the RZ/G3E as programmed by the old loop and by the new one.

From First Version to Linux 7.1

The first version of the series kept the old loop for the RZ/G3S and added a separate one for the RZ/G3E behind a SoC callback. It also fixed the size tracking of the old loop, which reset size_id at each iteration instead of adding to it. Claudiu Beznea, the author of the RZ/G3S driver, answered that both manuals describe the inbound windows the same way, and that the RZ/G3E loop, tested on the RZ/G3S, mapped the same regions and worked. Version 2 therefore replaced both with the single loop shown above, which needs no size tracking at all.

The loop changed little afterwards, and version 8 is the one merged in Linux 7.1. The same commit is in the CIP 6.1 and 6.12 kernels.

Summing Up

__ffs() gives the alignment of a value and __fls() the largest power of two it holds, and the kernel builds bitmap walks, logarithms and allocation orders on them. Both are undefined for 0, so code that can see a zero needs a test or ffs() and fls(), and 64-bit values on 32-bit kernels need __ffs64() and fls64(). For a base and mask window, base & mask computed for each window shows a misaligned base at once.

Which hardware rule cost you the most time while upstreaming a driver? Tell us in the comments.

Share this post on:

Leave a Reply

Your email address will not be published. Required fields are marked *