Srinu Gorle | cf8c675 | 2018-01-19 18:36:13 +0530 | [diff] [blame] | 1 | /* Copyright (c) 2015, 2018, The Linux Foundation. All rights reserved. |
| 2 | * |
| 3 | * This program is free software; you can redistribute it and/or modify |
| 4 | * it under the terms of the GNU General Public License version 2 and |
| 5 | * only version 2 as published by the Free Software Foundation. |
| 6 | * |
| 7 | * This program is distributed in the hope that it will be useful, |
| 8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 10 | * GNU General Public License for more details. |
| 11 | */ |
| 12 | |
| 13 | #ifdef _FIXP_ARITH_H |
| 14 | #error "This implementation is meant to override fixp-arith.h, don't use both" |
| 15 | #endif |
| 16 | |
| 17 | #ifndef __FP_H__ |
| 18 | #define __FP_H__ |
| 19 | |
| 20 | /* |
| 21 | * Normally would typedef'ed, but checkpatch doesn't like typedef. |
| 22 | * Also should be normally typedef'ed to intmax_t but that doesn't seem to be |
| 23 | * available in the kernel |
| 24 | */ |
| 25 | #define fp_t size_t |
| 26 | |
| 27 | /* (Arbitrarily) make the first 25% of the bits to be the fractional bits */ |
| 28 | #define FP_FRACTIONAL_BITS ((sizeof(fp_t) * 8) / 4) |
| 29 | |
| 30 | #define FP(__i, __f_n, __f_d) \ |
| 31 | ((((fp_t)(__i)) << FP_FRACTIONAL_BITS) + \ |
| 32 | (((__f_n) << FP_FRACTIONAL_BITS) / (__f_d))) |
| 33 | |
| 34 | #define FP_INT(__i) FP(__i, 0, 1) |
| 35 | #define FP_ONE FP_INT(1) |
| 36 | #define FP_ZERO FP_INT(0) |
| 37 | |
| 38 | static inline size_t fp_frac_base(void) |
| 39 | { |
| 40 | return GENMASK(FP_FRACTIONAL_BITS - 1, 0); |
| 41 | } |
| 42 | |
| 43 | static inline size_t fp_frac(fp_t a) |
| 44 | { |
| 45 | return a & GENMASK(FP_FRACTIONAL_BITS - 1, 0); |
| 46 | } |
| 47 | |
| 48 | static inline size_t fp_int(fp_t a) |
| 49 | { |
| 50 | return a >> FP_FRACTIONAL_BITS; |
| 51 | } |
| 52 | |
| 53 | static inline size_t fp_round(fp_t a) |
| 54 | { |
| 55 | /* is the fractional part >= frac_max / 2? */ |
| 56 | bool round_up = fp_frac(a) >= fp_frac_base() / 2; |
| 57 | |
| 58 | return fp_int(a) + round_up; |
| 59 | } |
| 60 | |
| 61 | static inline fp_t fp_mult(fp_t a, fp_t b) |
| 62 | { |
| 63 | return (a * b) >> FP_FRACTIONAL_BITS; |
| 64 | } |
| 65 | |
| 66 | |
| 67 | static inline fp_t fp_div(fp_t a, fp_t b) |
| 68 | { |
| 69 | return (a << FP_FRACTIONAL_BITS) / b; |
| 70 | } |
| 71 | |
| 72 | #endif |