Jakub Zawadzki noticed that some divisions by reciprocal_divide()
were not correct [1][2], which he could also show with BPF code
after divisions are transformed into reciprocal_value() for runtime
invariance which can be passed to reciprocal_divide() later on;
reverse in BPF dump ended up with a different, off-by-one K in
some situations.
This has been fixed by Eric Dumazet in commit aee636c4809fa5
("bpf: do not use reciprocal divide"). This follow-up patch
improves reciprocal_value() and reciprocal_divide() to work in
all cases by using Granlund and Montgomery method, so that also
future use is safe and without any non-obvious side-effects.
Known problems with the old implementation were that division by 1
always returned 0 and some off-by-ones when the dividend and divisor
where very large. This seemed to not be problematic with its
current users, as far as we can tell. Eric Dumazet checked for
the slab usage, we cannot surely say so in the case of flex_array.
Still, in order to fix that, we propose an extension from the
original implementation from commit 6a2d7a955d8d resp. [3][4],
by using the algorithm proposed in "Division by Invariant Integers
Using Multiplication" [5], Torbjörn Granlund and Peter L.
Montgomery, that is, pseudocode for q = n/d where q, n, d is in
u32 universe:
1) Initialization:
  int l = ceil(log_2 d)
  uword m' = floor((1<<
Cc: Eric Dumazet 
Cc: Austin S Hemmelgarn 
Cc: linux-kernel@vger.kernel.org
Cc: Jesse Gross 
Cc: Jamal Hadi Salim 
Cc: Stephen Hemminger 
Cc: Matt Mackall 
Cc: Pekka Enberg 
Cc: Christoph Lameter 
Cc: Andy Gospodarek 
Cc: Veaceslav Falico 
Cc: Jay Vosburgh 
Cc: Jakub Zawadzki 
Signed-off-by: Daniel Borkmann 
Signed-off-by: Hannes Frederic Sowa 
Signed-off-by: David S. Miller