Skip to contentSkip to conversation

linux/log2.h: Add round{up,down}_pow_of_two64()

PATCH In review David Gow 3 participants 5 messages Aug 21

Subsystems (2)
lore
Share & tools
lore

David Gow

author
#0 lore raw

PATCH 1/2 linux/log2.h: Add round{up,down}_pow_of_two64()

From: David Gow <[email protected]>

The existing roundup_pow_of_two() and rounddown_pow_of_two() functions work on values of type unsigned long, which is 32-bit on 32-bit systems. There are cases (most notably in the GPU buddy allocator) which always operate on 64-bit values (as a 32-bit host can still use a GPU which internally has 64-bit addresses).

Add a version of these which always operate on a 64-bit value. These have the (unimaginative) names roundup_pow_of_two64() and rounddown_pow_of_two64(), and otherwise work identically to their unsigned long counterparts. They are a bit ugly, but better than everyone hardcoding calls to ilog2() -- which does handle 64-bit values -- directly.

---

Hi all,

This series is basically a reworked and rebased version of
https://lore.kernel.org/all/[email protected]/

Most importantly, the drm_test_buddy_alloc_exceeds_max_order KUnit test was failing in linux-next on 32-bit systems, which this series fixes.

In rebasing it, I decided to add these helper functions, rather than having an open-coded round{up,down} implementation in the buddy allocator, but if no-one thinks it's worth having these for (at the moment) just one user, I'm not too worried either way.

Cheers,
-- David

---
 include/linux/log2.h | 57 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
include/linux/log2.h +57 -0
index e17ceb32e0c9..67446d5ce9a3 100644
@@ -195,6 +195,63 @@ unsigned long __rounddown_pow_of_two(unsigned long n)
 	__rounddown_pow_of_two(n)		\
  )
 
