Commit 77212d3a authored by Kent Overstreet's avatar Kent Overstreet

bcachefs: Fix shift by 64 in set_inc_field()

UBSAN was complaining about a shift by 64 in set_inc_field().

This only happened when the value being shifted was 0, so in theory
should be harmless - a shift by 64 (or register width) should logically
give a result of 0, but CPUs will in practice leave the input unchanged
when the number of bits to shift by wraps - and since our input here is
0, the output is still what we want.

But, it's still undefined behaviour and we need our UBSAN output to be
clean, so it needs to be fixed.
Signed-off-by: default avatarKent Overstreet <kent.overstreet@linux.dev>
parent 6c643965
......@@ -184,6 +184,28 @@ static u64 get_inc_field(struct unpack_state *state, unsigned field)
return v + offset;
}
__always_inline
static void __set_inc_field(struct pack_state *state, unsigned field, u64 v)
{
unsigned bits = state->format->bits_per_field[field];
if (bits) {
if (bits > state->bits) {
bits -= state->bits;
/* avoid shift by 64 if bits is 64 - bits is never 0 here: */
state->w |= (v >> 1) >> (bits - 1);
*state->p = state->w;
state->p = next_word(state->p);
state->w = 0;
state->bits = 64;
}
state->bits -= bits;
state->w |= v << state->bits;
}
}
__always_inline
static bool set_inc_field(struct pack_state *state, unsigned field, u64 v)
{
......@@ -198,20 +220,7 @@ static bool set_inc_field(struct pack_state *state, unsigned field, u64 v)
if (fls64(v) > bits)
return false;
if (bits > state->bits) {
bits -= state->bits;
/* avoid shift by 64 if bits is 0 - bits is never 64 here: */
state->w |= (v >> 1) >> (bits - 1);
*state->p = state->w;
state->p = next_word(state->p);
state->w = 0;
state->bits = 64;
}
state->bits -= bits;
state->w |= v << state->bits;
__set_inc_field(state, field, v);
return true;
}
......@@ -380,19 +389,7 @@ static bool set_inc_field_lossy(struct pack_state *state, unsigned field, u64 v)
ret = false;
}
if (bits > state->bits) {
bits -= state->bits;
state->w |= (v >> 1) >> (bits - 1);
*state->p = state->w;
state->p = next_word(state->p);
state->w = 0;
state->bits = 64;
}
state->bits -= bits;
state->w |= v << state->bits;
__set_inc_field(state, field, v);
return ret;
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment