blob: b0bee6ca5b90ea845e31cbf95bb60bdbaea75c9b [file] [log] [blame]
Ken Tsou8acade12020-07-09 03:17:35 +08001/*
AleX Pelosi78a4bea2020-09-01 19:02:24 -07002 * Copyright 2018 Google, LLC
Ken Tsou8acade12020-07-09 03:17:35 +08003 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15#ifndef QMATH_H_
16#define QMATH_H_
17
18#include <linux/types.h>
Alice Sheng83732292022-07-08 11:19:46 -070019#include <linux/math64.h>
Ken Tsou8acade12020-07-09 03:17:35 +080020
21typedef s32 qnum_t;
22typedef s64 qnumd_t;
23typedef u32 qnumu_t;
24typedef s64 qnumud_t;
25
26#define QNUM_BITS (sizeof(qnum_t)*8)
27/* integer part */
28#define QNUM_IBITS 8
29/* fractional part and mask */
30#define QNUM_FBITS (QNUM_BITS - QNUM_IBITS)
31#define QNUM_FMASK (((qnum_t)1 << QNUM_FBITS) - 1)
32
33#define qnum_rconst(R) \
34 ((qnum_t)((R) * (((qnumd_t)1 << QNUM_FBITS)\
35 + ((R) >= 0 ? 0.5 : -0.5))))
36
37#define qnum_fromint(I) ((qnumd_t)(I) << QNUM_FBITS)
38/* battery raw capacity is in Q8_8 */
39#define qnum_from_q8_8(Q8_8) ((qnumd_t)(Q8_8) << (QNUM_FBITS-8))
40
41/* truncate */
42#define qnum_toint(F) ((int)((F) >> QNUM_FBITS))
43/* round the number */
44#define qnum_roundint(F, P) \
45 qnum_toint(F + qnum_rconst(P))
46
47
48static inline qnum_t qnum_mul(qnum_t A, qnum_t B)
49{
50 return (((qnumd_t)A * (qnumd_t)B) >> QNUM_FBITS);
51}
52
53static inline qnum_t qnum_div(qnum_t A, qnum_t B)
54{
Alice Sheng83732292022-07-08 11:19:46 -070055
56 return div64_s64(((qnumd_t)A << QNUM_FBITS), (qnumd_t)B);
Ken Tsou8acade12020-07-09 03:17:35 +080057}
58
59
60/* 1, 2, 3, and 4 digits */
61#define qnum_fracpart(A) ((qnum_t)(A) & QNUM_FMASK)
62
63#define QNUM_FRACBITS(A) \
64 (((qnum_fracpart(A) << QNUM_IBITS)) & (((qnumud_t)1 << QNUM_BITS)-1))
65
66#define QNUM_FRACn(A, n) \
67 (((QNUM_FRACBITS(A) * n) >> QNUM_BITS) % n)
68
69#define QNUM_FRAC1(A) QNUM_FRACn(A, 10)
70#define QNUM_FRAC2(A) QNUM_FRACn(A, 100)
71#define QNUM_FRAC3(A) QNUM_FRACn(A, 1000)
72#define QNUM_FRAC4(A) QNUM_FRACn(A, 10000)
73
74
75#define _PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__
76
77/* print as %d.%0<num>d */
78#define _STR_(x) # x
79#define QNUM_FDGT_NUM 2
80#define QNUM_CSTR_FMT "%d.%02d"
81#define QNUM_CSTR_SZ (4 + 1 + QNUM_FDGT_NUM + 1)
82#define qnum_nfracdgt(A, n) _PRIMITIVE_CAT(QNUM_FRAC, n)(A)
83#define qnum_fracdgt(A) ((int)qnum_nfracdgt(A, QNUM_FDGT_NUM))
84#endif /* QMATH_H_ */