Skip to content
This repository has been archived by the owner on Jun 18, 2024. It is now read-only.

Commit

Permalink
scx: Branchless implementation of highest_bit
Browse files Browse the repository at this point in the history
Origin implementation of function highest_bit utilize the function of
"fls()" to calculate the most significant bit of the input parameter
"flags". Normally we can return the mask with "1 << (fls(flags) - 1)",
but "fls(flags)" will return 0 if the value of "flags" is 0, which will
cause the evaluation become "1 << (-1)" and it's illegal. So we use a
branch to determine whether the return value of "fls(flags)" is 0.

We can remove the use of branch first left shift "fls(flags)" number of
bits and then right shift 1 bit. When the value of "fls(flags)" is 0
then this evaluation will simply become 0 without any error. As more
values other than 0, evaluation is the same as it did for
"1 << (fls(flags) - 1)".

This implementation can prevent any possible branch prediction fault and
pure shift operations are cheaper than branch operation for if-else
statements.
  • Loading branch information
vax-r committed May 23, 2024
1 parent f62ec64 commit baff66e
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion kernel/sched/ext.c
Original file line number Diff line number Diff line change
Expand Up @@ -1017,7 +1017,7 @@ static u32 higher_bits(u32 flags)
static u32 highest_bit(u32 flags)
{
int bit = fls(flags);
return bit ? 1 << (bit - 1) : 0;
return ((u64) 1 << bit) >> 1;
}

/*
Expand Down

0 comments on commit baff66e

Please sign in to comment.