reciprocal_div.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/bitops.h>
  3. #include <linux/bug.h>
  4. #include <linux/export.h>
  5. #include <linux/limits.h>
  6. #include <linux/math.h>
  7. #include <linux/minmax.h>
  8. #include <linux/types.h>
  9. #include <linux/reciprocal_div.h>
  10. /*
  11. * For a description of the algorithm please have a look at
  12. * include/linux/reciprocal_div.h
  13. */
  14. struct reciprocal_value reciprocal_value(u32 d)
  15. {
  16. struct reciprocal_value R;
  17. u64 m;
  18. int l;
  19. l = fls(d - 1);
  20. m = ((1ULL << 32) * ((1ULL << l) - d));
  21. do_div(m, d);
  22. ++m;
  23. R.m = (u32)m;
  24. R.sh1 = min(l, 1);
  25. R.sh2 = max(l - 1, 0);
  26. return R;
  27. }
  28. EXPORT_SYMBOL(reciprocal_value);
  29. struct reciprocal_value_adv reciprocal_value_adv(u32 d, u8 prec)
  30. {
  31. struct reciprocal_value_adv R;
  32. u32 l, post_shift;
  33. u64 mhigh, mlow;
  34. /* ceil(log2(d)) */
  35. l = fls(d - 1);
  36. /* NOTE: mlow/mhigh could overflow u64 when l == 32. This case needs to
  37. * be handled before calling "reciprocal_value_adv", please see the
  38. * comment at include/linux/reciprocal_div.h.
  39. */
  40. WARN(l == 32,
  41. "ceil(log2(0x%08x)) == 32, %s doesn't support such divisor",
  42. d, __func__);
  43. post_shift = l;
  44. mlow = 1ULL << (32 + l);
  45. do_div(mlow, d);
  46. mhigh = (1ULL << (32 + l)) + (1ULL << (32 + l - prec));
  47. do_div(mhigh, d);
  48. for (; post_shift > 0; post_shift--) {
  49. u64 lo = mlow >> 1, hi = mhigh >> 1;
  50. if (lo >= hi)
  51. break;
  52. mlow = lo;
  53. mhigh = hi;
  54. }
  55. R.m = (u32)mhigh;
  56. R.sh = post_shift;
  57. R.exp = l;
  58. R.is_wide_m = mhigh > U32_MAX;
  59. return R;
  60. }
  61. EXPORT_SYMBOL(reciprocal_value_adv);