blob: 30e0f9770f88cef66f8655c0b377366b7d986db8 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Davidlohr Bueso30493cc2013-04-29 16:18:09 -07002/*
3 * Copyright (C) 2013 Davidlohr Bueso <davidlohr.bueso@hp.com>
4 *
5 * Based on the shift-and-subtract algorithm for computing integer
6 * square root from Guy L. Steele.
7 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07008
9#include <linux/kernel.h>
Paul Gortmaker8bc3bcc2011-11-16 21:29:17 -050010#include <linux/export.h>
Peter Zijlstraf8ae1072017-11-17 15:28:08 -080011#include <linux/bitops.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070012
13/**
Peter Zijlstrae813a612017-11-17 15:28:12 -080014 * int_sqrt - computes the integer square root
Linus Torvalds1da177e2005-04-16 15:20:36 -070015 * @x: integer of which to calculate the sqrt
16 *
Peter Zijlstrae813a612017-11-17 15:28:12 -080017 * Computes: floor(sqrt(x))
Linus Torvalds1da177e2005-04-16 15:20:36 -070018 */
19unsigned long int_sqrt(unsigned long x)
20{
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070021 unsigned long b, m, y = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -070022
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070023 if (x <= 1)
24 return x;
Linus Torvalds1da177e2005-04-16 15:20:36 -070025
Peter Zijlstraf8ae1072017-11-17 15:28:08 -080026 m = 1UL << (__fls(x) & ~1UL);
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070027 while (m != 0) {
28 b = y + m;
29 y >>= 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -070030
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070031 if (x >= b) {
32 x -= b;
33 y += m;
Linus Torvalds1da177e2005-04-16 15:20:36 -070034 }
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070035 m >>= 2;
Linus Torvalds1da177e2005-04-16 15:20:36 -070036 }
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070037
38 return y;
Linus Torvalds1da177e2005-04-16 15:20:36 -070039}
40EXPORT_SYMBOL(int_sqrt);
Crt Mori47a36162018-01-11 11:19:57 +010041
42#if BITS_PER_LONG < 64
43/**
44 * int_sqrt64 - strongly typed int_sqrt function when minimum 64 bit input
45 * is expected.
46 * @x: 64bit integer of which to calculate the sqrt
47 */
48u32 int_sqrt64(u64 x)
49{
50 u64 b, m, y = 0;
51
52 if (x <= ULONG_MAX)
53 return int_sqrt((unsigned long) x);
54
Florian La Roche328f3de2019-01-19 16:14:50 +010055 m = 1ULL << ((fls64(x) - 1) & ~1ULL);
Crt Mori47a36162018-01-11 11:19:57 +010056 while (m != 0) {
57 b = y + m;
58 y >>= 1;
59
60 if (x >= b) {
61 x -= b;
62 y += m;
63 }
64 m >>= 2;
65 }
66
67 return y;
68}
69EXPORT_SYMBOL(int_sqrt64);
70#endif