+/**
+ * __rounddown_pow_of_two64() - round a 64-bit value down to nearest power of two
+ * @n: value to round up
+ */
+static inline __attribute_const__
+u64 __rounddown_pow_of_two64(u64 n)
+{
+	return 1ULL << ilog2(n);
+}
+
+/**
+ * rounddown_pow_of_two64 - round a 64-bit value down to nearest power of two
+ * @n: parameter
+ *
+ * round the given value down to the nearest power of two
+ * - this always operates on 64-bit values, even on 32-bit systems
+ * - the result is undefined when n == 0
+ * - this can be used to initialise global variables from constant data
+ */
+#define rounddown_pow_of_two64(n)		\
+(						\
+	__builtin_constant_p(n) ? (		\
+		((n) == 1) ? 1ULL :		\
+		(1ULL << ilog2((n)))		\
+				   ) :		\
+	__rounddown_pow_of_two64(n)		\
+)
+
+
+/**
+ * __roundup_pow_of_two64() - round a 64-bit value up to nearest power of two
+ * @n: value to round up
+ */
+static inline __attribute_const__
+u64 __roundup_pow_of_two64(u64 n)
+{
+	return 1ULL << (ilog2(n - 1) + 1);
+}
+
+/**
+ * roundup_pow_of_two64 - round a 64-bit value up to nearest power of two
+ * @n: parameter
+ *
+ * round the given value up to the nearest power of two
+ * - this always operates on 64-bit values, even on 32-bit systems
+ * - the result is undefined when n == 0
+ * - this can be used to initialise global variables from constant data
+ */
+#define roundup_pow_of_two64(n)			\
+(						\
+	__builtin_constant_p(n) ? (		\
+		((n) == 1) ? 1ULL :		\
+		(1ULL << (ilog2((n) - 1) + 1))	\
+				   ) :		\
+	__roundup_pow_of_two64(n)		\
+)
+
 static inline __attribute_const__
 int __order_base_2(unsigned long n)
 {
Signature · 1 line
2.55.0
author
#1 lore raw

PATCH 2/2 drm_buddy: fix power-of-2 rounding errs

From: Jim Cromie <[email protected]>

The standard roundup_pow_of_two() and rounddown_pow_of_two() macros use unsigned long internally, which on 32-bit architectures (like arm32) is a 32-bit type.

drm_test_buddy_alloc_exceeds_max_order() uses these on a u64 value, where they silently truncate the 10GB allocation, giving unexpected success in DRM-CI. (see below the snip).

Fix this by replacing the those macros with the safe 64-bit power-of-two equivalents added in the previous patch.

---

This should actually be version 13, I think, as it's just a rebase of v12 here, where it was part of a large series of fixups:
https://lore.kernel.org/all/[email protected]/

The major changes since that version are:
- Add the helper functions rounddown_pow_of_two64() and roundup_pow_of_two64() (see patch 1) instead of open-coding them
- Rebase now that the buddy allocator lives in drivers/gpu/buddy.c instead of drivers/gpu/drm/drm_buddy.c

This is still breaking the gpu_test_buddy_alloc_exceeds_max_order
KUnit test on 32-bit systems:
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: EXPECTATION FAILED at drivers/gpu/tests/gpu_buddy_test.c:1429
[09:01:26] Expected err == -22, but
[09:01:26] err == 0 (0x0)
[09:01:26] WARNING: drivers/gpu/buddy.c:508 at gpu_buddy_fini+0x244/0x2e0, CPU#0: kunit_try_catch/1595
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: drivers/gpu/buddy.c:508: gpu_buddy_assert(gpu_buddy_block_is_free(mm->roots[i]))
[09:01:26] WARNING: drivers/gpu/buddy.c:516 at gpu_buddy_fini+0x284/0x2e0, CPU#0: kunit_try_catch/1595
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: drivers/gpu/buddy.c:508: gpu_buddy_assert(gpu_buddy_block_is_free(mm->roots[i]))
[09:01:26] WARNING: drivers/gpu/buddy.c:516 at gpu_buddy_fini+0x284/0x2e0, CPU#0: kunit_try_catch/1595
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: drivers/gpu/buddy.c:519: gpu_buddy_assert(!mm->used_scoreboard[i])
[09:01:26] [FAILED] gpu_test_buddy_alloc_exceeds_max_order

Cheers,
-- David

---
 drivers/gpu/buddy.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/gpu/buddy.c +2 -2
index a5553fcec28c..64f41f1fe908 100644
@@ -1193,7 +1193,7 @@ static int __alloc_contig_try_harder(struct gpu_buddy *mm,
 	u64 modify_size;
 	int err;
 
-	modify_size = rounddown_pow_of_two(size);
+	modify_size = rounddown_pow_of_two64(size);
 	order = ilog2(modify_size) - ilog2(mm->chunk_size);
 	if (order == 0)
 		return -ENOSPC;
@@ -1440,7 +1440,7 @@ int gpu_buddy_alloc_blocks(struct gpu_buddy *mm,
 
 	/* Roundup the size to power of 2 */
 	if (flags & GPU_BUDDY_CONTIGUOUS_ALLOCATION) {
-		size = roundup_pow_of_two(size);
+		size = roundup_pow_of_two64(size);
 		min_block_size = size;
 		/*
 		 * Normalize the requested size to min_block_size for regular allocations.
Signature · 1 line
2.55.0
#2 lore raw

Re: [PATCH 2/2] drm_buddy: fix power-of-2 rounding errs

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Pre-existing issues:
- [High] The pages variable is declared as unsigned long, and the fls() and BIT() macros are used, leading to silent truncation and potential infinite loops or crashes for large allocations.
- [High] Calling the is_power_of_2() macro with 64-bit variables (min_block_size and size) silently truncates them to 32 bits on 32-bit architectures, breaking allocator validation. --

--- Patch [2]: [PATCH 2/2] drm_buddy: fix power-of-2 rounding errs --- commit 6e9e2fbe5490ccf9c40ea5dcdf1e897c00f63b30
Author: Jim Cromie <[email protected]>

drm_buddy: fix power-of-2 rounding errs

This patch replaces standard roundup_pow_of_two() and rounddown_pow_of_two() macros with their 64-bit equivalents in the GPU buddy allocator. This fixes silent truncation of 64-bit allocation sizes on 32-bit architectures, which was causing tests to fail.

Quoted 4 lines
drivers/gpu/buddy.c +0 -0
index a5553fcec28c2..64f41f1fe9089 100644

[ ... ]

drivers/gpu/buddy.c int gpu_buddy_alloc_blocks(struct gpu_buddy *mm, · line 1446

Quoted 9 lines
drivers/gpu/buddy.c +1 -1
@@ -1440,7 +1440,7 @@ int gpu_buddy_alloc_blocks(struct gpu_buddy *mm,
 
 	/* Roundup the size to power of 2 */
 	if (flags & GPU_BUDDY_CONTIGUOUS_ALLOCATION) {
-		size = roundup_pow_of_two(size);
+		size = roundup_pow_of_two64(size);
 		min_block_size = size;
 		/*
 		 * Normalize the requested size to min_block_size for regular allocations.

[Severity: High]
This is a pre-existing issue, but since you are fixing 32-bit truncation errors in this function, are there similar truncation issues with the pages variable later in gpu_buddy_alloc_blocks()?

The pages variable is declared as unsigned long:

	unsigned long pages;

And later initialized and used with fls() and BIT():

	pages = size >> ilog2(mm->chunk_size);
	order = fls(pages) - 1;
        ...
		pages -= BIT(order);

Since unsigned long is 32-bit on 32-bit architectures, pages truncates for sizes > 16TB (assuming 4KB chunks).

Furthermore, fls() takes a 32-bit integer, so it will truncate pages on 64-bit systems.

BIT(order) also uses 1UL, which overflows on 32-bit architectures if order >= 32.

Can this lead to infinite loops or crashes for large allocations?

Similar truncation might also occur in gpu_buddy_offset_aligned_allocation(), which also uses unsigned long pages.

[Severity: High]
This is another pre-existing issue, but does is_power_of_2() also silently truncate 64-bit variables on 32-bit architectures?

Earlier in gpu_buddy_alloc_blocks():

	if (!is_power_of_2(min_block_size))
		return -EINVAL;

The is_power_of_2() macro casts its argument to unsigned long.

If a 64-bit value like 4GB + 4KB is passed, it truncates to 4KB on 32-bit systems, which is a valid power of two.

This bypasses the validation and allows non-power-of-two sizes to reach round_up(), which could corrupt sizes and allocator memory.

A similar check exists in gpu_buddy_can_offset_align():

	return size < min_block_size && is_power_of_2(size);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
maintainer
#3 lore raw

Re: [PATCH 2/2] drm_buddy: fix power-of-2 rounding errs

In reply to David Gow
Quoted 6 lines · David Gow

From: Jim Cromie <[email protected]>

The standard roundup_pow_of_two() and rounddown_pow_of_two() macros use unsigned long internally, which on 32-bit architectures (like arm32) is a 32-bit type.

Quoted 6 lines

drm_test_buddy_alloc_exceeds_max_order() uses these on a u64 value, where they silently truncate the 10GB allocation, giving unexpected success in DRM-CI. (see below the snip).

Fix this by replacing the those macros with the safe 64-bit power-of-two equivalents added in the previous patch.

Do we also need something like is_power_of_2_u64() ? I think we could then remove that from i915_utils.h

Quoted 57 lines

---

This should actually be version 13, I think, as it's just a rebase of v12 here, where it was part of a large series of fixups:
https://lore.kernel.org/all/[email protected]/

The major changes since that version are:
- Add the helper functions rounddown_pow_of_two64() and roundup_pow_of_two64() (see patch 1) instead of open-coding them
- Rebase now that the buddy allocator lives in drivers/gpu/buddy.c instead of drivers/gpu/drm/drm_buddy.c

This is still breaking the gpu_test_buddy_alloc_exceeds_max_order
KUnit test on 32-bit systems:
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: EXPECTATION FAILED at drivers/gpu/tests/gpu_buddy_test.c:1429
[09:01:26] Expected err == -22, but
[09:01:26] err == 0 (0x0)
[09:01:26] WARNING: drivers/gpu/buddy.c:508 at gpu_buddy_fini+0x244/0x2e0, CPU#0: kunit_try_catch/1595
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: drivers/gpu/buddy.c:508: gpu_buddy_assert(gpu_buddy_block_is_free(mm->roots[i]))
[09:01:26] WARNING: drivers/gpu/buddy.c:516 at gpu_buddy_fini+0x284/0x2e0, CPU#0: kunit_try_catch/1595
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: drivers/gpu/buddy.c:508: gpu_buddy_assert(gpu_buddy_block_is_free(mm->roots[i]))
[09:01:26] WARNING: drivers/gpu/buddy.c:516 at gpu_buddy_fini+0x284/0x2e0, CPU#0: kunit_try_catch/1595
[09:01:26] # gpu_test_buddy_alloc_exceeds_max_order: drivers/gpu/buddy.c:519: gpu_buddy_assert(!mm->used_scoreboard[i])
[09:01:26] [FAILED] gpu_test_buddy_alloc_exceeds_max_order

Cheers,
-- David

---
  drivers/gpu/buddy.c | 4 ++--
  1 file changed, 2 insertions(+), 2 deletions(-)
drivers/gpu/buddy.c +2 -2
index a5553fcec28c..64f41f1fe908 100644
@@ -1193,7 +1193,7 @@ static int __alloc_contig_try_harder(struct gpu_buddy *mm,
  	u64 modify_size;
  	int err;
 
-	modify_size = rounddown_pow_of_two(size);
+	modify_size = rounddown_pow_of_two64(size);
  	order = ilog2(modify_size) - ilog2(mm->chunk_size);
  	if (order == 0)
  		return -ENOSPC;
@@ -1440,7 +1440,7 @@ int gpu_buddy_alloc_blocks(struct gpu_buddy *mm,
 
  	/* Roundup the size to power of 2 */
  	if (flags & GPU_BUDDY_CONTIGUOUS_ALLOCATION) {
-		size = roundup_pow_of_two(size);
+		size = roundup_pow_of_two64(size);
  		min_block_size = size;
  		/*
  		 * Normalize the requested size to min_block_size for regular allocations.
#4 lore raw
In reply to David Gow
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Calling `__roundup_pow_of_two64(1)` evaluates `ilog2(0)`, violating the `ilog2()` API contract…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Calling __roundup_pow_of_two64(1) evaluates ilog2(0), violating the ilog2() API contract and relying on undefined behavior for architecture fallbacks.
- [Low] The kernel-doc comment for __rounddown_pow_of_two64() incorrectly describes the @n parameter as 'value to round up'.
--

--- Patch [1]: [PATCH 1/2] linux/log2.h: Add round{up,down}_pow_of_two64() --- commit 4cce4f9f15f91ab3c1df542bca356b3776146fef
Author: David Gow <[email protected]>

linux/log2.h: Add round{up,down}_pow_of_two64()

This commit adds 64-bit specific versions of round-up and round-down power of two macros. It is intended to support 64-bit values on 32-bit systems, particularly for the GPU buddy allocator.

include/linux/log2.h unsigned long __rounddown_pow_of_two(unsigned long n) · line 200

Quoted 11 lines
include/linux/log2.h +3 -0
index e17ceb32e0c97..67446d5ce9a32 100644
@@ -195,6 +195,63 @@ unsigned long __rounddown_pow_of_two(unsigned long n)
 	__rounddown_pow_of_two(n)		\
  )
 
+/**
+ * __rounddown_pow_of_two64() - round a 64-bit value down to nearest power of two
+ * @n: value to round up

[Severity: Low]
This isn't a bug, but should this be "value to round down" for the __rounddown_pow_of_two64() variant?

Quoted 4 lines
include/linux/log2.h +4 -0
+ */
+static inline __attribute_const__
+u64 __rounddown_pow_of_two64(u64 n)
+{

[ ... ]

include/linux/log2.h unsigned long __rounddown_pow_of_two(unsigned long n) · line 234

Quoted 8 lines
include/linux/log2.h +8 -0
+/**
+ * __roundup_pow_of_two64() - round a 64-bit value up to nearest power of two
+ * @n: value to round up
+ */
+static inline __attribute_const__
+u64 __roundup_pow_of_two64(u64 n)
+{
+	return 1ULL << (ilog2(n - 1) + 1);

[Severity: Medium]
Will calling roundup_pow_of_two64(1) with a runtime variable evaluate to ilog2(0) here?

The documentation in include/linux/log2.h states that the architecture is not required to handle n == 0 for ilog2(). While current fallback implementations evaluate fls64(0) - 1 to -1 and return 1, an architecture providing an optimized hardware ilog2() implementation might trap or break on 0.

The existing 32-bit __roundup_pow_of_two() avoids this by safely relying on fls_long(n - 1).

Quoted 1 line

+}

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1