xref: /linux-6.15/include/linux/units.h (revision ef6c8da7)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_UNITS_H
3 #define _LINUX_UNITS_H
4 
5 #include <linux/math.h>
6 
7 /* Metric prefixes in accordance with Système international (d'unités) */
8 #define PETA	1000000000000000ULL
9 #define TERA	1000000000000ULL
10 #define GIGA	1000000000UL
11 #define MEGA	1000000UL
12 #define KILO	1000UL
13 #define HECTO	100UL
14 #define DECA	10UL
15 #define DECI	10UL
16 #define CENTI	100UL
17 #define MILLI	1000UL
18 #define MICRO	1000000UL
19 #define NANO	1000000000UL
20 #define PICO	1000000000000ULL
21 #define FEMTO	1000000000000000ULL
22 
23 #define MILLIWATT_PER_WATT	1000L
24 #define MICROWATT_PER_MILLIWATT	1000L
25 #define MICROWATT_PER_WATT	1000000L
26 
27 #define ABSOLUTE_ZERO_MILLICELSIUS -273150
28 
29 static inline long milli_kelvin_to_millicelsius(long t)
30 {
31 	return t + ABSOLUTE_ZERO_MILLICELSIUS;
32 }
33 
34 static inline long millicelsius_to_milli_kelvin(long t)
35 {
36 	return t - ABSOLUTE_ZERO_MILLICELSIUS;
37 }
38 
39 #define MILLIDEGREE_PER_DEGREE 1000
40 #define MILLIDEGREE_PER_DECIDEGREE 100
41 
42 static inline long kelvin_to_millicelsius(long t)
43 {
44 	return milli_kelvin_to_millicelsius(t * MILLIDEGREE_PER_DEGREE);
45 }
46 
47 static inline long millicelsius_to_kelvin(long t)
48 {
49 	t = millicelsius_to_milli_kelvin(t);
50 
51 	return DIV_ROUND_CLOSEST(t, MILLIDEGREE_PER_DEGREE);
52 }
53 
54 static inline long deci_kelvin_to_celsius(long t)
55 {
56 	t = milli_kelvin_to_millicelsius(t * MILLIDEGREE_PER_DECIDEGREE);
57 
58 	return DIV_ROUND_CLOSEST(t, MILLIDEGREE_PER_DEGREE);
59 }
60 
61 static inline long celsius_to_deci_kelvin(long t)
62 {
63 	t = millicelsius_to_milli_kelvin(t * MILLIDEGREE_PER_DEGREE);
64 
65 	return DIV_ROUND_CLOSEST(t, MILLIDEGREE_PER_DECIDEGREE);
66 }
67 
68 /**
69  * deci_kelvin_to_millicelsius_with_offset - convert Kelvin to Celsius
70  * @t: temperature value in decidegrees Kelvin
71  * @offset: difference between Kelvin and Celsius in millidegrees
72  *
73  * Return: temperature value in millidegrees Celsius
74  */
75 static inline long deci_kelvin_to_millicelsius_with_offset(long t, long offset)
76 {
77 	return t * MILLIDEGREE_PER_DECIDEGREE - offset;
78 }
79 
80 static inline long deci_kelvin_to_millicelsius(long t)
81 {
82 	return milli_kelvin_to_millicelsius(t * MILLIDEGREE_PER_DECIDEGREE);
83 }
84 
85 static inline long millicelsius_to_deci_kelvin(long t)
86 {
87 	t = millicelsius_to_milli_kelvin(t);
88 
89 	return DIV_ROUND_CLOSEST(t, MILLIDEGREE_PER_DECIDEGREE);
90 }
91 
92 static inline long kelvin_to_celsius(long t)
93 {
94 	return t + DIV_ROUND_CLOSEST(ABSOLUTE_ZERO_MILLICELSIUS,
95 				     MILLIDEGREE_PER_DEGREE);
96 }
97 
98 static inline long celsius_to_kelvin(long t)
99 {
100 	return t - DIV_ROUND_CLOSEST(ABSOLUTE_ZERO_MILLICELSIUS,
101 				     MILLIDEGREE_PER_DEGREE);
102 }
103 
104 #endif /* _LINUX_UNITS_H */
105