OSDN Git Service

Merge "mmc: block: Unhalt the command queue before releasing mmc host"
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / drivers / power / supply / qcom / qpnp-fg-gen3.c
1 /* Copyright (c) 2016-2017, 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 #define pr_fmt(fmt)     "FG: %s: " fmt, __func__
14
15 #include <linux/ktime.h>
16 #include <linux/of.h>
17 #include <linux/of_irq.h>
18 #include <linux/of_platform.h>
19 #include <linux/of_batterydata.h>
20 #include <linux/platform_device.h>
21 #include <linux/iio/consumer.h>
22 #include <linux/qpnp/qpnp-revid.h>
23 #include "fg-core.h"
24 #include "fg-reg.h"
25
26 #define FG_GEN3_DEV_NAME        "qcom,fg-gen3"
27
28 #define PERPH_SUBTYPE_REG               0x05
29 #define FG_BATT_SOC_PMI8998             0x10
30 #define FG_BATT_INFO_PMI8998            0x11
31 #define FG_MEM_INFO_PMI8998             0x0D
32
33 /* SRAM address and offset in ascending order */
34 #define ESR_PULSE_THRESH_WORD           2
35 #define ESR_PULSE_THRESH_OFFSET         3
36 #define SLOPE_LIMIT_WORD                3
37 #define SLOPE_LIMIT_OFFSET              0
38 #define CUTOFF_VOLT_WORD                5
39 #define CUTOFF_VOLT_OFFSET              0
40 #define SYS_TERM_CURR_WORD              6
41 #define SYS_TERM_CURR_OFFSET            0
42 #define VBATT_FULL_WORD                 7
43 #define VBATT_FULL_OFFSET               0
44 #define ESR_FILTER_WORD                 8
45 #define ESR_UPD_TIGHT_OFFSET            0
46 #define ESR_UPD_BROAD_OFFSET            1
47 #define ESR_UPD_TIGHT_LOW_TEMP_OFFSET   2
48 #define ESR_UPD_BROAD_LOW_TEMP_OFFSET   3
49 #define KI_COEFF_MED_DISCHG_WORD        9
50 #define TIMEBASE_OFFSET                 1
51 #define KI_COEFF_MED_DISCHG_OFFSET      3
52 #define KI_COEFF_HI_DISCHG_WORD         10
53 #define KI_COEFF_HI_DISCHG_OFFSET       0
54 #define KI_COEFF_LOW_DISCHG_WORD        10
55 #define KI_COEFF_LOW_DISCHG_OFFSET      2
56 #define KI_COEFF_FULL_SOC_WORD          12
57 #define KI_COEFF_FULL_SOC_OFFSET        2
58 #define DELTA_MSOC_THR_WORD             12
59 #define DELTA_MSOC_THR_OFFSET           3
60 #define DELTA_BSOC_THR_WORD             13
61 #define DELTA_BSOC_THR_OFFSET           2
62 #define RECHARGE_SOC_THR_WORD           14
63 #define RECHARGE_SOC_THR_OFFSET         0
64 #define CHG_TERM_CURR_WORD              14
65 #define CHG_TERM_CURR_OFFSET            1
66 #define EMPTY_VOLT_WORD                 15
67 #define EMPTY_VOLT_OFFSET               0
68 #define VBATT_LOW_WORD                  15
69 #define VBATT_LOW_OFFSET                1
70 #define ESR_TIMER_DISCHG_MAX_WORD       17
71 #define ESR_TIMER_DISCHG_MAX_OFFSET     0
72 #define ESR_TIMER_DISCHG_INIT_WORD      17
73 #define ESR_TIMER_DISCHG_INIT_OFFSET    2
74 #define ESR_TIMER_CHG_MAX_WORD          18
75 #define ESR_TIMER_CHG_MAX_OFFSET        0
76 #define ESR_TIMER_CHG_INIT_WORD         18
77 #define ESR_TIMER_CHG_INIT_OFFSET       2
78 #define ESR_EXTRACTION_ENABLE_WORD      19
79 #define ESR_EXTRACTION_ENABLE_OFFSET    0
80 #define PROFILE_LOAD_WORD               24
81 #define PROFILE_LOAD_OFFSET             0
82 #define ESR_RSLOW_DISCHG_WORD           34
83 #define ESR_RSLOW_DISCHG_OFFSET         0
84 #define ESR_RSLOW_CHG_WORD              51
85 #define ESR_RSLOW_CHG_OFFSET            0
86 #define NOM_CAP_WORD                    58
87 #define NOM_CAP_OFFSET                  0
88 #define ACT_BATT_CAP_BKUP_WORD          74
89 #define ACT_BATT_CAP_BKUP_OFFSET        0
90 #define CYCLE_COUNT_WORD                75
91 #define CYCLE_COUNT_OFFSET              0
92 #define PROFILE_INTEGRITY_WORD          79
93 #define SW_CONFIG_OFFSET                0
94 #define PROFILE_INTEGRITY_OFFSET        3
95 #define BATT_SOC_WORD                   91
96 #define BATT_SOC_OFFSET                 0
97 #define FULL_SOC_WORD                   93
98 #define FULL_SOC_OFFSET                 2
99 #define MONOTONIC_SOC_WORD              94
100 #define MONOTONIC_SOC_OFFSET            2
101 #define CC_SOC_WORD                     95
102 #define CC_SOC_OFFSET                   0
103 #define CC_SOC_SW_WORD                  96
104 #define CC_SOC_SW_OFFSET                0
105 #define VOLTAGE_PRED_WORD               97
106 #define VOLTAGE_PRED_OFFSET             0
107 #define OCV_WORD                        97
108 #define OCV_OFFSET                      2
109 #define ESR_WORD                        99
110 #define ESR_OFFSET                      0
111 #define RSLOW_WORD                      101
112 #define RSLOW_OFFSET                    0
113 #define ACT_BATT_CAP_WORD               117
114 #define ACT_BATT_CAP_OFFSET             0
115 #define LAST_BATT_SOC_WORD              119
116 #define LAST_BATT_SOC_OFFSET            0
117 #define LAST_MONOTONIC_SOC_WORD         119
118 #define LAST_MONOTONIC_SOC_OFFSET       2
119 #define ALG_FLAGS_WORD                  120
120 #define ALG_FLAGS_OFFSET                1
121
122 /* v2 SRAM address and offset in ascending order */
123 #define KI_COEFF_LOW_DISCHG_v2_WORD     9
124 #define KI_COEFF_LOW_DISCHG_v2_OFFSET   3
125 #define KI_COEFF_MED_DISCHG_v2_WORD     10
126 #define KI_COEFF_MED_DISCHG_v2_OFFSET   0
127 #define KI_COEFF_HI_DISCHG_v2_WORD      10
128 #define KI_COEFF_HI_DISCHG_v2_OFFSET    1
129 #define DELTA_BSOC_THR_v2_WORD          12
130 #define DELTA_BSOC_THR_v2_OFFSET        3
131 #define DELTA_MSOC_THR_v2_WORD          13
132 #define DELTA_MSOC_THR_v2_OFFSET        0
133 #define RECHARGE_SOC_THR_v2_WORD        14
134 #define RECHARGE_SOC_THR_v2_OFFSET      1
135 #define CHG_TERM_CURR_v2_WORD           15
136 #define CHG_TERM_BASE_CURR_v2_OFFSET    0
137 #define CHG_TERM_CURR_v2_OFFSET         1
138 #define EMPTY_VOLT_v2_WORD              15
139 #define EMPTY_VOLT_v2_OFFSET            3
140 #define VBATT_LOW_v2_WORD               16
141 #define VBATT_LOW_v2_OFFSET             0
142 #define RECHARGE_VBATT_THR_v2_WORD      16
143 #define RECHARGE_VBATT_THR_v2_OFFSET    1
144 #define FLOAT_VOLT_v2_WORD              16
145 #define FLOAT_VOLT_v2_OFFSET            2
146
147 static int fg_decode_voltage_15b(struct fg_sram_param *sp,
148         enum fg_sram_param_id id, int val);
149 static int fg_decode_value_16b(struct fg_sram_param *sp,
150         enum fg_sram_param_id id, int val);
151 static int fg_decode_default(struct fg_sram_param *sp,
152         enum fg_sram_param_id id, int val);
153 static int fg_decode_cc_soc(struct fg_sram_param *sp,
154         enum fg_sram_param_id id, int value);
155 static void fg_encode_voltage(struct fg_sram_param *sp,
156         enum fg_sram_param_id id, int val_mv, u8 *buf);
157 static void fg_encode_current(struct fg_sram_param *sp,
158         enum fg_sram_param_id id, int val_ma, u8 *buf);
159 static void fg_encode_default(struct fg_sram_param *sp,
160         enum fg_sram_param_id id, int val, u8 *buf);
161
162 static struct fg_irq_info fg_irqs[FG_IRQ_MAX];
163
164 #define PARAM(_id, _addr_word, _addr_byte, _len, _num, _den, _offset,   \
165               _enc, _dec)                                               \
166         [FG_SRAM_##_id] = {                                             \
167                 .addr_word      = _addr_word,                           \
168                 .addr_byte      = _addr_byte,                           \
169                 .len            = _len,                                 \
170                 .numrtr         = _num,                                 \
171                 .denmtr         = _den,                                 \
172                 .offset         = _offset,                              \
173                 .encode         = _enc,                                 \
174                 .decode         = _dec,                                 \
175         }                                                               \
176
177 static struct fg_sram_param pmi8998_v1_sram_params[] = {
178         PARAM(BATT_SOC, BATT_SOC_WORD, BATT_SOC_OFFSET, 4, 1, 1, 0, NULL,
179                 fg_decode_default),
180         PARAM(FULL_SOC, FULL_SOC_WORD, FULL_SOC_OFFSET, 2, 1, 1, 0, NULL,
181                 fg_decode_default),
182         PARAM(VOLTAGE_PRED, VOLTAGE_PRED_WORD, VOLTAGE_PRED_OFFSET, 2, 1000,
183                 244141, 0, NULL, fg_decode_voltage_15b),
184         PARAM(OCV, OCV_WORD, OCV_OFFSET, 2, 1000, 244141, 0, NULL,
185                 fg_decode_voltage_15b),
186         PARAM(ESR, ESR_WORD, ESR_OFFSET, 2, 1000, 244141, 0, fg_encode_default,
187                 fg_decode_value_16b),
188         PARAM(RSLOW, RSLOW_WORD, RSLOW_OFFSET, 2, 1000, 244141, 0, NULL,
189                 fg_decode_value_16b),
190         PARAM(ALG_FLAGS, ALG_FLAGS_WORD, ALG_FLAGS_OFFSET, 1, 1, 1, 0, NULL,
191                 fg_decode_default),
192         PARAM(CC_SOC, CC_SOC_WORD, CC_SOC_OFFSET, 4, 1, 1, 0, NULL,
193                 fg_decode_cc_soc),
194         PARAM(CC_SOC_SW, CC_SOC_SW_WORD, CC_SOC_SW_OFFSET, 4, 1, 1, 0, NULL,
195                 fg_decode_cc_soc),
196         PARAM(ACT_BATT_CAP, ACT_BATT_CAP_BKUP_WORD, ACT_BATT_CAP_BKUP_OFFSET, 2,
197                 1, 1, 0, NULL, fg_decode_default),
198         /* Entries below here are configurable during initialization */
199         PARAM(CUTOFF_VOLT, CUTOFF_VOLT_WORD, CUTOFF_VOLT_OFFSET, 2, 1000000,
200                 244141, 0, fg_encode_voltage, NULL),
201         PARAM(EMPTY_VOLT, EMPTY_VOLT_WORD, EMPTY_VOLT_OFFSET, 1, 100000, 390625,
202                 -2500, fg_encode_voltage, NULL),
203         PARAM(VBATT_LOW, VBATT_LOW_WORD, VBATT_LOW_OFFSET, 1, 100000, 390625,
204                 -2500, fg_encode_voltage, NULL),
205         PARAM(VBATT_FULL, VBATT_FULL_WORD, VBATT_FULL_OFFSET, 2, 1000,
206                 244141, 0, fg_encode_voltage, fg_decode_voltage_15b),
207         PARAM(SYS_TERM_CURR, SYS_TERM_CURR_WORD, SYS_TERM_CURR_OFFSET, 3,
208                 1000000, 122070, 0, fg_encode_current, NULL),
209         PARAM(CHG_TERM_CURR, CHG_TERM_CURR_WORD, CHG_TERM_CURR_OFFSET, 1,
210                 100000, 390625, 0, fg_encode_current, NULL),
211         PARAM(DELTA_MSOC_THR, DELTA_MSOC_THR_WORD, DELTA_MSOC_THR_OFFSET, 1,
212                 2048, 100, 0, fg_encode_default, NULL),
213         PARAM(DELTA_BSOC_THR, DELTA_BSOC_THR_WORD, DELTA_BSOC_THR_OFFSET, 1,
214                 2048, 100, 0, fg_encode_default, NULL),
215         PARAM(RECHARGE_SOC_THR, RECHARGE_SOC_THR_WORD, RECHARGE_SOC_THR_OFFSET,
216                 1, 256, 100, 0, fg_encode_default, NULL),
217         PARAM(ESR_TIMER_DISCHG_MAX, ESR_TIMER_DISCHG_MAX_WORD,
218                 ESR_TIMER_DISCHG_MAX_OFFSET, 2, 1, 1, 0, fg_encode_default,
219                 NULL),
220         PARAM(ESR_TIMER_DISCHG_INIT, ESR_TIMER_DISCHG_INIT_WORD,
221                 ESR_TIMER_DISCHG_INIT_OFFSET, 2, 1, 1, 0, fg_encode_default,
222                 NULL),
223         PARAM(ESR_TIMER_CHG_MAX, ESR_TIMER_CHG_MAX_WORD,
224                 ESR_TIMER_CHG_MAX_OFFSET, 2, 1, 1, 0, fg_encode_default, NULL),
225         PARAM(ESR_TIMER_CHG_INIT, ESR_TIMER_CHG_INIT_WORD,
226                 ESR_TIMER_CHG_INIT_OFFSET, 2, 1, 1, 0, fg_encode_default, NULL),
227         PARAM(ESR_PULSE_THRESH, ESR_PULSE_THRESH_WORD, ESR_PULSE_THRESH_OFFSET,
228                 1, 100000, 390625, 0, fg_encode_default, NULL),
229         PARAM(KI_COEFF_MED_DISCHG, KI_COEFF_MED_DISCHG_WORD,
230                 KI_COEFF_MED_DISCHG_OFFSET, 1, 1000, 244141, 0,
231                 fg_encode_default, NULL),
232         PARAM(KI_COEFF_HI_DISCHG, KI_COEFF_HI_DISCHG_WORD,
233                 KI_COEFF_HI_DISCHG_OFFSET, 1, 1000, 244141, 0,
234                 fg_encode_default, NULL),
235         PARAM(KI_COEFF_FULL_SOC, KI_COEFF_FULL_SOC_WORD,
236                 KI_COEFF_FULL_SOC_OFFSET, 1, 1000, 244141, 0,
237                 fg_encode_default, NULL),
238         PARAM(ESR_TIGHT_FILTER, ESR_FILTER_WORD, ESR_UPD_TIGHT_OFFSET,
239                 1, 512, 1000000, 0, fg_encode_default, NULL),
240         PARAM(ESR_BROAD_FILTER, ESR_FILTER_WORD, ESR_UPD_BROAD_OFFSET,
241                 1, 512, 1000000, 0, fg_encode_default, NULL),
242         PARAM(SLOPE_LIMIT, SLOPE_LIMIT_WORD, SLOPE_LIMIT_OFFSET, 1, 8192, 1000,
243                 0, fg_encode_default, NULL),
244 };
245
246 static struct fg_sram_param pmi8998_v2_sram_params[] = {
247         PARAM(BATT_SOC, BATT_SOC_WORD, BATT_SOC_OFFSET, 4, 1, 1, 0, NULL,
248                 fg_decode_default),
249         PARAM(FULL_SOC, FULL_SOC_WORD, FULL_SOC_OFFSET, 2, 1, 1, 0, NULL,
250                 fg_decode_default),
251         PARAM(VOLTAGE_PRED, VOLTAGE_PRED_WORD, VOLTAGE_PRED_OFFSET, 2, 1000,
252                 244141, 0, NULL, fg_decode_voltage_15b),
253         PARAM(OCV, OCV_WORD, OCV_OFFSET, 2, 1000, 244141, 0, NULL,
254                 fg_decode_voltage_15b),
255         PARAM(ESR, ESR_WORD, ESR_OFFSET, 2, 1000, 244141, 0, fg_encode_default,
256                 fg_decode_value_16b),
257         PARAM(RSLOW, RSLOW_WORD, RSLOW_OFFSET, 2, 1000, 244141, 0, NULL,
258                 fg_decode_value_16b),
259         PARAM(ALG_FLAGS, ALG_FLAGS_WORD, ALG_FLAGS_OFFSET, 1, 1, 1, 0, NULL,
260                 fg_decode_default),
261         PARAM(CC_SOC, CC_SOC_WORD, CC_SOC_OFFSET, 4, 1, 1, 0, NULL,
262                 fg_decode_cc_soc),
263         PARAM(CC_SOC_SW, CC_SOC_SW_WORD, CC_SOC_SW_OFFSET, 4, 1, 1, 0, NULL,
264                 fg_decode_cc_soc),
265         PARAM(ACT_BATT_CAP, ACT_BATT_CAP_BKUP_WORD, ACT_BATT_CAP_BKUP_OFFSET, 2,
266                 1, 1, 0, NULL, fg_decode_default),
267         PARAM(TIMEBASE, KI_COEFF_MED_DISCHG_WORD, TIMEBASE_OFFSET, 2, 1000,
268                 61000, 0, fg_encode_default, NULL),
269         /* Entries below here are configurable during initialization */
270         PARAM(CUTOFF_VOLT, CUTOFF_VOLT_WORD, CUTOFF_VOLT_OFFSET, 2, 1000000,
271                 244141, 0, fg_encode_voltage, NULL),
272         PARAM(EMPTY_VOLT, EMPTY_VOLT_v2_WORD, EMPTY_VOLT_v2_OFFSET, 1, 1000,
273                 15625, -2000, fg_encode_voltage, NULL),
274         PARAM(VBATT_LOW, VBATT_LOW_v2_WORD, VBATT_LOW_v2_OFFSET, 1, 1000,
275                 15625, -2000, fg_encode_voltage, NULL),
276         PARAM(FLOAT_VOLT, FLOAT_VOLT_v2_WORD, FLOAT_VOLT_v2_OFFSET, 1, 1000,
277                 15625, -2000, fg_encode_voltage, NULL),
278         PARAM(VBATT_FULL, VBATT_FULL_WORD, VBATT_FULL_OFFSET, 2, 1000,
279                 244141, 0, fg_encode_voltage, fg_decode_voltage_15b),
280         PARAM(SYS_TERM_CURR, SYS_TERM_CURR_WORD, SYS_TERM_CURR_OFFSET, 3,
281                 1000000, 122070, 0, fg_encode_current, NULL),
282         PARAM(CHG_TERM_CURR, CHG_TERM_CURR_v2_WORD, CHG_TERM_CURR_v2_OFFSET, 1,
283                 100000, 390625, 0, fg_encode_current, NULL),
284         PARAM(CHG_TERM_BASE_CURR, CHG_TERM_CURR_v2_WORD,
285                 CHG_TERM_BASE_CURR_v2_OFFSET, 1, 1024, 1000, 0,
286                 fg_encode_current, NULL),
287         PARAM(DELTA_MSOC_THR, DELTA_MSOC_THR_v2_WORD, DELTA_MSOC_THR_v2_OFFSET,
288                 1, 2048, 100, 0, fg_encode_default, NULL),
289         PARAM(DELTA_BSOC_THR, DELTA_BSOC_THR_v2_WORD, DELTA_BSOC_THR_v2_OFFSET,
290                 1, 2048, 100, 0, fg_encode_default, NULL),
291         PARAM(RECHARGE_SOC_THR, RECHARGE_SOC_THR_v2_WORD,
292                 RECHARGE_SOC_THR_v2_OFFSET, 1, 256, 100, 0, fg_encode_default,
293                 NULL),
294         PARAM(RECHARGE_VBATT_THR, RECHARGE_VBATT_THR_v2_WORD,
295                 RECHARGE_VBATT_THR_v2_OFFSET, 1, 1000, 15625, -2000,
296                 fg_encode_voltage, NULL),
297         PARAM(ESR_TIMER_DISCHG_MAX, ESR_TIMER_DISCHG_MAX_WORD,
298                 ESR_TIMER_DISCHG_MAX_OFFSET, 2, 1, 1, 0, fg_encode_default,
299                 NULL),
300         PARAM(ESR_TIMER_DISCHG_INIT, ESR_TIMER_DISCHG_INIT_WORD,
301                 ESR_TIMER_DISCHG_INIT_OFFSET, 2, 1, 1, 0, fg_encode_default,
302                 NULL),
303         PARAM(ESR_TIMER_CHG_MAX, ESR_TIMER_CHG_MAX_WORD,
304                 ESR_TIMER_CHG_MAX_OFFSET, 2, 1, 1, 0, fg_encode_default, NULL),
305         PARAM(ESR_TIMER_CHG_INIT, ESR_TIMER_CHG_INIT_WORD,
306                 ESR_TIMER_CHG_INIT_OFFSET, 2, 1, 1, 0, fg_encode_default, NULL),
307         PARAM(ESR_PULSE_THRESH, ESR_PULSE_THRESH_WORD, ESR_PULSE_THRESH_OFFSET,
308                 1, 100000, 390625, 0, fg_encode_default, NULL),
309         PARAM(KI_COEFF_MED_DISCHG, KI_COEFF_MED_DISCHG_v2_WORD,
310                 KI_COEFF_MED_DISCHG_v2_OFFSET, 1, 1000, 244141, 0,
311                 fg_encode_default, NULL),
312         PARAM(KI_COEFF_HI_DISCHG, KI_COEFF_HI_DISCHG_v2_WORD,
313                 KI_COEFF_HI_DISCHG_v2_OFFSET, 1, 1000, 244141, 0,
314                 fg_encode_default, NULL),
315         PARAM(KI_COEFF_FULL_SOC, KI_COEFF_FULL_SOC_WORD,
316                 KI_COEFF_FULL_SOC_OFFSET, 1, 1000, 244141, 0,
317                 fg_encode_default, NULL),
318         PARAM(ESR_TIGHT_FILTER, ESR_FILTER_WORD, ESR_UPD_TIGHT_OFFSET,
319                 1, 512, 1000000, 0, fg_encode_default, NULL),
320         PARAM(ESR_BROAD_FILTER, ESR_FILTER_WORD, ESR_UPD_BROAD_OFFSET,
321                 1, 512, 1000000, 0, fg_encode_default, NULL),
322         PARAM(SLOPE_LIMIT, SLOPE_LIMIT_WORD, SLOPE_LIMIT_OFFSET, 1, 8192, 1000,
323                 0, fg_encode_default, NULL),
324 };
325
326 static struct fg_alg_flag pmi8998_v1_alg_flags[] = {
327         [ALG_FLAG_SOC_LT_OTG_MIN]       = {
328                 .name   = "SOC_LT_OTG_MIN",
329                 .bit    = BIT(0),
330         },
331         [ALG_FLAG_SOC_LT_RECHARGE]      = {
332                 .name   = "SOC_LT_RECHARGE",
333                 .bit    = BIT(1),
334         },
335         [ALG_FLAG_IBATT_LT_ITERM]       = {
336                 .name   = "IBATT_LT_ITERM",
337                 .bit    = BIT(2),
338         },
339         [ALG_FLAG_IBATT_GT_HPM]         = {
340                 .name   = "IBATT_GT_HPM",
341                 .bit    = BIT(3),
342         },
343         [ALG_FLAG_IBATT_GT_UPM]         = {
344                 .name   = "IBATT_GT_UPM",
345                 .bit    = BIT(4),
346         },
347         [ALG_FLAG_VBATT_LT_RECHARGE]    = {
348                 .name   = "VBATT_LT_RECHARGE",
349                 .bit    = BIT(5),
350         },
351         [ALG_FLAG_VBATT_GT_VFLOAT]      = {
352                 .invalid = true,
353         },
354 };
355
356 static struct fg_alg_flag pmi8998_v2_alg_flags[] = {
357         [ALG_FLAG_SOC_LT_OTG_MIN]       = {
358                 .name   = "SOC_LT_OTG_MIN",
359                 .bit    = BIT(0),
360         },
361         [ALG_FLAG_SOC_LT_RECHARGE]      = {
362                 .name   = "SOC_LT_RECHARGE",
363                 .bit    = BIT(1),
364         },
365         [ALG_FLAG_IBATT_LT_ITERM]       = {
366                 .name   = "IBATT_LT_ITERM",
367                 .bit    = BIT(2),
368         },
369         [ALG_FLAG_IBATT_GT_HPM]         = {
370                 .name   = "IBATT_GT_HPM",
371                 .bit    = BIT(4),
372         },
373         [ALG_FLAG_IBATT_GT_UPM]         = {
374                 .name   = "IBATT_GT_UPM",
375                 .bit    = BIT(5),
376         },
377         [ALG_FLAG_VBATT_LT_RECHARGE]    = {
378                 .name   = "VBATT_LT_RECHARGE",
379                 .bit    = BIT(6),
380         },
381         [ALG_FLAG_VBATT_GT_VFLOAT]      = {
382                 .name   = "VBATT_GT_VFLOAT",
383                 .bit    = BIT(7),
384         },
385 };
386
387 static int fg_gen3_debug_mask;
388 module_param_named(
389         debug_mask, fg_gen3_debug_mask, int, S_IRUSR | S_IWUSR
390 );
391
392 static bool fg_profile_dump;
393 module_param_named(
394         profile_dump, fg_profile_dump, bool, S_IRUSR | S_IWUSR
395 );
396
397 static int fg_sram_dump_period_ms = 20000;
398 module_param_named(
399         sram_dump_period_ms, fg_sram_dump_period_ms, int, S_IRUSR | S_IWUSR
400 );
401
402 static int fg_restart;
403 static bool fg_sram_dump;
404
405 /* All getters HERE */
406
407 #define VOLTAGE_15BIT_MASK      GENMASK(14, 0)
408 static int fg_decode_voltage_15b(struct fg_sram_param *sp,
409                                 enum fg_sram_param_id id, int value)
410 {
411         value &= VOLTAGE_15BIT_MASK;
412         sp[id].value = div_u64((u64)value * sp[id].denmtr, sp[id].numrtr);
413         pr_debug("id: %d raw value: %x decoded value: %x\n", id, value,
414                 sp[id].value);
415         return sp[id].value;
416 }
417
418 static int fg_decode_cc_soc(struct fg_sram_param *sp,
419                                 enum fg_sram_param_id id, int value)
420 {
421         sp[id].value = div_s64((s64)value * sp[id].denmtr, sp[id].numrtr);
422         sp[id].value = sign_extend32(sp[id].value, 31);
423         pr_debug("id: %d raw value: %x decoded value: %x\n", id, value,
424                 sp[id].value);
425         return sp[id].value;
426 }
427
428 static int fg_decode_value_16b(struct fg_sram_param *sp,
429                                 enum fg_sram_param_id id, int value)
430 {
431         sp[id].value = div_u64((u64)(u16)value * sp[id].denmtr, sp[id].numrtr);
432         pr_debug("id: %d raw value: %x decoded value: %x\n", id, value,
433                 sp[id].value);
434         return sp[id].value;
435 }
436
437 static int fg_decode_default(struct fg_sram_param *sp, enum fg_sram_param_id id,
438                                 int value)
439 {
440         sp[id].value = value;
441         return sp[id].value;
442 }
443
444 static int fg_decode(struct fg_sram_param *sp, enum fg_sram_param_id id,
445                         int value)
446 {
447         if (!sp[id].decode) {
448                 pr_err("No decoding function for parameter %d\n", id);
449                 return -EINVAL;
450         }
451
452         return sp[id].decode(sp, id, value);
453 }
454
455 static void fg_encode_voltage(struct fg_sram_param *sp,
456                                 enum fg_sram_param_id  id, int val_mv, u8 *buf)
457 {
458         int i, mask = 0xff;
459         int64_t temp;
460
461         val_mv += sp[id].offset;
462         temp = (int64_t)div_u64((u64)val_mv * sp[id].numrtr, sp[id].denmtr);
463         pr_debug("temp: %llx id: %d, val_mv: %d, buf: [ ", temp, id, val_mv);
464         for (i = 0; i < sp[id].len; i++) {
465                 buf[i] = temp & mask;
466                 temp >>= 8;
467                 pr_debug("%x ", buf[i]);
468         }
469         pr_debug("]\n");
470 }
471
472 static void fg_encode_current(struct fg_sram_param *sp,
473                                 enum fg_sram_param_id  id, int val_ma, u8 *buf)
474 {
475         int i, mask = 0xff;
476         int64_t temp;
477         s64 current_ma;
478
479         current_ma = val_ma;
480         temp = (int64_t)div_s64(current_ma * sp[id].numrtr, sp[id].denmtr);
481         pr_debug("temp: %llx id: %d, val: %d, buf: [ ", temp, id, val_ma);
482         for (i = 0; i < sp[id].len; i++) {
483                 buf[i] = temp & mask;
484                 temp >>= 8;
485                 pr_debug("%x ", buf[i]);
486         }
487         pr_debug("]\n");
488 }
489
490 static void fg_encode_default(struct fg_sram_param *sp,
491                                 enum fg_sram_param_id  id, int val, u8 *buf)
492 {
493         int i, mask = 0xff;
494         int64_t temp;
495
496         temp = (int64_t)div_s64((s64)val * sp[id].numrtr, sp[id].denmtr);
497         pr_debug("temp: %llx id: %d, val: %d, buf: [ ", temp, id, val);
498         for (i = 0; i < sp[id].len; i++) {
499                 buf[i] = temp & mask;
500                 temp >>= 8;
501                 pr_debug("%x ", buf[i]);
502         }
503         pr_debug("]\n");
504 }
505
506 static void fg_encode(struct fg_sram_param *sp, enum fg_sram_param_id id,
507                         int val, u8 *buf)
508 {
509         if (!sp[id].encode) {
510                 pr_err("No encoding function for parameter %d\n", id);
511                 return;
512         }
513
514         sp[id].encode(sp, id, val, buf);
515 }
516
517 /*
518  * Please make sure *_sram_params table has the entry for the parameter
519  * obtained through this function. In addition to address, offset,
520  * length from where this SRAM parameter is read, a decode function
521  * need to be specified.
522  */
523 static int fg_get_sram_prop(struct fg_chip *chip, enum fg_sram_param_id id,
524                                 int *val)
525 {
526         int temp, rc, i;
527         u8 buf[4];
528
529         if (id < 0 || id > FG_SRAM_MAX || chip->sp[id].len > sizeof(buf))
530                 return -EINVAL;
531
532         if (chip->battery_missing)
533                 return -ENODATA;
534
535         rc = fg_sram_read(chip, chip->sp[id].addr_word, chip->sp[id].addr_byte,
536                 buf, chip->sp[id].len, FG_IMA_DEFAULT);
537         if (rc < 0) {
538                 pr_err("Error reading address 0x%04x[%d] rc=%d\n",
539                         chip->sp[id].addr_word, chip->sp[id].addr_byte, rc);
540                 return rc;
541         }
542
543         for (i = 0, temp = 0; i < chip->sp[id].len; i++)
544                 temp |= buf[i] << (8 * i);
545
546         *val = fg_decode(chip->sp, id, temp);
547         return 0;
548 }
549
550 #define CC_SOC_30BIT    GENMASK(29, 0)
551 static int fg_get_charge_raw(struct fg_chip *chip, int *val)
552 {
553         int rc, cc_soc;
554
555         rc = fg_get_sram_prop(chip, FG_SRAM_CC_SOC, &cc_soc);
556         if (rc < 0) {
557                 pr_err("Error in getting CC_SOC, rc=%d\n", rc);
558                 return rc;
559         }
560
561         *val = div_s64(cc_soc * chip->cl.nom_cap_uah, CC_SOC_30BIT);
562         return 0;
563 }
564
565 static int fg_get_charge_counter(struct fg_chip *chip, int *val)
566 {
567         int rc, cc_soc;
568
569         rc = fg_get_sram_prop(chip, FG_SRAM_CC_SOC_SW, &cc_soc);
570         if (rc < 0) {
571                 pr_err("Error in getting CC_SOC_SW, rc=%d\n", rc);
572                 return rc;
573         }
574
575         *val = div_s64(cc_soc * chip->cl.learned_cc_uah, CC_SOC_30BIT);
576         return 0;
577 }
578
579 static int fg_get_jeita_threshold(struct fg_chip *chip,
580                                 enum jeita_levels level, int *temp_decidegC)
581 {
582         int rc;
583         u8 val;
584         u16 reg;
585
586         switch (level) {
587         case JEITA_COLD:
588                 reg = BATT_INFO_JEITA_TOO_COLD(chip);
589                 break;
590         case JEITA_COOL:
591                 reg = BATT_INFO_JEITA_COLD(chip);
592                 break;
593         case JEITA_WARM:
594                 reg = BATT_INFO_JEITA_HOT(chip);
595                 break;
596         case JEITA_HOT:
597                 reg = BATT_INFO_JEITA_TOO_HOT(chip);
598                 break;
599         default:
600                 return -EINVAL;
601         }
602
603         rc = fg_read(chip, reg, &val, 1);
604         if (rc < 0) {
605                 pr_err("Error in reading jeita level %d, rc=%d\n", level, rc);
606                 return rc;
607         }
608
609         /* Resolution is 0.5C. Base is -30C. */
610         *temp_decidegC = (((5 * val) / 10) - 30) * 10;
611         return 0;
612 }
613
614 #define BATT_TEMP_NUMR          1
615 #define BATT_TEMP_DENR          1
616 static int fg_get_battery_temp(struct fg_chip *chip, int *val)
617 {
618         int rc = 0, temp;
619         u8 buf[2];
620
621         rc = fg_read(chip, BATT_INFO_BATT_TEMP_LSB(chip), buf, 2);
622         if (rc < 0) {
623                 pr_err("failed to read addr=0x%04x, rc=%d\n",
624                         BATT_INFO_BATT_TEMP_LSB(chip), rc);
625                 return rc;
626         }
627
628         temp = ((buf[1] & BATT_TEMP_MSB_MASK) << 8) |
629                 (buf[0] & BATT_TEMP_LSB_MASK);
630         temp = DIV_ROUND_CLOSEST(temp, 4);
631
632         /* Value is in Kelvin; Convert it to deciDegC */
633         temp = (temp - 273) * 10;
634         *val = temp;
635         return 0;
636 }
637
638 static int fg_get_battery_resistance(struct fg_chip *chip, int *val)
639 {
640         int rc, esr_uohms, rslow_uohms;
641
642         rc = fg_get_sram_prop(chip, FG_SRAM_ESR, &esr_uohms);
643         if (rc < 0) {
644                 pr_err("failed to get ESR, rc=%d\n", rc);
645                 return rc;
646         }
647
648         rc = fg_get_sram_prop(chip, FG_SRAM_RSLOW, &rslow_uohms);
649         if (rc < 0) {
650                 pr_err("failed to get Rslow, rc=%d\n", rc);
651                 return rc;
652         }
653
654         *val = esr_uohms + rslow_uohms;
655         return 0;
656 }
657
658 #define BATT_CURRENT_NUMR       488281
659 #define BATT_CURRENT_DENR       1000
660 static int fg_get_battery_current(struct fg_chip *chip, int *val)
661 {
662         int rc = 0;
663         int64_t temp = 0;
664         u8 buf[2];
665
666         rc = fg_read(chip, BATT_INFO_IBATT_LSB(chip), buf, 2);
667         if (rc < 0) {
668                 pr_err("failed to read addr=0x%04x, rc=%d\n",
669                         BATT_INFO_IBATT_LSB(chip), rc);
670                 return rc;
671         }
672
673         if (chip->wa_flags & PMI8998_V1_REV_WA)
674                 temp = buf[0] << 8 | buf[1];
675         else
676                 temp = buf[1] << 8 | buf[0];
677
678         pr_debug("buf: %x %x temp: %llx\n", buf[0], buf[1], temp);
679         /* Sign bit is bit 15 */
680         temp = twos_compliment_extend(temp, 15);
681         *val = div_s64((s64)temp * BATT_CURRENT_NUMR, BATT_CURRENT_DENR);
682         return 0;
683 }
684
685 #define BATT_VOLTAGE_NUMR       122070
686 #define BATT_VOLTAGE_DENR       1000
687 static int fg_get_battery_voltage(struct fg_chip *chip, int *val)
688 {
689         int rc = 0;
690         u16 temp = 0;
691         u8 buf[2];
692
693         rc = fg_read(chip, BATT_INFO_VBATT_LSB(chip), buf, 2);
694         if (rc < 0) {
695                 pr_err("failed to read addr=0x%04x, rc=%d\n",
696                         BATT_INFO_VBATT_LSB(chip), rc);
697                 return rc;
698         }
699
700         if (chip->wa_flags & PMI8998_V1_REV_WA)
701                 temp = buf[0] << 8 | buf[1];
702         else
703                 temp = buf[1] << 8 | buf[0];
704
705         pr_debug("buf: %x %x temp: %x\n", buf[0], buf[1], temp);
706         *val = div_u64((u64)temp * BATT_VOLTAGE_NUMR, BATT_VOLTAGE_DENR);
707         return 0;
708 }
709
710 #define MAX_TRIES_SOC           5
711 static int fg_get_msoc_raw(struct fg_chip *chip, int *val)
712 {
713         u8 cap[2];
714         int rc, tries = 0;
715
716         while (tries < MAX_TRIES_SOC) {
717                 rc = fg_read(chip, BATT_SOC_FG_MONOTONIC_SOC(chip), cap, 2);
718                 if (rc < 0) {
719                         pr_err("failed to read addr=0x%04x, rc=%d\n",
720                                 BATT_SOC_FG_MONOTONIC_SOC(chip), rc);
721                         return rc;
722                 }
723
724                 if (cap[0] == cap[1])
725                         break;
726
727                 tries++;
728         }
729
730         if (tries == MAX_TRIES_SOC) {
731                 pr_err("shadow registers do not match\n");
732                 return -EINVAL;
733         }
734
735         fg_dbg(chip, FG_POWER_SUPPLY, "raw: 0x%02x\n", cap[0]);
736         *val = cap[0];
737         return 0;
738 }
739
740 #define FULL_CAPACITY   100
741 #define FULL_SOC_RAW    255
742 static int fg_get_msoc(struct fg_chip *chip, int *msoc)
743 {
744         int rc;
745
746         rc = fg_get_msoc_raw(chip, msoc);
747         if (rc < 0)
748                 return rc;
749
750         *msoc = DIV_ROUND_CLOSEST(*msoc * FULL_CAPACITY, FULL_SOC_RAW);
751         return 0;
752 }
753
754 static bool is_batt_empty(struct fg_chip *chip)
755 {
756         u8 status;
757         int rc, vbatt_uv, msoc;
758
759         rc = fg_read(chip, BATT_SOC_INT_RT_STS(chip), &status, 1);
760         if (rc < 0) {
761                 pr_err("failed to read addr=0x%04x, rc=%d\n",
762                         BATT_SOC_INT_RT_STS(chip), rc);
763                 return false;
764         }
765
766         if (!(status & MSOC_EMPTY_BIT))
767                 return false;
768
769         rc = fg_get_battery_voltage(chip, &vbatt_uv);
770         if (rc < 0) {
771                 pr_err("failed to get battery voltage, rc=%d\n", rc);
772                 return false;
773         }
774
775         rc = fg_get_msoc(chip, &msoc);
776         if (!rc)
777                 pr_warn("batt_soc_rt_sts: %x vbatt: %d uV msoc:%d\n", status,
778                         vbatt_uv, msoc);
779
780         return ((vbatt_uv < chip->dt.cutoff_volt_mv * 1000) ? true : false);
781 }
782
783 static int fg_get_debug_batt_id(struct fg_chip *chip, int *batt_id)
784 {
785         int rc;
786         u64 temp;
787         u8 buf[2];
788
789         rc = fg_read(chip, ADC_RR_FAKE_BATT_LOW_LSB(chip), buf, 2);
790         if (rc < 0) {
791                 pr_err("failed to read addr=0x%04x, rc=%d\n",
792                         ADC_RR_FAKE_BATT_LOW_LSB(chip), rc);
793                 return rc;
794         }
795
796         /*
797          * Fake battery threshold is encoded in the following format.
798          * Threshold (code) = (battery_id in Ohms) * 0.00015 * 2^10 / 2.5
799          */
800         temp = (buf[1] << 8 | buf[0]) * 2500000;
801         do_div(temp, 150 * 1024);
802         batt_id[0] = temp;
803         rc = fg_read(chip, ADC_RR_FAKE_BATT_HIGH_LSB(chip), buf, 2);
804         if (rc < 0) {
805                 pr_err("failed to read addr=0x%04x, rc=%d\n",
806                         ADC_RR_FAKE_BATT_HIGH_LSB(chip), rc);
807                 return rc;
808         }
809
810         temp = (buf[1] << 8 | buf[0]) * 2500000;
811         do_div(temp, 150 * 1024);
812         batt_id[1] = temp;
813         pr_debug("debug batt_id range: [%d %d]\n", batt_id[0], batt_id[1]);
814         return 0;
815 }
816
817 static bool is_debug_batt_id(struct fg_chip *chip)
818 {
819         int debug_batt_id[2], rc;
820
821         if (!chip->batt_id_ohms)
822                 return false;
823
824         rc = fg_get_debug_batt_id(chip, debug_batt_id);
825         if (rc < 0) {
826                 pr_err("Failed to get debug batt_id, rc=%d\n", rc);
827                 return false;
828         }
829
830         if (is_between(debug_batt_id[0], debug_batt_id[1],
831                 chip->batt_id_ohms)) {
832                 fg_dbg(chip, FG_POWER_SUPPLY, "Debug battery id: %dohms\n",
833                         chip->batt_id_ohms);
834                 return true;
835         }
836
837         return false;
838 }
839
840 #define DEBUG_BATT_SOC  67
841 #define BATT_MISS_SOC   50
842 #define EMPTY_SOC       0
843 static int fg_get_prop_capacity(struct fg_chip *chip, int *val)
844 {
845         int rc, msoc;
846
847         if (is_debug_batt_id(chip)) {
848                 *val = DEBUG_BATT_SOC;
849                 return 0;
850         }
851
852         if (chip->fg_restarting) {
853                 *val = chip->last_soc;
854                 return 0;
855         }
856
857         if (chip->battery_missing) {
858                 *val = BATT_MISS_SOC;
859                 return 0;
860         }
861
862         if (is_batt_empty(chip)) {
863                 *val = EMPTY_SOC;
864                 return 0;
865         }
866
867         if (chip->charge_full) {
868                 *val = FULL_CAPACITY;
869                 return 0;
870         }
871
872         rc = fg_get_msoc(chip, &msoc);
873         if (rc < 0)
874                 return rc;
875
876         if (chip->dt.linearize_soc && chip->delta_soc > 0)
877                 *val = chip->maint_soc;
878         else
879                 *val = msoc;
880         return 0;
881 }
882
883 #define DEFAULT_BATT_TYPE       "Unknown Battery"
884 #define MISSING_BATT_TYPE       "Missing Battery"
885 #define LOADING_BATT_TYPE       "Loading Battery"
886 static const char *fg_get_battery_type(struct fg_chip *chip)
887 {
888         if (chip->battery_missing)
889                 return MISSING_BATT_TYPE;
890
891         if (chip->bp.batt_type_str) {
892                 if (chip->profile_loaded)
893                         return chip->bp.batt_type_str;
894                 else if (chip->profile_available)
895                         return LOADING_BATT_TYPE;
896         }
897
898         return DEFAULT_BATT_TYPE;
899 }
900
901 static int fg_batt_missing_config(struct fg_chip *chip, bool enable)
902 {
903         int rc;
904
905         rc = fg_masked_write(chip, BATT_INFO_BATT_MISS_CFG(chip),
906                         BM_FROM_BATT_ID_BIT, enable ? BM_FROM_BATT_ID_BIT : 0);
907         if (rc < 0)
908                 pr_err("Error in writing to %04x, rc=%d\n",
909                         BATT_INFO_BATT_MISS_CFG(chip), rc);
910         return rc;
911 }
912
913 static int fg_get_batt_id(struct fg_chip *chip)
914 {
915         int rc, ret, batt_id = 0;
916
917         if (!chip->batt_id_chan)
918                 return -EINVAL;
919
920         rc = fg_batt_missing_config(chip, false);
921         if (rc < 0) {
922                 pr_err("Error in disabling BMD, rc=%d\n", rc);
923                 return rc;
924         }
925
926         rc = iio_read_channel_processed(chip->batt_id_chan, &batt_id);
927         if (rc < 0) {
928                 pr_err("Error in reading batt_id channel, rc:%d\n", rc);
929                 goto out;
930         }
931
932         /* Wait for 200ms before enabling BMD again */
933         msleep(200);
934
935         fg_dbg(chip, FG_STATUS, "batt_id: %d\n", batt_id);
936         chip->batt_id_ohms = batt_id;
937 out:
938         ret = fg_batt_missing_config(chip, true);
939         if (ret < 0) {
940                 pr_err("Error in enabling BMD, ret=%d\n", ret);
941                 return ret;
942         }
943
944         vote(chip->batt_miss_irq_en_votable, BATT_MISS_IRQ_VOTER, true, 0);
945         return rc;
946 }
947
948 static int fg_get_batt_profile(struct fg_chip *chip)
949 {
950         struct device_node *node = chip->dev->of_node;
951         struct device_node *batt_node, *profile_node;
952         const char *data;
953         int rc, len;
954
955         batt_node = of_find_node_by_name(node, "qcom,battery-data");
956         if (!batt_node) {
957                 pr_err("Batterydata not available\n");
958                 return -ENXIO;
959         }
960
961         profile_node = of_batterydata_get_best_profile(batt_node,
962                                 chip->batt_id_ohms / 1000, NULL);
963         if (IS_ERR(profile_node))
964                 return PTR_ERR(profile_node);
965
966         if (!profile_node) {
967                 pr_err("couldn't find profile handle\n");
968                 return -ENODATA;
969         }
970
971         rc = of_property_read_string(profile_node, "qcom,battery-type",
972                         &chip->bp.batt_type_str);
973         if (rc < 0) {
974                 pr_err("battery type unavailable, rc:%d\n", rc);
975                 return rc;
976         }
977
978         rc = of_property_read_u32(profile_node, "qcom,max-voltage-uv",
979                         &chip->bp.float_volt_uv);
980         if (rc < 0) {
981                 pr_err("battery float voltage unavailable, rc:%d\n", rc);
982                 chip->bp.float_volt_uv = -EINVAL;
983         }
984
985         rc = of_property_read_u32(profile_node, "qcom,fastchg-current-ma",
986                         &chip->bp.fastchg_curr_ma);
987         if (rc < 0) {
988                 pr_err("battery fastchg current unavailable, rc:%d\n", rc);
989                 chip->bp.fastchg_curr_ma = -EINVAL;
990         }
991
992         rc = of_property_read_u32(profile_node, "qcom,fg-cc-cv-threshold-mv",
993                         &chip->bp.vbatt_full_mv);
994         if (rc < 0) {
995                 pr_err("battery cc_cv threshold unavailable, rc:%d\n", rc);
996                 chip->bp.vbatt_full_mv = -EINVAL;
997         }
998
999         data = of_get_property(profile_node, "qcom,fg-profile-data", &len);
1000         if (!data) {
1001                 pr_err("No profile data available\n");
1002                 return -ENODATA;
1003         }
1004
1005         if (len != PROFILE_LEN) {
1006                 pr_err("battery profile incorrect size: %d\n", len);
1007                 return -EINVAL;
1008         }
1009
1010         chip->profile_available = true;
1011         memcpy(chip->batt_profile, data, len);
1012
1013         return 0;
1014 }
1015
1016 static inline void get_batt_temp_delta(int delta, u8 *val)
1017 {
1018         switch (delta) {
1019         case 2:
1020                 *val = BTEMP_DELTA_2K;
1021                 break;
1022         case 4:
1023                 *val = BTEMP_DELTA_4K;
1024                 break;
1025         case 6:
1026                 *val = BTEMP_DELTA_6K;
1027                 break;
1028         case 10:
1029                 *val = BTEMP_DELTA_10K;
1030                 break;
1031         default:
1032                 *val = BTEMP_DELTA_2K;
1033                 break;
1034         };
1035 }
1036
1037 static inline void get_esr_meas_current(int curr_ma, u8 *val)
1038 {
1039         switch (curr_ma) {
1040         case 60:
1041                 *val = ESR_MEAS_CUR_60MA;
1042                 break;
1043         case 120:
1044                 *val = ESR_MEAS_CUR_120MA;
1045                 break;
1046         case 180:
1047                 *val = ESR_MEAS_CUR_180MA;
1048                 break;
1049         case 240:
1050                 *val = ESR_MEAS_CUR_240MA;
1051                 break;
1052         default:
1053                 *val = ESR_MEAS_CUR_120MA;
1054                 break;
1055         };
1056
1057         *val <<= ESR_PULL_DOWN_IVAL_SHIFT;
1058 }
1059
1060 static int fg_set_esr_timer(struct fg_chip *chip, int cycles_init,
1061                                 int cycles_max, bool charging, int flags)
1062 {
1063         u8 buf[2];
1064         int rc, timer_max, timer_init;
1065
1066         if (cycles_init < 0 || cycles_max < 0)
1067                 return 0;
1068
1069         if (charging) {
1070                 timer_max = FG_SRAM_ESR_TIMER_CHG_MAX;
1071                 timer_init = FG_SRAM_ESR_TIMER_CHG_INIT;
1072         } else {
1073                 timer_max = FG_SRAM_ESR_TIMER_DISCHG_MAX;
1074                 timer_init = FG_SRAM_ESR_TIMER_DISCHG_INIT;
1075         }
1076
1077         fg_encode(chip->sp, timer_max, cycles_max, buf);
1078         rc = fg_sram_write(chip,
1079                         chip->sp[timer_max].addr_word,
1080                         chip->sp[timer_max].addr_byte, buf,
1081                         chip->sp[timer_max].len, flags);
1082         if (rc < 0) {
1083                 pr_err("Error in writing esr_timer_dischg_max, rc=%d\n",
1084                         rc);
1085                 return rc;
1086         }
1087
1088         fg_encode(chip->sp, timer_init, cycles_init, buf);
1089         rc = fg_sram_write(chip,
1090                         chip->sp[timer_init].addr_word,
1091                         chip->sp[timer_init].addr_byte, buf,
1092                         chip->sp[timer_init].len, flags);
1093         if (rc < 0) {
1094                 pr_err("Error in writing esr_timer_dischg_init, rc=%d\n",
1095                         rc);
1096                 return rc;
1097         }
1098
1099         fg_dbg(chip, FG_STATUS, "esr_%s_timer set to %d/%d\n",
1100                 charging ? "charging" : "discharging", cycles_init, cycles_max);
1101         return 0;
1102 }
1103
1104 /* Other functions HERE */
1105
1106 static void fg_notify_charger(struct fg_chip *chip)
1107 {
1108         union power_supply_propval prop = {0, };
1109         int rc;
1110
1111         if (!chip->batt_psy)
1112                 return;
1113
1114         if (!chip->profile_available)
1115                 return;
1116
1117         prop.intval = chip->bp.float_volt_uv;
1118         rc = power_supply_set_property(chip->batt_psy,
1119                         POWER_SUPPLY_PROP_VOLTAGE_MAX, &prop);
1120         if (rc < 0) {
1121                 pr_err("Error in setting voltage_max property on batt_psy, rc=%d\n",
1122                         rc);
1123                 return;
1124         }
1125
1126         prop.intval = chip->bp.fastchg_curr_ma * 1000;
1127         rc = power_supply_set_property(chip->batt_psy,
1128                         POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &prop);
1129         if (rc < 0) {
1130                 pr_err("Error in setting constant_charge_current_max property on batt_psy, rc=%d\n",
1131                         rc);
1132                 return;
1133         }
1134
1135         fg_dbg(chip, FG_STATUS, "Notified charger on float voltage and FCC\n");
1136 }
1137
1138 static int fg_batt_miss_irq_en_cb(struct votable *votable, void *data,
1139                                         int enable, const char *client)
1140 {
1141         struct fg_chip *chip = data;
1142
1143         if (!chip->irqs[BATT_MISSING_IRQ].irq)
1144                 return 0;
1145
1146         if (enable) {
1147                 enable_irq(chip->irqs[BATT_MISSING_IRQ].irq);
1148                 enable_irq_wake(chip->irqs[BATT_MISSING_IRQ].irq);
1149         } else {
1150                 disable_irq_wake(chip->irqs[BATT_MISSING_IRQ].irq);
1151                 disable_irq(chip->irqs[BATT_MISSING_IRQ].irq);
1152         }
1153
1154         return 0;
1155 }
1156
1157 static int fg_delta_bsoc_irq_en_cb(struct votable *votable, void *data,
1158                                         int enable, const char *client)
1159 {
1160         struct fg_chip *chip = data;
1161
1162         if (!chip->irqs[BSOC_DELTA_IRQ].irq)
1163                 return 0;
1164
1165         if (enable) {
1166                 enable_irq(chip->irqs[BSOC_DELTA_IRQ].irq);
1167                 enable_irq_wake(chip->irqs[BSOC_DELTA_IRQ].irq);
1168         } else {
1169                 disable_irq_wake(chip->irqs[BSOC_DELTA_IRQ].irq);
1170                 disable_irq(chip->irqs[BSOC_DELTA_IRQ].irq);
1171         }
1172
1173         return 0;
1174 }
1175
1176 static int fg_awake_cb(struct votable *votable, void *data, int awake,
1177                         const char *client)
1178 {
1179         struct fg_chip *chip = data;
1180
1181         if (awake)
1182                 pm_stay_awake(chip->dev);
1183         else
1184                 pm_relax(chip->dev);
1185
1186         pr_debug("client: %s awake: %d\n", client, awake);
1187         return 0;
1188 }
1189
1190 static bool batt_psy_initialized(struct fg_chip *chip)
1191 {
1192         if (chip->batt_psy)
1193                 return true;
1194
1195         chip->batt_psy = power_supply_get_by_name("battery");
1196         if (!chip->batt_psy)
1197                 return false;
1198
1199         /* batt_psy is initialized, set the fcc and fv */
1200         fg_notify_charger(chip);
1201
1202         return true;
1203 }
1204
1205 static bool usb_psy_initialized(struct fg_chip *chip)
1206 {
1207         if (chip->usb_psy)
1208                 return true;
1209
1210         chip->usb_psy = power_supply_get_by_name("usb");
1211         if (!chip->usb_psy)
1212                 return false;
1213
1214         return true;
1215 }
1216
1217 static bool pc_port_psy_initialized(struct fg_chip *chip)
1218 {
1219         if (chip->pc_port_psy)
1220                 return true;
1221
1222         chip->pc_port_psy = power_supply_get_by_name("pc_port");
1223         if (!chip->pc_port_psy)
1224                 return false;
1225
1226         return true;
1227 }
1228
1229 static bool dc_psy_initialized(struct fg_chip *chip)
1230 {
1231         if (chip->dc_psy)
1232                 return true;
1233
1234         chip->dc_psy = power_supply_get_by_name("dc");
1235         if (!chip->dc_psy)
1236                 return false;
1237
1238         return true;
1239 }
1240
1241 static bool is_parallel_charger_available(struct fg_chip *chip)
1242 {
1243         if (!chip->parallel_psy)
1244                 chip->parallel_psy = power_supply_get_by_name("parallel");
1245
1246         if (!chip->parallel_psy)
1247                 return false;
1248
1249         return true;
1250 }
1251
1252 static int fg_save_learned_cap_to_sram(struct fg_chip *chip)
1253 {
1254         int16_t cc_mah;
1255         int rc;
1256
1257         if (chip->battery_missing || !chip->cl.learned_cc_uah)
1258                 return -EPERM;
1259
1260         cc_mah = div64_s64(chip->cl.learned_cc_uah, 1000);
1261         /* Write to a backup register to use across reboot */
1262         rc = fg_sram_write(chip, chip->sp[FG_SRAM_ACT_BATT_CAP].addr_word,
1263                         chip->sp[FG_SRAM_ACT_BATT_CAP].addr_byte, (u8 *)&cc_mah,
1264                         chip->sp[FG_SRAM_ACT_BATT_CAP].len, FG_IMA_DEFAULT);
1265         if (rc < 0) {
1266                 pr_err("Error in writing act_batt_cap_bkup, rc=%d\n", rc);
1267                 return rc;
1268         }
1269
1270         /* Write to actual capacity register for coulomb counter operation */
1271         rc = fg_sram_write(chip, ACT_BATT_CAP_WORD, ACT_BATT_CAP_OFFSET,
1272                         (u8 *)&cc_mah, chip->sp[FG_SRAM_ACT_BATT_CAP].len,
1273                         FG_IMA_DEFAULT);
1274         if (rc < 0) {
1275                 pr_err("Error in writing act_batt_cap, rc=%d\n", rc);
1276                 return rc;
1277         }
1278
1279         fg_dbg(chip, FG_CAP_LEARN, "learned capacity %llduah/%dmah stored\n",
1280                 chip->cl.learned_cc_uah, cc_mah);
1281         return 0;
1282 }
1283
1284 #define CAPACITY_DELTA_DECIPCT  500
1285 static int fg_load_learned_cap_from_sram(struct fg_chip *chip)
1286 {
1287         int rc, act_cap_mah;
1288         int64_t delta_cc_uah, pct_nom_cap_uah;
1289
1290         rc = fg_get_sram_prop(chip, FG_SRAM_ACT_BATT_CAP, &act_cap_mah);
1291         if (rc < 0) {
1292                 pr_err("Error in getting ACT_BATT_CAP, rc=%d\n", rc);
1293                 return rc;
1294         }
1295
1296         chip->cl.learned_cc_uah = act_cap_mah * 1000;
1297
1298         if (chip->cl.learned_cc_uah != chip->cl.nom_cap_uah) {
1299                 if (chip->cl.learned_cc_uah == 0)
1300                         chip->cl.learned_cc_uah = chip->cl.nom_cap_uah;
1301
1302                 delta_cc_uah = abs(chip->cl.learned_cc_uah -
1303                                         chip->cl.nom_cap_uah);
1304                 pct_nom_cap_uah = div64_s64((int64_t)chip->cl.nom_cap_uah *
1305                                 CAPACITY_DELTA_DECIPCT, 1000);
1306                 /*
1307                  * If the learned capacity is out of range by 50% from the
1308                  * nominal capacity, then overwrite the learned capacity with
1309                  * the nominal capacity.
1310                  */
1311                 if (chip->cl.nom_cap_uah && delta_cc_uah > pct_nom_cap_uah) {
1312                         fg_dbg(chip, FG_CAP_LEARN, "learned_cc_uah: %lld is higher than expected, capping it to nominal: %lld\n",
1313                                 chip->cl.learned_cc_uah, chip->cl.nom_cap_uah);
1314                         chip->cl.learned_cc_uah = chip->cl.nom_cap_uah;
1315                 }
1316
1317                 rc = fg_save_learned_cap_to_sram(chip);
1318                 if (rc < 0)
1319                         pr_err("Error in saving learned_cc_uah, rc=%d\n", rc);
1320         }
1321
1322         fg_dbg(chip, FG_CAP_LEARN, "learned_cc_uah:%lld nom_cap_uah: %lld\n",
1323                 chip->cl.learned_cc_uah, chip->cl.nom_cap_uah);
1324         return 0;
1325 }
1326
1327 static bool is_temp_valid_cap_learning(struct fg_chip *chip)
1328 {
1329         int rc, batt_temp;
1330
1331         rc = fg_get_battery_temp(chip, &batt_temp);
1332         if (rc < 0) {
1333                 pr_err("Error in getting batt_temp\n");
1334                 return false;
1335         }
1336
1337         if (batt_temp > chip->dt.cl_max_temp ||
1338                 batt_temp < chip->dt.cl_min_temp) {
1339                 fg_dbg(chip, FG_CAP_LEARN, "batt temp %d out of range [%d %d]\n",
1340                         batt_temp, chip->dt.cl_min_temp, chip->dt.cl_max_temp);
1341                 return false;
1342         }
1343
1344         return true;
1345 }
1346
1347 #define QNOVO_CL_SKEW_DECIPCT   -30
1348 static void fg_cap_learning_post_process(struct fg_chip *chip)
1349 {
1350         int64_t max_inc_val, min_dec_val, old_cap;
1351         int rc;
1352
1353         if (is_qnovo_en(chip)) {
1354                 fg_dbg(chip, FG_CAP_LEARN, "applying skew %d on current learnt capacity %lld\n",
1355                         QNOVO_CL_SKEW_DECIPCT, chip->cl.final_cc_uah);
1356                 chip->cl.final_cc_uah = chip->cl.final_cc_uah *
1357                                                 (1000 + QNOVO_CL_SKEW_DECIPCT);
1358                 do_div(chip->cl.final_cc_uah, 1000);
1359         }
1360
1361         max_inc_val = chip->cl.learned_cc_uah
1362                         * (1000 + chip->dt.cl_max_cap_inc);
1363         do_div(max_inc_val, 1000);
1364
1365         min_dec_val = chip->cl.learned_cc_uah
1366                         * (1000 - chip->dt.cl_max_cap_dec);
1367         do_div(min_dec_val, 1000);
1368
1369         old_cap = chip->cl.learned_cc_uah;
1370         if (chip->cl.final_cc_uah > max_inc_val)
1371                 chip->cl.learned_cc_uah = max_inc_val;
1372         else if (chip->cl.final_cc_uah < min_dec_val)
1373                 chip->cl.learned_cc_uah = min_dec_val;
1374         else
1375                 chip->cl.learned_cc_uah =
1376                         chip->cl.final_cc_uah;
1377
1378         if (chip->dt.cl_max_cap_limit) {
1379                 max_inc_val = (int64_t)chip->cl.nom_cap_uah * (1000 +
1380                                 chip->dt.cl_max_cap_limit);
1381                 do_div(max_inc_val, 1000);
1382                 if (chip->cl.final_cc_uah > max_inc_val) {
1383                         fg_dbg(chip, FG_CAP_LEARN, "learning capacity %lld goes above max limit %lld\n",
1384                                 chip->cl.final_cc_uah, max_inc_val);
1385                         chip->cl.learned_cc_uah = max_inc_val;
1386                 }
1387         }
1388
1389         if (chip->dt.cl_min_cap_limit) {
1390                 min_dec_val = (int64_t)chip->cl.nom_cap_uah * (1000 -
1391                                 chip->dt.cl_min_cap_limit);
1392                 do_div(min_dec_val, 1000);
1393                 if (chip->cl.final_cc_uah < min_dec_val) {
1394                         fg_dbg(chip, FG_CAP_LEARN, "learning capacity %lld goes below min limit %lld\n",
1395                                 chip->cl.final_cc_uah, min_dec_val);
1396                         chip->cl.learned_cc_uah = min_dec_val;
1397                 }
1398         }
1399
1400         rc = fg_save_learned_cap_to_sram(chip);
1401         if (rc < 0)
1402                 pr_err("Error in saving learned_cc_uah, rc=%d\n", rc);
1403
1404         fg_dbg(chip, FG_CAP_LEARN, "final cc_uah = %lld, learned capacity %lld -> %lld uah\n",
1405                 chip->cl.final_cc_uah, old_cap, chip->cl.learned_cc_uah);
1406 }
1407
1408 static int fg_cap_learning_process_full_data(struct fg_chip *chip)
1409 {
1410         int rc, cc_soc_sw, cc_soc_delta_pct;
1411         int64_t delta_cc_uah;
1412
1413         rc = fg_get_sram_prop(chip, FG_SRAM_CC_SOC_SW, &cc_soc_sw);
1414         if (rc < 0) {
1415                 pr_err("Error in getting CC_SOC_SW, rc=%d\n", rc);
1416                 return rc;
1417         }
1418
1419         cc_soc_delta_pct =
1420                 div64_s64((int64_t)(cc_soc_sw - chip->cl.init_cc_soc_sw) * 100,
1421                         CC_SOC_30BIT);
1422
1423         /* If the delta is < 50%, then skip processing full data */
1424         if (cc_soc_delta_pct < 50) {
1425                 pr_err("cc_soc_delta_pct: %d\n", cc_soc_delta_pct);
1426                 return -ERANGE;
1427         }
1428
1429         delta_cc_uah = div64_s64(chip->cl.learned_cc_uah * cc_soc_delta_pct,
1430                                 100);
1431         chip->cl.final_cc_uah = chip->cl.init_cc_uah + delta_cc_uah;
1432         fg_dbg(chip, FG_CAP_LEARN, "Current cc_soc=%d cc_soc_delta_pct=%d total_cc_uah=%lld\n",
1433                 cc_soc_sw, cc_soc_delta_pct, chip->cl.final_cc_uah);
1434         return 0;
1435 }
1436
1437 #define BATT_SOC_32BIT  GENMASK(31, 0)
1438 static int fg_cap_learning_begin(struct fg_chip *chip, u32 batt_soc)
1439 {
1440         int rc, cc_soc_sw, batt_soc_msb;
1441
1442         batt_soc_msb = batt_soc >> 24;
1443         if (DIV_ROUND_CLOSEST(batt_soc_msb * 100, FULL_SOC_RAW) >
1444                 chip->dt.cl_start_soc) {
1445                 fg_dbg(chip, FG_CAP_LEARN, "Battery SOC %d is high!, not starting\n",
1446                         batt_soc_msb);
1447                 return -EINVAL;
1448         }
1449
1450         chip->cl.init_cc_uah = div64_s64(chip->cl.learned_cc_uah * batt_soc_msb,
1451                                         FULL_SOC_RAW);
1452
1453         /* Prime cc_soc_sw with battery SOC when capacity learning begins */
1454         cc_soc_sw = div64_s64((int64_t)batt_soc * CC_SOC_30BIT,
1455                                 BATT_SOC_32BIT);
1456         rc = fg_sram_write(chip, chip->sp[FG_SRAM_CC_SOC_SW].addr_word,
1457                 chip->sp[FG_SRAM_CC_SOC_SW].addr_byte, (u8 *)&cc_soc_sw,
1458                 chip->sp[FG_SRAM_CC_SOC_SW].len, FG_IMA_ATOMIC);
1459         if (rc < 0) {
1460                 pr_err("Error in writing cc_soc_sw, rc=%d\n", rc);
1461                 goto out;
1462         }
1463
1464         chip->cl.init_cc_soc_sw = cc_soc_sw;
1465         chip->cl.active = true;
1466         fg_dbg(chip, FG_CAP_LEARN, "Capacity learning started @ battery SOC %d init_cc_soc_sw:%d\n",
1467                 batt_soc_msb, chip->cl.init_cc_soc_sw);
1468 out:
1469         return rc;
1470 }
1471
1472 static int fg_cap_learning_done(struct fg_chip *chip)
1473 {
1474         int rc, cc_soc_sw;
1475
1476         rc = fg_cap_learning_process_full_data(chip);
1477         if (rc < 0) {
1478                 pr_err("Error in processing cap learning full data, rc=%d\n",
1479                         rc);
1480                 goto out;
1481         }
1482
1483         /* Write a FULL value to cc_soc_sw */
1484         cc_soc_sw = CC_SOC_30BIT;
1485         rc = fg_sram_write(chip, chip->sp[FG_SRAM_CC_SOC_SW].addr_word,
1486                 chip->sp[FG_SRAM_CC_SOC_SW].addr_byte, (u8 *)&cc_soc_sw,
1487                 chip->sp[FG_SRAM_CC_SOC_SW].len, FG_IMA_ATOMIC);
1488         if (rc < 0) {
1489                 pr_err("Error in writing cc_soc_sw, rc=%d\n", rc);
1490                 goto out;
1491         }
1492
1493         fg_cap_learning_post_process(chip);
1494 out:
1495         return rc;
1496 }
1497
1498 static void fg_cap_learning_update(struct fg_chip *chip)
1499 {
1500         int rc, batt_soc, batt_soc_msb;
1501         bool input_present = is_input_present(chip);
1502
1503         mutex_lock(&chip->cl.lock);
1504
1505         if (!is_temp_valid_cap_learning(chip) || !chip->cl.learned_cc_uah ||
1506                 chip->battery_missing) {
1507                 fg_dbg(chip, FG_CAP_LEARN, "Aborting cap_learning %lld\n",
1508                         chip->cl.learned_cc_uah);
1509                 chip->cl.active = false;
1510                 chip->cl.init_cc_uah = 0;
1511                 goto out;
1512         }
1513
1514         rc = fg_get_sram_prop(chip, FG_SRAM_BATT_SOC, &batt_soc);
1515         if (rc < 0) {
1516                 pr_err("Error in getting ACT_BATT_CAP, rc=%d\n", rc);
1517                 goto out;
1518         }
1519
1520         batt_soc_msb = (u32)batt_soc >> 24;
1521         fg_dbg(chip, FG_CAP_LEARN, "Chg_status: %d cl_active: %d batt_soc: %d\n",
1522                 chip->charge_status, chip->cl.active, batt_soc_msb);
1523
1524         /* Initialize the starting point of learning capacity */
1525         if (!chip->cl.active) {
1526                 if (chip->charge_status == POWER_SUPPLY_STATUS_CHARGING) {
1527                         rc = fg_cap_learning_begin(chip, batt_soc);
1528                         chip->cl.active = (rc == 0);
1529                 }
1530
1531         } else {
1532                 if (chip->charge_done) {
1533                         rc = fg_cap_learning_done(chip);
1534                         if (rc < 0)
1535                                 pr_err("Error in completing capacity learning, rc=%d\n",
1536                                         rc);
1537
1538                         chip->cl.active = false;
1539                         chip->cl.init_cc_uah = 0;
1540                 }
1541
1542                 if (chip->charge_status == POWER_SUPPLY_STATUS_DISCHARGING) {
1543                         if (!input_present) {
1544                                 fg_dbg(chip, FG_CAP_LEARN, "Capacity learning aborted @ battery SOC %d\n",
1545                                          batt_soc_msb);
1546                                 chip->cl.active = false;
1547                                 chip->cl.init_cc_uah = 0;
1548                         }
1549                 }
1550
1551                 if (chip->charge_status == POWER_SUPPLY_STATUS_NOT_CHARGING) {
1552                         if (is_qnovo_en(chip) && input_present) {
1553                                 /*
1554                                  * Don't abort the capacity learning when qnovo
1555                                  * is enabled and input is present where the
1556                                  * charging status can go to "not charging"
1557                                  * intermittently.
1558                                  */
1559                         } else {
1560                                 fg_dbg(chip, FG_CAP_LEARN, "Capacity learning aborted @ battery SOC %d\n",
1561                                         batt_soc_msb);
1562                                 chip->cl.active = false;
1563                                 chip->cl.init_cc_uah = 0;
1564                         }
1565                 }
1566         }
1567
1568 out:
1569         mutex_unlock(&chip->cl.lock);
1570 }
1571
1572 #define KI_COEFF_MED_DISCHG_DEFAULT     1500
1573 #define KI_COEFF_HI_DISCHG_DEFAULT      2200
1574 static int fg_adjust_ki_coeff_dischg(struct fg_chip *chip)
1575 {
1576         int rc, i, msoc;
1577         int ki_coeff_med = KI_COEFF_MED_DISCHG_DEFAULT;
1578         int ki_coeff_hi = KI_COEFF_HI_DISCHG_DEFAULT;
1579         u8 val;
1580
1581         if (!chip->ki_coeff_dischg_en)
1582                 return 0;
1583
1584         rc = fg_get_prop_capacity(chip, &msoc);
1585         if (rc < 0) {
1586                 pr_err("Error in getting capacity, rc=%d\n", rc);
1587                 return rc;
1588         }
1589
1590         if (chip->charge_status == POWER_SUPPLY_STATUS_DISCHARGING) {
1591                 for (i = KI_COEFF_SOC_LEVELS - 1; i >= 0; i--) {
1592                         if (msoc < chip->dt.ki_coeff_soc[i]) {
1593                                 ki_coeff_med = chip->dt.ki_coeff_med_dischg[i];
1594                                 ki_coeff_hi = chip->dt.ki_coeff_hi_dischg[i];
1595                         }
1596                 }
1597         }
1598
1599         fg_encode(chip->sp, FG_SRAM_KI_COEFF_MED_DISCHG, ki_coeff_med, &val);
1600         rc = fg_sram_write(chip,
1601                         chip->sp[FG_SRAM_KI_COEFF_MED_DISCHG].addr_word,
1602                         chip->sp[FG_SRAM_KI_COEFF_MED_DISCHG].addr_byte, &val,
1603                         chip->sp[FG_SRAM_KI_COEFF_MED_DISCHG].len,
1604                         FG_IMA_DEFAULT);
1605         if (rc < 0) {
1606                 pr_err("Error in writing ki_coeff_med, rc=%d\n", rc);
1607                 return rc;
1608         }
1609
1610         fg_encode(chip->sp, FG_SRAM_KI_COEFF_HI_DISCHG, ki_coeff_hi, &val);
1611         rc = fg_sram_write(chip,
1612                         chip->sp[FG_SRAM_KI_COEFF_HI_DISCHG].addr_word,
1613                         chip->sp[FG_SRAM_KI_COEFF_HI_DISCHG].addr_byte, &val,
1614                         chip->sp[FG_SRAM_KI_COEFF_HI_DISCHG].len,
1615                         FG_IMA_DEFAULT);
1616         if (rc < 0) {
1617                 pr_err("Error in writing ki_coeff_hi, rc=%d\n", rc);
1618                 return rc;
1619         }
1620
1621         fg_dbg(chip, FG_STATUS, "Wrote ki_coeff_med %d ki_coeff_hi %d\n",
1622                 ki_coeff_med, ki_coeff_hi);
1623         return 0;
1624 }
1625
1626 #define KI_COEFF_FULL_SOC_DEFAULT       733
1627 static int fg_adjust_ki_coeff_full_soc(struct fg_chip *chip, int batt_temp)
1628 {
1629         int rc, ki_coeff_full_soc;
1630         u8 val;
1631
1632         if (batt_temp < 0)
1633                 ki_coeff_full_soc = 0;
1634         else if (chip->charge_status == POWER_SUPPLY_STATUS_DISCHARGING)
1635                 ki_coeff_full_soc = chip->dt.ki_coeff_full_soc_dischg;
1636         else
1637                 ki_coeff_full_soc = KI_COEFF_FULL_SOC_DEFAULT;
1638
1639         if (chip->ki_coeff_full_soc == ki_coeff_full_soc)
1640                 return 0;
1641
1642         fg_encode(chip->sp, FG_SRAM_KI_COEFF_FULL_SOC, ki_coeff_full_soc, &val);
1643         rc = fg_sram_write(chip,
1644                         chip->sp[FG_SRAM_KI_COEFF_FULL_SOC].addr_word,
1645                         chip->sp[FG_SRAM_KI_COEFF_FULL_SOC].addr_byte, &val,
1646                         chip->sp[FG_SRAM_KI_COEFF_FULL_SOC].len,
1647                         FG_IMA_DEFAULT);
1648         if (rc < 0) {
1649                 pr_err("Error in writing ki_coeff_full_soc, rc=%d\n", rc);
1650                 return rc;
1651         }
1652
1653         chip->ki_coeff_full_soc = ki_coeff_full_soc;
1654         fg_dbg(chip, FG_STATUS, "Wrote ki_coeff_full_soc %d\n",
1655                 ki_coeff_full_soc);
1656         return 0;
1657 }
1658
1659 static int fg_set_recharge_voltage(struct fg_chip *chip, int voltage_mv)
1660 {
1661         u8 buf;
1662         int rc;
1663
1664         if (chip->dt.auto_recharge_soc)
1665                 return 0;
1666
1667         /* This configuration is available only for pmicobalt v2.0 and above */
1668         if (chip->wa_flags & PMI8998_V1_REV_WA)
1669                 return 0;
1670
1671         if (voltage_mv == chip->last_recharge_volt_mv)
1672                 return 0;
1673
1674         fg_dbg(chip, FG_STATUS, "Setting recharge voltage to %dmV\n",
1675                 voltage_mv);
1676         fg_encode(chip->sp, FG_SRAM_RECHARGE_VBATT_THR, voltage_mv, &buf);
1677         rc = fg_sram_write(chip,
1678                         chip->sp[FG_SRAM_RECHARGE_VBATT_THR].addr_word,
1679                         chip->sp[FG_SRAM_RECHARGE_VBATT_THR].addr_byte,
1680                         &buf, chip->sp[FG_SRAM_RECHARGE_VBATT_THR].len,
1681                         FG_IMA_DEFAULT);
1682         if (rc < 0) {
1683                 pr_err("Error in writing recharge_vbatt_thr, rc=%d\n",
1684                         rc);
1685                 return rc;
1686         }
1687
1688         chip->last_recharge_volt_mv = voltage_mv;
1689         return 0;
1690 }
1691
1692 static int fg_configure_full_soc(struct fg_chip *chip, int bsoc)
1693 {
1694         int rc;
1695         u8 full_soc[2] = {0xFF, 0xFF};
1696
1697         /*
1698          * Once SOC masking condition is cleared, FULL_SOC and MONOTONIC_SOC
1699          * needs to be updated to reflect the same. Write battery SOC to
1700          * FULL_SOC and write a full value to MONOTONIC_SOC.
1701          */
1702         rc = fg_sram_write(chip, FULL_SOC_WORD, FULL_SOC_OFFSET,
1703                         (u8 *)&bsoc, 2, FG_IMA_ATOMIC);
1704         if (rc < 0) {
1705                 pr_err("failed to write full_soc rc=%d\n", rc);
1706                 return rc;
1707         }
1708
1709         rc = fg_sram_write(chip, MONOTONIC_SOC_WORD, MONOTONIC_SOC_OFFSET,
1710                         full_soc, 2, FG_IMA_ATOMIC);
1711         if (rc < 0) {
1712                 pr_err("failed to write monotonic_soc rc=%d\n", rc);
1713                 return rc;
1714         }
1715
1716         return 0;
1717 }
1718
1719 #define AUTO_RECHG_VOLT_LOW_LIMIT_MV    3700
1720 static int fg_charge_full_update(struct fg_chip *chip)
1721 {
1722         union power_supply_propval prop = {0, };
1723         int rc, msoc, bsoc, recharge_soc, msoc_raw;
1724
1725         if (!chip->dt.hold_soc_while_full)
1726                 return 0;
1727
1728         if (!batt_psy_initialized(chip))
1729                 return 0;
1730
1731         mutex_lock(&chip->charge_full_lock);
1732         vote(chip->delta_bsoc_irq_en_votable, DELTA_BSOC_IRQ_VOTER,
1733                 chip->charge_done, 0);
1734         rc = power_supply_get_property(chip->batt_psy, POWER_SUPPLY_PROP_HEALTH,
1735                 &prop);
1736         if (rc < 0) {
1737                 pr_err("Error in getting battery health, rc=%d\n", rc);
1738                 goto out;
1739         }
1740
1741         chip->health = prop.intval;
1742         recharge_soc = chip->dt.recharge_soc_thr;
1743         recharge_soc = DIV_ROUND_CLOSEST(recharge_soc * FULL_SOC_RAW,
1744                                 FULL_CAPACITY);
1745         rc = fg_get_sram_prop(chip, FG_SRAM_BATT_SOC, &bsoc);
1746         if (rc < 0) {
1747                 pr_err("Error in getting BATT_SOC, rc=%d\n", rc);
1748                 goto out;
1749         }
1750
1751         /* We need 2 most significant bytes here */
1752         bsoc = (u32)bsoc >> 16;
1753         rc = fg_get_msoc_raw(chip, &msoc_raw);
1754         if (rc < 0) {
1755                 pr_err("Error in getting msoc_raw, rc=%d\n", rc);
1756                 goto out;
1757         }
1758         msoc = DIV_ROUND_CLOSEST(msoc_raw * FULL_CAPACITY, FULL_SOC_RAW);
1759
1760         fg_dbg(chip, FG_STATUS, "msoc: %d bsoc: %x health: %d status: %d full: %d\n",
1761                 msoc, bsoc, chip->health, chip->charge_status,
1762                 chip->charge_full);
1763         if (chip->charge_done && !chip->charge_full) {
1764                 if (msoc >= 99 && chip->health == POWER_SUPPLY_HEALTH_GOOD) {
1765                         fg_dbg(chip, FG_STATUS, "Setting charge_full to true\n");
1766                         chip->charge_full = true;
1767                         /*
1768                          * Lower the recharge voltage so that VBAT_LT_RECHG
1769                          * signal will not be asserted soon.
1770                          */
1771                         rc = fg_set_recharge_voltage(chip,
1772                                         AUTO_RECHG_VOLT_LOW_LIMIT_MV);
1773                         if (rc < 0) {
1774                                 pr_err("Error in reducing recharge voltage, rc=%d\n",
1775                                         rc);
1776                                 goto out;
1777                         }
1778                 } else {
1779                         fg_dbg(chip, FG_STATUS, "Terminated charging @ SOC%d\n",
1780                                 msoc);
1781                 }
1782         } else if (msoc_raw <= recharge_soc && chip->charge_full) {
1783                 if (chip->dt.linearize_soc) {
1784                         chip->delta_soc = FULL_CAPACITY - msoc;
1785
1786                         /*
1787                          * We're spreading out the delta SOC over every 10%
1788                          * change in monotonic SOC. We cannot spread more than
1789                          * 9% in the range of 0-100 skipping the first 10%.
1790                          */
1791                         if (chip->delta_soc > 9) {
1792                                 chip->delta_soc = 0;
1793                                 chip->maint_soc = 0;
1794                         } else {
1795                                 chip->maint_soc = FULL_CAPACITY;
1796                                 chip->last_msoc = msoc;
1797                         }
1798                 }
1799
1800                 /*
1801                  * Raise the recharge voltage so that VBAT_LT_RECHG signal
1802                  * will be asserted soon as battery SOC had dropped below
1803                  * the recharge SOC threshold.
1804                  */
1805                 rc = fg_set_recharge_voltage(chip,
1806                                         chip->dt.recharge_volt_thr_mv);
1807                 if (rc < 0) {
1808                         pr_err("Error in setting recharge voltage, rc=%d\n",
1809                                 rc);
1810                         goto out;
1811                 }
1812
1813                 /*
1814                  * If charge_done is still set, wait for recharging or
1815                  * discharging to happen.
1816                  */
1817                 if (chip->charge_done)
1818                         goto out;
1819
1820                 rc = fg_configure_full_soc(chip, bsoc);
1821                 if (rc < 0)
1822                         goto out;
1823
1824                 chip->charge_full = false;
1825                 fg_dbg(chip, FG_STATUS, "msoc_raw = %d bsoc: %d recharge_soc: %d delta_soc: %d\n",
1826                         msoc_raw, bsoc >> 8, recharge_soc, chip->delta_soc);
1827         }
1828
1829 out:
1830         mutex_unlock(&chip->charge_full_lock);
1831         return rc;
1832 }
1833
1834 #define RCONN_CONFIG_BIT        BIT(0)
1835 static int fg_rconn_config(struct fg_chip *chip)
1836 {
1837         int rc, esr_uohms;
1838         u64 scaling_factor;
1839         u32 val = 0;
1840
1841         if (!chip->dt.rconn_mohms)
1842                 return 0;
1843
1844         rc = fg_sram_read(chip, PROFILE_INTEGRITY_WORD,
1845                         SW_CONFIG_OFFSET, (u8 *)&val, 1, FG_IMA_DEFAULT);
1846         if (rc < 0) {
1847                 pr_err("Error in reading SW_CONFIG_OFFSET, rc=%d\n", rc);
1848                 return rc;
1849         }
1850
1851         if (val & RCONN_CONFIG_BIT) {
1852                 fg_dbg(chip, FG_STATUS, "Rconn already configured: %x\n", val);
1853                 return 0;
1854         }
1855
1856         rc = fg_get_sram_prop(chip, FG_SRAM_ESR, &esr_uohms);
1857         if (rc < 0) {
1858                 pr_err("failed to get ESR, rc=%d\n", rc);
1859                 return rc;
1860         }
1861
1862         scaling_factor = div64_u64((u64)esr_uohms * 1000,
1863                                 esr_uohms + (chip->dt.rconn_mohms * 1000));
1864
1865         rc = fg_sram_read(chip, ESR_RSLOW_CHG_WORD,
1866                         ESR_RSLOW_CHG_OFFSET, (u8 *)&val, 1, FG_IMA_DEFAULT);
1867         if (rc < 0) {
1868                 pr_err("Error in reading ESR_RSLOW_CHG_OFFSET, rc=%d\n", rc);
1869                 return rc;
1870         }
1871
1872         val *= scaling_factor;
1873         do_div(val, 1000);
1874         rc = fg_sram_write(chip, ESR_RSLOW_CHG_WORD,
1875                         ESR_RSLOW_CHG_OFFSET, (u8 *)&val, 1, FG_IMA_DEFAULT);
1876         if (rc < 0) {
1877                 pr_err("Error in writing ESR_RSLOW_CHG_OFFSET, rc=%d\n", rc);
1878                 return rc;
1879         }
1880         fg_dbg(chip, FG_STATUS, "esr_rslow_chg modified to %x\n", val & 0xFF);
1881
1882         rc = fg_sram_read(chip, ESR_RSLOW_DISCHG_WORD,
1883                         ESR_RSLOW_DISCHG_OFFSET, (u8 *)&val, 1, FG_IMA_DEFAULT);
1884         if (rc < 0) {
1885                 pr_err("Error in reading ESR_RSLOW_DISCHG_OFFSET, rc=%d\n", rc);
1886                 return rc;
1887         }
1888
1889         val *= scaling_factor;
1890         do_div(val, 1000);
1891         rc = fg_sram_write(chip, ESR_RSLOW_DISCHG_WORD,
1892                         ESR_RSLOW_DISCHG_OFFSET, (u8 *)&val, 1, FG_IMA_DEFAULT);
1893         if (rc < 0) {
1894                 pr_err("Error in writing ESR_RSLOW_DISCHG_OFFSET, rc=%d\n", rc);
1895                 return rc;
1896         }
1897         fg_dbg(chip, FG_STATUS, "esr_rslow_dischg modified to %x\n",
1898                 val & 0xFF);
1899
1900         val = RCONN_CONFIG_BIT;
1901         rc = fg_sram_write(chip, PROFILE_INTEGRITY_WORD,
1902                         SW_CONFIG_OFFSET, (u8 *)&val, 1, FG_IMA_DEFAULT);
1903         if (rc < 0) {
1904                 pr_err("Error in writing SW_CONFIG_OFFSET, rc=%d\n", rc);
1905                 return rc;
1906         }
1907
1908         return 0;
1909 }
1910
1911 static int fg_set_jeita_threshold(struct fg_chip *chip,
1912                                 enum jeita_levels level, int temp_decidegC)
1913 {
1914         int rc;
1915         u8 val;
1916         u16 reg;
1917
1918         if (temp_decidegC < -300 || temp_decidegC > 970)
1919                 return -EINVAL;
1920
1921         /* Resolution is 0.5C. Base is -30C. */
1922         val = DIV_ROUND_CLOSEST(((temp_decidegC / 10) + 30) * 10, 5);
1923         switch (level) {
1924         case JEITA_COLD:
1925                 reg = BATT_INFO_JEITA_TOO_COLD(chip);
1926                 break;
1927         case JEITA_COOL:
1928                 reg = BATT_INFO_JEITA_COLD(chip);
1929                 break;
1930         case JEITA_WARM:
1931                 reg = BATT_INFO_JEITA_HOT(chip);
1932                 break;
1933         case JEITA_HOT:
1934                 reg = BATT_INFO_JEITA_TOO_HOT(chip);
1935                 break;
1936         default:
1937                 return -EINVAL;
1938         }
1939
1940         rc = fg_write(chip, reg, &val, 1);
1941         if (rc < 0) {
1942                 pr_err("Error in setting jeita level %d, rc=%d\n", level, rc);
1943                 return rc;
1944         }
1945
1946         return 0;
1947 }
1948
1949 static int fg_set_constant_chg_voltage(struct fg_chip *chip, int volt_uv)
1950 {
1951         u8 buf[2];
1952         int rc;
1953
1954         if (volt_uv <= 0 || volt_uv > 15590000) {
1955                 pr_err("Invalid voltage %d\n", volt_uv);
1956                 return -EINVAL;
1957         }
1958
1959         fg_encode(chip->sp, FG_SRAM_VBATT_FULL, volt_uv, buf);
1960
1961         rc = fg_sram_write(chip, chip->sp[FG_SRAM_VBATT_FULL].addr_word,
1962                 chip->sp[FG_SRAM_VBATT_FULL].addr_byte, buf,
1963                 chip->sp[FG_SRAM_VBATT_FULL].len, FG_IMA_DEFAULT);
1964         if (rc < 0) {
1965                 pr_err("Error in writing vbatt_full, rc=%d\n", rc);
1966                 return rc;
1967         }
1968
1969         return 0;
1970 }
1971
1972 static int fg_set_recharge_soc(struct fg_chip *chip, int recharge_soc)
1973 {
1974         u8 buf;
1975         int rc;
1976
1977         if (!chip->dt.auto_recharge_soc)
1978                 return 0;
1979
1980         if (recharge_soc < 0 || recharge_soc > FULL_CAPACITY)
1981                 return 0;
1982
1983         fg_encode(chip->sp, FG_SRAM_RECHARGE_SOC_THR, recharge_soc, &buf);
1984         rc = fg_sram_write(chip,
1985                         chip->sp[FG_SRAM_RECHARGE_SOC_THR].addr_word,
1986                         chip->sp[FG_SRAM_RECHARGE_SOC_THR].addr_byte, &buf,
1987                         chip->sp[FG_SRAM_RECHARGE_SOC_THR].len, FG_IMA_DEFAULT);
1988         if (rc < 0) {
1989                 pr_err("Error in writing recharge_soc_thr, rc=%d\n", rc);
1990                 return rc;
1991         }
1992
1993         return 0;
1994 }
1995
1996 static int fg_adjust_recharge_soc(struct fg_chip *chip)
1997 {
1998         int rc, msoc, recharge_soc, new_recharge_soc = 0;
1999         bool recharge_soc_status;
2000
2001         if (!chip->dt.auto_recharge_soc)
2002                 return 0;
2003
2004         recharge_soc = chip->dt.recharge_soc_thr;
2005         recharge_soc_status = chip->recharge_soc_adjusted;
2006         /*
2007          * If the input is present and charging had been terminated, adjust
2008          * the recharge SOC threshold based on the monotonic SOC at which
2009          * the charge termination had happened.
2010          */
2011         if (is_input_present(chip)) {
2012                 if (chip->charge_done) {
2013                         if (!chip->recharge_soc_adjusted) {
2014                                 /* Get raw monotonic SOC for calculation */
2015                                 rc = fg_get_msoc(chip, &msoc);
2016                                 if (rc < 0) {
2017                                         pr_err("Error in getting msoc, rc=%d\n",
2018                                                 rc);
2019                                         return rc;
2020                                 }
2021
2022                                 /* Adjust the recharge_soc threshold */
2023                                 new_recharge_soc = msoc - (FULL_CAPACITY -
2024                                                                 recharge_soc);
2025                                 chip->recharge_soc_adjusted = true;
2026                         } else {
2027                                 /* adjusted already, do nothing */
2028                                 return 0;
2029                         }
2030                 } else {
2031                         /* Charging, do nothing */
2032                         return 0;
2033                 }
2034         } else {
2035                 /* Restore the default value */
2036                 new_recharge_soc = recharge_soc;
2037                 chip->recharge_soc_adjusted = false;
2038         }
2039
2040         rc = fg_set_recharge_soc(chip, new_recharge_soc);
2041         if (rc < 0) {
2042                 chip->recharge_soc_adjusted = recharge_soc_status;
2043                 pr_err("Couldn't set resume SOC for FG, rc=%d\n", rc);
2044                 return rc;
2045         }
2046
2047         fg_dbg(chip, FG_STATUS, "resume soc set to %d\n", new_recharge_soc);
2048         return 0;
2049 }
2050
2051 static int fg_adjust_recharge_voltage(struct fg_chip *chip)
2052 {
2053         int rc, recharge_volt_mv;
2054
2055         if (chip->dt.auto_recharge_soc)
2056                 return 0;
2057
2058         fg_dbg(chip, FG_STATUS, "health: %d chg_status: %d chg_done: %d\n",
2059                 chip->health, chip->charge_status, chip->charge_done);
2060
2061         recharge_volt_mv = chip->dt.recharge_volt_thr_mv;
2062
2063         /* Lower the recharge voltage in soft JEITA */
2064         if (chip->health == POWER_SUPPLY_HEALTH_WARM ||
2065                         chip->health == POWER_SUPPLY_HEALTH_COOL)
2066                 recharge_volt_mv -= 200;
2067
2068         rc = fg_set_recharge_voltage(chip, recharge_volt_mv);
2069         if (rc < 0) {
2070                 pr_err("Error in setting recharge_voltage, rc=%d\n",
2071                         rc);
2072                 return rc;
2073         }
2074
2075         return 0;
2076 }
2077
2078 static int fg_slope_limit_config(struct fg_chip *chip, int batt_temp)
2079 {
2080         enum slope_limit_status status;
2081         int rc;
2082         u8 buf;
2083
2084         if (!chip->slope_limit_en)
2085                 return 0;
2086
2087         if (chip->charge_status == POWER_SUPPLY_STATUS_CHARGING ||
2088                 chip->charge_status == POWER_SUPPLY_STATUS_FULL) {
2089                 if (batt_temp < chip->dt.slope_limit_temp)
2090                         status = LOW_TEMP_CHARGE;
2091                 else
2092                         status = HIGH_TEMP_CHARGE;
2093         } else {
2094                 if (batt_temp < chip->dt.slope_limit_temp)
2095                         status = LOW_TEMP_DISCHARGE;
2096                 else
2097                         status = HIGH_TEMP_DISCHARGE;
2098         }
2099
2100         if (chip->slope_limit_sts == status)
2101                 return 0;
2102
2103         fg_encode(chip->sp, FG_SRAM_SLOPE_LIMIT,
2104                 chip->dt.slope_limit_coeffs[status], &buf);
2105         rc = fg_sram_write(chip, chip->sp[FG_SRAM_SLOPE_LIMIT].addr_word,
2106                         chip->sp[FG_SRAM_SLOPE_LIMIT].addr_byte, &buf,
2107                         chip->sp[FG_SRAM_SLOPE_LIMIT].len, FG_IMA_DEFAULT);
2108         if (rc < 0) {
2109                 pr_err("Error in configuring slope_limit coefficient, rc=%d\n",
2110                         rc);
2111                 return rc;
2112         }
2113
2114         chip->slope_limit_sts = status;
2115         fg_dbg(chip, FG_STATUS, "Slope limit status: %d value: %x\n", status,
2116                 buf);
2117         return 0;
2118 }
2119
2120 static int fg_esr_filter_config(struct fg_chip *chip, int batt_temp)
2121 {
2122         u8 esr_tight_lt_flt, esr_broad_lt_flt;
2123         bool cold_temp = false;
2124         int rc;
2125
2126         /*
2127          * If the battery temperature is lower than -20 C, then skip modifying
2128          * ESR filter.
2129          */
2130         if (batt_temp < -210)
2131                 return 0;
2132
2133         /*
2134          * If battery temperature is lesser than 10 C (default), then apply the
2135          * ESR low temperature tight and broad filter values to ESR room
2136          * temperature tight and broad filters. If battery temperature is higher
2137          * than 10 C, then apply back the room temperature ESR filter
2138          * coefficients to ESR room temperature tight and broad filters.
2139          */
2140         if (batt_temp > chip->dt.esr_flt_switch_temp
2141                 && chip->esr_flt_cold_temp_en) {
2142                 fg_encode(chip->sp, FG_SRAM_ESR_TIGHT_FILTER,
2143                         chip->dt.esr_tight_flt_upct, &esr_tight_lt_flt);
2144                 fg_encode(chip->sp, FG_SRAM_ESR_BROAD_FILTER,
2145                         chip->dt.esr_broad_flt_upct, &esr_broad_lt_flt);
2146         } else if (batt_temp <= chip->dt.esr_flt_switch_temp
2147                         && !chip->esr_flt_cold_temp_en) {
2148                 fg_encode(chip->sp, FG_SRAM_ESR_TIGHT_FILTER,
2149                         chip->dt.esr_tight_lt_flt_upct, &esr_tight_lt_flt);
2150                 fg_encode(chip->sp, FG_SRAM_ESR_BROAD_FILTER,
2151                         chip->dt.esr_broad_lt_flt_upct, &esr_broad_lt_flt);
2152                 cold_temp = true;
2153         } else {
2154                 return 0;
2155         }
2156
2157         rc = fg_sram_write(chip, chip->sp[FG_SRAM_ESR_TIGHT_FILTER].addr_word,
2158                         chip->sp[FG_SRAM_ESR_TIGHT_FILTER].addr_byte,
2159                         &esr_tight_lt_flt,
2160                         chip->sp[FG_SRAM_ESR_TIGHT_FILTER].len, FG_IMA_DEFAULT);
2161         if (rc < 0) {
2162                 pr_err("Error in writing ESR LT tight filter, rc=%d\n", rc);
2163                 return rc;
2164         }
2165
2166         rc = fg_sram_write(chip, chip->sp[FG_SRAM_ESR_BROAD_FILTER].addr_word,
2167                         chip->sp[FG_SRAM_ESR_BROAD_FILTER].addr_byte,
2168                         &esr_broad_lt_flt,
2169                         chip->sp[FG_SRAM_ESR_BROAD_FILTER].len, FG_IMA_DEFAULT);
2170         if (rc < 0) {
2171                 pr_err("Error in writing ESR LT broad filter, rc=%d\n", rc);
2172                 return rc;
2173         }
2174
2175         chip->esr_flt_cold_temp_en = cold_temp;
2176         fg_dbg(chip, FG_STATUS, "applied %s ESR filter values\n",
2177                 cold_temp ? "cold" : "normal");
2178         return 0;
2179 }
2180
2181 static int fg_esr_fcc_config(struct fg_chip *chip)
2182 {
2183         union power_supply_propval prop = {0, };
2184         int rc;
2185         bool parallel_en = false, qnovo_en;
2186
2187         if (is_parallel_charger_available(chip)) {
2188                 rc = power_supply_get_property(chip->parallel_psy,
2189                         POWER_SUPPLY_PROP_CHARGING_ENABLED, &prop);
2190                 if (rc < 0) {
2191                         pr_err("Error in reading charging_enabled from parallel_psy, rc=%d\n",
2192                                 rc);
2193                         return rc;
2194                 }
2195                 parallel_en = prop.intval;
2196         }
2197
2198         qnovo_en = is_qnovo_en(chip);
2199
2200         fg_dbg(chip, FG_POWER_SUPPLY, "chg_sts: %d par_en: %d qnov_en: %d esr_fcc_ctrl_en: %d\n",
2201                 chip->charge_status, parallel_en, qnovo_en,
2202                 chip->esr_fcc_ctrl_en);
2203
2204         if (chip->charge_status == POWER_SUPPLY_STATUS_CHARGING &&
2205                         (parallel_en || qnovo_en)) {
2206                 if (chip->esr_fcc_ctrl_en)
2207                         return 0;
2208
2209                 /*
2210                  * When parallel charging or Qnovo is enabled, configure ESR
2211                  * FCC to 300mA to trigger an ESR pulse. Without this, FG can
2212                  * request the main charger to increase FCC when it is supposed
2213                  * to decrease it.
2214                  */
2215                 rc = fg_masked_write(chip, BATT_INFO_ESR_FAST_CRG_CFG(chip),
2216                                 ESR_FAST_CRG_IVAL_MASK |
2217                                 ESR_FAST_CRG_CTL_EN_BIT,
2218                                 ESR_FCC_300MA | ESR_FAST_CRG_CTL_EN_BIT);
2219                 if (rc < 0) {
2220                         pr_err("Error in writing to %04x, rc=%d\n",
2221                                 BATT_INFO_ESR_FAST_CRG_CFG(chip), rc);
2222                         return rc;
2223                 }
2224
2225                 chip->esr_fcc_ctrl_en = true;
2226         } else {
2227                 if (!chip->esr_fcc_ctrl_en)
2228                         return 0;
2229
2230                 /*
2231                  * If we're here, then it means either the device is not in
2232                  * charging state or parallel charging / Qnovo is disabled.
2233                  * Disable ESR fast charge current control in SW.
2234                  */
2235                 rc = fg_masked_write(chip, BATT_INFO_ESR_FAST_CRG_CFG(chip),
2236                                 ESR_FAST_CRG_CTL_EN_BIT, 0);
2237                 if (rc < 0) {
2238                         pr_err("Error in writing to %04x, rc=%d\n",
2239                                 BATT_INFO_ESR_FAST_CRG_CFG(chip), rc);
2240                         return rc;
2241                 }
2242
2243                 chip->esr_fcc_ctrl_en = false;
2244         }
2245
2246         fg_dbg(chip, FG_STATUS, "esr_fcc_ctrl_en set to %d\n",
2247                 chip->esr_fcc_ctrl_en);
2248         return 0;
2249 }
2250
2251 static int fg_esr_timer_config(struct fg_chip *chip, bool sleep)
2252 {
2253         int rc, cycles_init, cycles_max;
2254         bool end_of_charge = false;
2255
2256         end_of_charge = is_input_present(chip) && chip->charge_done;
2257         fg_dbg(chip, FG_STATUS, "sleep: %d eoc: %d\n", sleep, end_of_charge);
2258
2259         /* ESR discharging timer configuration */
2260         cycles_init = sleep ? chip->dt.esr_timer_asleep[TIMER_RETRY] :
2261                         chip->dt.esr_timer_awake[TIMER_RETRY];
2262         if (end_of_charge)
2263                 cycles_init = 0;
2264
2265         cycles_max = sleep ? chip->dt.esr_timer_asleep[TIMER_MAX] :
2266                         chip->dt.esr_timer_awake[TIMER_MAX];
2267
2268         rc = fg_set_esr_timer(chip, cycles_init, cycles_max, false,
2269                 sleep ? FG_IMA_NO_WLOCK : FG_IMA_DEFAULT);
2270         if (rc < 0) {
2271                 pr_err("Error in setting ESR timer, rc=%d\n", rc);
2272                 return rc;
2273         }
2274
2275         /* ESR charging timer configuration */
2276         cycles_init = cycles_max = -EINVAL;
2277         if (end_of_charge || sleep) {
2278                 cycles_init = chip->dt.esr_timer_charging[TIMER_RETRY];
2279                 cycles_max = chip->dt.esr_timer_charging[TIMER_MAX];
2280         } else if (is_input_present(chip)) {
2281                 cycles_init = chip->esr_timer_charging_default[TIMER_RETRY];
2282                 cycles_max = chip->esr_timer_charging_default[TIMER_MAX];
2283         }
2284
2285         rc = fg_set_esr_timer(chip, cycles_init, cycles_max, true,
2286                 sleep ? FG_IMA_NO_WLOCK : FG_IMA_DEFAULT);
2287         if (rc < 0) {
2288                 pr_err("Error in setting ESR timer, rc=%d\n", rc);
2289                 return rc;
2290         }
2291
2292         return 0;
2293 }
2294
2295 static void fg_ttf_update(struct fg_chip *chip)
2296 {
2297         int rc;
2298         int delay_ms;
2299         union power_supply_propval prop = {0, };
2300         int online = 0;
2301
2302         if (usb_psy_initialized(chip)) {
2303                 rc = power_supply_get_property(chip->usb_psy,
2304                         POWER_SUPPLY_PROP_ONLINE, &prop);
2305                 if (rc < 0) {
2306                         pr_err("Couldn't read usb ONLINE prop rc=%d\n", rc);
2307                         return;
2308                 }
2309
2310                 online = online || prop.intval;
2311         }
2312
2313         if (pc_port_psy_initialized(chip)) {
2314                 rc = power_supply_get_property(chip->pc_port_psy,
2315                         POWER_SUPPLY_PROP_ONLINE, &prop);
2316                 if (rc < 0) {
2317                         pr_err("Couldn't read pc_port ONLINE prop rc=%d\n", rc);
2318                         return;
2319                 }
2320
2321                 online = online || prop.intval;
2322         }
2323
2324         if (dc_psy_initialized(chip)) {
2325                 rc = power_supply_get_property(chip->dc_psy,
2326                         POWER_SUPPLY_PROP_ONLINE, &prop);
2327                 if (rc < 0) {
2328                         pr_err("Couldn't read dc ONLINE prop rc=%d\n", rc);
2329                         return;
2330                 }
2331
2332                 online = online || prop.intval;
2333         }
2334
2335
2336         if (chip->online_status == online)
2337                 return;
2338
2339         chip->online_status = online;
2340         if (online)
2341                 /* wait 35 seconds for the input to settle */
2342                 delay_ms = 35000;
2343         else
2344                 /* wait 5 seconds for current to settle during discharge */
2345                 delay_ms = 5000;
2346
2347         vote(chip->awake_votable, TTF_PRIMING, true, 0);
2348         cancel_delayed_work_sync(&chip->ttf_work);
2349         mutex_lock(&chip->ttf.lock);
2350         fg_circ_buf_clr(&chip->ttf.ibatt);
2351         fg_circ_buf_clr(&chip->ttf.vbatt);
2352         chip->ttf.last_ttf = 0;
2353         chip->ttf.last_ms = 0;
2354         mutex_unlock(&chip->ttf.lock);
2355         schedule_delayed_work(&chip->ttf_work, msecs_to_jiffies(delay_ms));
2356 }
2357
2358 static void restore_cycle_counter(struct fg_chip *chip)
2359 {
2360         int rc = 0, i;
2361         u8 data[2];
2362
2363         if (!chip->cyc_ctr.en)
2364                 return;
2365
2366         mutex_lock(&chip->cyc_ctr.lock);
2367         for (i = 0; i < BUCKET_COUNT; i++) {
2368                 rc = fg_sram_read(chip, CYCLE_COUNT_WORD + (i / 2),
2369                                 CYCLE_COUNT_OFFSET + (i % 2) * 2, data, 2,
2370                                 FG_IMA_DEFAULT);
2371                 if (rc < 0)
2372                         pr_err("failed to read bucket %d rc=%d\n", i, rc);
2373                 else
2374                         chip->cyc_ctr.count[i] = data[0] | data[1] << 8;
2375         }
2376         mutex_unlock(&chip->cyc_ctr.lock);
2377 }
2378
2379 static void clear_cycle_counter(struct fg_chip *chip)
2380 {
2381         int rc = 0, i;
2382
2383         if (!chip->cyc_ctr.en)
2384                 return;
2385
2386         mutex_lock(&chip->cyc_ctr.lock);
2387         memset(chip->cyc_ctr.count, 0, sizeof(chip->cyc_ctr.count));
2388         for (i = 0; i < BUCKET_COUNT; i++) {
2389                 chip->cyc_ctr.started[i] = false;
2390                 chip->cyc_ctr.last_soc[i] = 0;
2391         }
2392         rc = fg_sram_write(chip, CYCLE_COUNT_WORD, CYCLE_COUNT_OFFSET,
2393                         (u8 *)&chip->cyc_ctr.count,
2394                         sizeof(chip->cyc_ctr.count) / sizeof(u8 *),
2395                         FG_IMA_DEFAULT);
2396         if (rc < 0)
2397                 pr_err("failed to clear cycle counter rc=%d\n", rc);
2398
2399         mutex_unlock(&chip->cyc_ctr.lock);
2400 }
2401
2402 static int fg_inc_store_cycle_ctr(struct fg_chip *chip, int bucket)
2403 {
2404         int rc = 0;
2405         u16 cyc_count;
2406         u8 data[2];
2407
2408         if (bucket < 0 || (bucket > BUCKET_COUNT - 1))
2409                 return 0;
2410
2411         cyc_count = chip->cyc_ctr.count[bucket];
2412         cyc_count++;
2413         data[0] = cyc_count & 0xFF;
2414         data[1] = cyc_count >> 8;
2415
2416         rc = fg_sram_write(chip, CYCLE_COUNT_WORD + (bucket / 2),
2417                         CYCLE_COUNT_OFFSET + (bucket % 2) * 2, data, 2,
2418                         FG_IMA_DEFAULT);
2419         if (rc < 0) {
2420                 pr_err("failed to write BATT_CYCLE[%d] rc=%d\n",
2421                         bucket, rc);
2422                 return rc;
2423         }
2424
2425         chip->cyc_ctr.count[bucket] = cyc_count;
2426         fg_dbg(chip, FG_STATUS, "Stored count %d in bucket %d\n", cyc_count,
2427                 bucket);
2428
2429         return rc;
2430 }
2431
2432 static void fg_cycle_counter_update(struct fg_chip *chip)
2433 {
2434         int rc = 0, bucket, i, batt_soc;
2435
2436         if (!chip->cyc_ctr.en)
2437                 return;
2438
2439         mutex_lock(&chip->cyc_ctr.lock);
2440         rc = fg_get_sram_prop(chip, FG_SRAM_BATT_SOC, &batt_soc);
2441         if (rc < 0) {
2442                 pr_err("Failed to read battery soc rc: %d\n", rc);
2443                 goto out;
2444         }
2445
2446         /* We need only the most significant byte here */
2447         batt_soc = (u32)batt_soc >> 24;
2448
2449         /* Find out which bucket the SOC falls in */
2450         bucket = batt_soc / BUCKET_SOC_PCT;
2451
2452         if (chip->charge_status == POWER_SUPPLY_STATUS_CHARGING) {
2453                 if (!chip->cyc_ctr.started[bucket]) {
2454                         chip->cyc_ctr.started[bucket] = true;
2455                         chip->cyc_ctr.last_soc[bucket] = batt_soc;
2456                 }
2457         } else if (chip->charge_done || !is_input_present(chip)) {
2458                 for (i = 0; i < BUCKET_COUNT; i++) {
2459                         if (chip->cyc_ctr.started[i] &&
2460                                 batt_soc > chip->cyc_ctr.last_soc[i] + 2) {
2461                                 rc = fg_inc_store_cycle_ctr(chip, i);
2462                                 if (rc < 0)
2463                                         pr_err("Error in storing cycle_ctr rc: %d\n",
2464                                                 rc);
2465                                 chip->cyc_ctr.last_soc[i] = 0;
2466                                 chip->cyc_ctr.started[i] = false;
2467                         }
2468                 }
2469         }
2470
2471         fg_dbg(chip, FG_STATUS, "batt_soc: %d bucket: %d chg_status: %d\n",
2472                 batt_soc, bucket, chip->charge_status);
2473 out:
2474         mutex_unlock(&chip->cyc_ctr.lock);
2475 }
2476
2477 static int fg_get_cycle_count(struct fg_chip *chip)
2478 {
2479         int count;
2480
2481         if (!chip->cyc_ctr.en)
2482                 return 0;
2483
2484         if ((chip->cyc_ctr.id <= 0) || (chip->cyc_ctr.id > BUCKET_COUNT))
2485                 return -EINVAL;
2486
2487         mutex_lock(&chip->cyc_ctr.lock);
2488         count = chip->cyc_ctr.count[chip->cyc_ctr.id - 1];
2489         mutex_unlock(&chip->cyc_ctr.lock);
2490         return count;
2491 }
2492
2493 static void status_change_work(struct work_struct *work)
2494 {
2495         struct fg_chip *chip = container_of(work,
2496                         struct fg_chip, status_change_work);
2497         union power_supply_propval prop = {0, };
2498         int rc, batt_temp;
2499
2500         if (!batt_psy_initialized(chip)) {
2501                 fg_dbg(chip, FG_STATUS, "Charger not available?!\n");
2502                 goto out;
2503         }
2504
2505         rc = power_supply_get_property(chip->batt_psy, POWER_SUPPLY_PROP_STATUS,
2506                         &prop);
2507         if (rc < 0) {
2508                 pr_err("Error in getting charging status, rc=%d\n", rc);
2509                 goto out;
2510         }
2511
2512         chip->charge_status = prop.intval;
2513         rc = power_supply_get_property(chip->batt_psy,
2514                         POWER_SUPPLY_PROP_CHARGE_TYPE, &prop);
2515         if (rc < 0) {
2516                 pr_err("Error in getting charge type, rc=%d\n", rc);
2517                 goto out;
2518         }
2519
2520         chip->charge_type = prop.intval;
2521         rc = power_supply_get_property(chip->batt_psy,
2522                         POWER_SUPPLY_PROP_CHARGE_DONE, &prop);
2523         if (rc < 0) {
2524                 pr_err("Error in getting charge_done, rc=%d\n", rc);
2525                 goto out;
2526         }
2527
2528         chip->charge_done = prop.intval;
2529         fg_cycle_counter_update(chip);
2530         fg_cap_learning_update(chip);
2531
2532         rc = fg_charge_full_update(chip);
2533         if (rc < 0)
2534                 pr_err("Error in charge_full_update, rc=%d\n", rc);
2535
2536         rc = fg_adjust_recharge_soc(chip);
2537         if (rc < 0)
2538                 pr_err("Error in adjusting recharge_soc, rc=%d\n", rc);
2539
2540         rc = fg_adjust_recharge_voltage(chip);
2541         if (rc < 0)
2542                 pr_err("Error in adjusting recharge_voltage, rc=%d\n", rc);
2543
2544         rc = fg_adjust_ki_coeff_dischg(chip);
2545         if (rc < 0)
2546                 pr_err("Error in adjusting ki_coeff_dischg, rc=%d\n", rc);
2547
2548         rc = fg_esr_fcc_config(chip);
2549         if (rc < 0)
2550                 pr_err("Error in adjusting FCC for ESR, rc=%d\n", rc);
2551
2552         rc = fg_get_battery_temp(chip, &batt_temp);
2553         if (!rc) {
2554                 rc = fg_slope_limit_config(chip, batt_temp);
2555                 if (rc < 0)
2556                         pr_err("Error in configuring slope limiter rc:%d\n",
2557                                 rc);
2558
2559                 rc = fg_adjust_ki_coeff_full_soc(chip, batt_temp);
2560                 if (rc < 0)
2561                         pr_err("Error in configuring ki_coeff_full_soc rc:%d\n",
2562                                 rc);
2563         }
2564
2565         fg_ttf_update(chip);
2566
2567 out:
2568         fg_dbg(chip, FG_POWER_SUPPLY, "charge_status:%d charge_type:%d charge_done:%d\n",
2569                 chip->charge_status, chip->charge_type, chip->charge_done);
2570         pm_relax(chip->dev);
2571 }
2572
2573 static int fg_bp_params_config(struct fg_chip *chip)
2574 {
2575         int rc = 0;
2576         u8 buf;
2577
2578         /* This SRAM register is only present in v2.0 and above */
2579         if (!(chip->wa_flags & PMI8998_V1_REV_WA) &&
2580                                         chip->bp.float_volt_uv > 0) {
2581                 fg_encode(chip->sp, FG_SRAM_FLOAT_VOLT,
2582                         chip->bp.float_volt_uv / 1000, &buf);
2583                 rc = fg_sram_write(chip, chip->sp[FG_SRAM_FLOAT_VOLT].addr_word,
2584                         chip->sp[FG_SRAM_FLOAT_VOLT].addr_byte, &buf,
2585                         chip->sp[FG_SRAM_FLOAT_VOLT].len, FG_IMA_DEFAULT);
2586                 if (rc < 0) {
2587                         pr_err("Error in writing float_volt, rc=%d\n", rc);
2588                         return rc;
2589                 }
2590         }
2591
2592         if (chip->bp.vbatt_full_mv > 0) {
2593                 rc = fg_set_constant_chg_voltage(chip,
2594                                 chip->bp.vbatt_full_mv * 1000);
2595                 if (rc < 0)
2596                         return rc;
2597         }
2598
2599         return rc;
2600 }
2601
2602 #define PROFILE_LOAD_BIT        BIT(0)
2603 #define BOOTLOADER_LOAD_BIT     BIT(1)
2604 #define BOOTLOADER_RESTART_BIT  BIT(2)
2605 #define HLOS_RESTART_BIT        BIT(3)
2606 static bool is_profile_load_required(struct fg_chip *chip)
2607 {
2608         u8 buf[PROFILE_COMP_LEN], val;
2609         bool profiles_same = false;
2610         int rc;
2611
2612         rc = fg_sram_read(chip, PROFILE_INTEGRITY_WORD,
2613                         PROFILE_INTEGRITY_OFFSET, &val, 1, FG_IMA_DEFAULT);
2614         if (rc < 0) {
2615                 pr_err("failed to read profile integrity rc=%d\n", rc);
2616                 return false;
2617         }
2618
2619         /* Check if integrity bit is set */
2620         if (val & PROFILE_LOAD_BIT) {
2621                 fg_dbg(chip, FG_STATUS, "Battery profile integrity bit is set\n");
2622
2623                 /* Whitelist the values */
2624                 val &= ~PROFILE_LOAD_BIT;
2625                 if (val != HLOS_RESTART_BIT && val != BOOTLOADER_LOAD_BIT &&
2626                         val != (BOOTLOADER_LOAD_BIT | BOOTLOADER_RESTART_BIT)) {
2627                         val |= PROFILE_LOAD_BIT;
2628                         pr_warn("Garbage value in profile integrity word: 0x%x\n",
2629                                 val);
2630                         return true;
2631                 }
2632
2633                 rc = fg_sram_read(chip, PROFILE_LOAD_WORD, PROFILE_LOAD_OFFSET,
2634                                 buf, PROFILE_COMP_LEN, FG_IMA_DEFAULT);
2635                 if (rc < 0) {
2636                         pr_err("Error in reading battery profile, rc:%d\n", rc);
2637                         return false;
2638                 }
2639                 profiles_same = memcmp(chip->batt_profile, buf,
2640                                         PROFILE_COMP_LEN) == 0;
2641                 if (profiles_same) {
2642                         fg_dbg(chip, FG_STATUS, "Battery profile is same, not loading it\n");
2643                         return false;
2644                 }
2645
2646                 if (!chip->dt.force_load_profile) {
2647                         pr_warn("Profiles doesn't match, skipping loading it since force_load_profile is disabled\n");
2648                         if (fg_profile_dump) {
2649                                 pr_info("FG: loaded profile:\n");
2650                                 dump_sram(buf, PROFILE_LOAD_WORD,
2651                                         PROFILE_COMP_LEN);
2652                                 pr_info("FG: available profile:\n");
2653                                 dump_sram(chip->batt_profile, PROFILE_LOAD_WORD,
2654                                         PROFILE_LEN);
2655                         }
2656                         return false;
2657                 }
2658
2659                 fg_dbg(chip, FG_STATUS, "Profiles are different, loading the correct one\n");
2660         } else {
2661                 fg_dbg(chip, FG_STATUS, "Profile integrity bit is not set\n");
2662                 if (fg_profile_dump) {
2663                         pr_info("FG: profile to be loaded:\n");
2664                         dump_sram(chip->batt_profile, PROFILE_LOAD_WORD,
2665                                 PROFILE_LEN);
2666                 }
2667         }
2668         return true;
2669 }
2670
2671 static void clear_battery_profile(struct fg_chip *chip)
2672 {
2673         u8 val = 0;
2674         int rc;
2675
2676         rc = fg_sram_write(chip, PROFILE_INTEGRITY_WORD,
2677                         PROFILE_INTEGRITY_OFFSET, &val, 1, FG_IMA_DEFAULT);
2678         if (rc < 0)
2679                 pr_err("failed to write profile integrity rc=%d\n", rc);
2680 }
2681
2682 #define SOC_READY_WAIT_MS               2000
2683 static int __fg_restart(struct fg_chip *chip)
2684 {
2685         int rc, msoc;
2686         bool tried_again = false;
2687
2688         rc = fg_get_prop_capacity(chip, &msoc);
2689         if (rc < 0) {
2690                 pr_err("Error in getting capacity, rc=%d\n", rc);
2691                 return rc;
2692         }
2693
2694         chip->last_soc = msoc;
2695         chip->fg_restarting = true;
2696         reinit_completion(&chip->soc_ready);
2697         rc = fg_masked_write(chip, BATT_SOC_RESTART(chip), RESTART_GO_BIT,
2698                         RESTART_GO_BIT);
2699         if (rc < 0) {
2700                 pr_err("Error in writing to %04x, rc=%d\n",
2701                         BATT_SOC_RESTART(chip), rc);
2702                 goto out;
2703         }
2704
2705 wait:
2706         rc = wait_for_completion_interruptible_timeout(&chip->soc_ready,
2707                 msecs_to_jiffies(SOC_READY_WAIT_MS));
2708
2709         /* If we were interrupted wait again one more time. */
2710         if (rc == -ERESTARTSYS && !tried_again) {
2711                 tried_again = true;
2712                 goto wait;
2713         } else if (rc <= 0) {
2714                 pr_err("wait for soc_ready timed out rc=%d\n", rc);
2715         }
2716
2717         rc = fg_masked_write(chip, BATT_SOC_RESTART(chip), RESTART_GO_BIT, 0);
2718         if (rc < 0) {
2719                 pr_err("Error in writing to %04x, rc=%d\n",
2720                         BATT_SOC_RESTART(chip), rc);
2721                 goto out;
2722         }
2723 out:
2724         chip->fg_restarting = false;
2725         return rc;
2726 }
2727
2728 static void profile_load_work(struct work_struct *work)
2729 {
2730         struct fg_chip *chip = container_of(work,
2731                                 struct fg_chip,
2732                                 profile_load_work.work);
2733         u8 buf[2], val;
2734         int rc;
2735
2736         vote(chip->awake_votable, PROFILE_LOAD, true, 0);
2737
2738         rc = fg_get_batt_id(chip);
2739         if (rc < 0) {
2740                 pr_err("Error in getting battery id, rc:%d\n", rc);
2741                 goto out;
2742         }
2743
2744         rc = fg_get_batt_profile(chip);
2745         if (rc < 0) {
2746                 pr_warn("profile for batt_id=%dKOhms not found..using OTP, rc:%d\n",
2747                         chip->batt_id_ohms / 1000, rc);
2748                 goto out;
2749         }
2750
2751         if (!chip->profile_available)
2752                 goto out;
2753
2754         if (!is_profile_load_required(chip))
2755                 goto done;
2756
2757         clear_cycle_counter(chip);
2758         mutex_lock(&chip->cl.lock);
2759         chip->cl.learned_cc_uah = 0;
2760         chip->cl.active = false;
2761         mutex_unlock(&chip->cl.lock);
2762
2763         fg_dbg(chip, FG_STATUS, "profile loading started\n");
2764         rc = fg_masked_write(chip, BATT_SOC_RESTART(chip), RESTART_GO_BIT, 0);
2765         if (rc < 0) {
2766                 pr_err("Error in writing to %04x, rc=%d\n",
2767                         BATT_SOC_RESTART(chip), rc);
2768                 goto out;
2769         }
2770
2771         /* load battery profile */
2772         rc = fg_sram_write(chip, PROFILE_LOAD_WORD, PROFILE_LOAD_OFFSET,
2773                         chip->batt_profile, PROFILE_LEN, FG_IMA_ATOMIC);
2774         if (rc < 0) {
2775                 pr_err("Error in writing battery profile, rc:%d\n", rc);
2776                 goto out;
2777         }
2778
2779         rc = __fg_restart(chip);
2780         if (rc < 0) {
2781                 pr_err("Error in restarting FG, rc=%d\n", rc);
2782                 goto out;
2783         }
2784
2785         fg_dbg(chip, FG_STATUS, "SOC is ready\n");
2786
2787         /* Set the profile integrity bit */
2788         val = HLOS_RESTART_BIT | PROFILE_LOAD_BIT;
2789         rc = fg_sram_write(chip, PROFILE_INTEGRITY_WORD,
2790                         PROFILE_INTEGRITY_OFFSET, &val, 1, FG_IMA_DEFAULT);
2791         if (rc < 0) {
2792                 pr_err("failed to write profile integrity rc=%d\n", rc);
2793                 goto out;
2794         }
2795
2796 done:
2797         rc = fg_bp_params_config(chip);
2798         if (rc < 0)
2799                 pr_err("Error in configuring battery profile params, rc:%d\n",
2800                         rc);
2801
2802         rc = fg_sram_read(chip, NOM_CAP_WORD, NOM_CAP_OFFSET, buf, 2,
2803                         FG_IMA_DEFAULT);
2804         if (rc < 0) {
2805                 pr_err("Error in reading %04x[%d] rc=%d\n", NOM_CAP_WORD,
2806                         NOM_CAP_OFFSET, rc);
2807         } else {
2808                 chip->cl.nom_cap_uah = (int)(buf[0] | buf[1] << 8) * 1000;
2809                 rc = fg_load_learned_cap_from_sram(chip);
2810                 if (rc < 0)
2811                         pr_err("Error in loading capacity learning data, rc:%d\n",
2812                                 rc);
2813         }
2814
2815         batt_psy_initialized(chip);
2816         fg_notify_charger(chip);
2817         chip->profile_loaded = true;
2818         fg_dbg(chip, FG_STATUS, "profile loaded successfully");
2819 out:
2820         chip->soc_reporting_ready = true;
2821         vote(chip->awake_votable, PROFILE_LOAD, false, 0);
2822 }
2823
2824 static void sram_dump_work(struct work_struct *work)
2825 {
2826         struct fg_chip *chip = container_of(work, struct fg_chip,
2827                                             sram_dump_work.work);
2828         u8 buf[FG_SRAM_LEN];
2829         int rc;
2830         s64 timestamp_ms, quotient;
2831         s32 remainder;
2832
2833         rc = fg_sram_read(chip, 0, 0, buf, FG_SRAM_LEN, FG_IMA_DEFAULT);
2834         if (rc < 0) {
2835                 pr_err("Error in reading FG SRAM, rc:%d\n", rc);
2836                 goto resched;
2837         }
2838
2839         timestamp_ms = ktime_to_ms(ktime_get_boottime());
2840         quotient = div_s64_rem(timestamp_ms, 1000, &remainder);
2841         fg_dbg(chip, FG_STATUS, "SRAM Dump Started at %lld.%d\n",
2842                 quotient, remainder);
2843         dump_sram(buf, 0, FG_SRAM_LEN);
2844         timestamp_ms = ktime_to_ms(ktime_get_boottime());
2845         quotient = div_s64_rem(timestamp_ms, 1000, &remainder);
2846         fg_dbg(chip, FG_STATUS, "SRAM Dump done at %lld.%d\n",
2847                 quotient, remainder);
2848 resched:
2849         schedule_delayed_work(&chip->sram_dump_work,
2850                         msecs_to_jiffies(fg_sram_dump_period_ms));
2851 }
2852
2853 static int fg_sram_dump_sysfs(const char *val, const struct kernel_param *kp)
2854 {
2855         int rc;
2856         struct power_supply *bms_psy;
2857         struct fg_chip *chip;
2858         bool old_val = fg_sram_dump;
2859
2860         rc = param_set_bool(val, kp);
2861         if (rc) {
2862                 pr_err("Unable to set fg_sram_dump: %d\n", rc);
2863                 return rc;
2864         }
2865
2866         if (fg_sram_dump == old_val)
2867                 return 0;
2868
2869         bms_psy = power_supply_get_by_name("bms");
2870         if (!bms_psy) {
2871                 pr_err("bms psy not found\n");
2872                 return -ENODEV;
2873         }
2874
2875         chip = power_supply_get_drvdata(bms_psy);
2876         if (fg_sram_dump)
2877                 schedule_delayed_work(&chip->sram_dump_work,
2878                                 msecs_to_jiffies(fg_sram_dump_period_ms));
2879         else
2880                 cancel_delayed_work_sync(&chip->sram_dump_work);
2881
2882         return 0;
2883 }
2884
2885 static struct kernel_param_ops fg_sram_dump_ops = {
2886         .set = fg_sram_dump_sysfs,
2887         .get = param_get_bool,
2888 };
2889
2890 module_param_cb(sram_dump_en, &fg_sram_dump_ops, &fg_sram_dump, 0644);
2891
2892 static int fg_restart_sysfs(const char *val, const struct kernel_param *kp)
2893 {
2894         int rc;
2895         struct power_supply *bms_psy;
2896         struct fg_chip *chip;
2897
2898         rc = param_set_int(val, kp);
2899         if (rc) {
2900                 pr_err("Unable to set fg_restart: %d\n", rc);
2901                 return rc;
2902         }
2903
2904         if (fg_restart != 1) {
2905                 pr_err("Bad value %d\n", fg_restart);
2906                 return -EINVAL;
2907         }
2908
2909         bms_psy = power_supply_get_by_name("bms");
2910         if (!bms_psy) {
2911                 pr_err("bms psy not found\n");
2912                 return 0;
2913         }
2914
2915         chip = power_supply_get_drvdata(bms_psy);
2916         rc = __fg_restart(chip);
2917         if (rc < 0) {
2918                 pr_err("Error in restarting FG, rc=%d\n", rc);
2919                 return rc;
2920         }
2921
2922         pr_info("FG restart done\n");
2923         return rc;
2924 }
2925
2926 static struct kernel_param_ops fg_restart_ops = {
2927         .set = fg_restart_sysfs,
2928         .get = param_get_int,
2929 };
2930
2931 module_param_cb(restart, &fg_restart_ops, &fg_restart, 0644);
2932
2933 #define HOURS_TO_SECONDS        3600
2934 #define OCV_SLOPE_UV            10869
2935 #define MILLI_UNIT              1000
2936 #define MICRO_UNIT              1000000
2937 #define NANO_UNIT               1000000000
2938 static int fg_get_time_to_full_locked(struct fg_chip *chip, int *val)
2939 {
2940         int rc, ibatt_avg, vbatt_avg, rbatt, msoc, full_soc, act_cap_mah,
2941                 i_cc2cv, soc_cc2cv, tau, divisor, iterm, ttf_mode,
2942                 i, soc_per_step, msoc_this_step, msoc_next_step,
2943                 ibatt_this_step, t_predicted_this_step, ttf_slope,
2944                 t_predicted_cv, t_predicted = 0;
2945         s64 delta_ms;
2946
2947         if (chip->bp.float_volt_uv <= 0) {
2948                 pr_err("battery profile is not loaded\n");
2949                 return -ENODATA;
2950         }
2951
2952         if (!batt_psy_initialized(chip)) {
2953                 fg_dbg(chip, FG_TTF, "charger is not available\n");
2954                 return -ENODATA;
2955         }
2956
2957         rc = fg_get_prop_capacity(chip, &msoc);
2958         if (rc < 0) {
2959                 pr_err("failed to get msoc rc=%d\n", rc);
2960                 return rc;
2961         }
2962         fg_dbg(chip, FG_TTF, "msoc=%d\n", msoc);
2963
2964         /* the battery is considered full if the SOC is 100% */
2965         if (msoc >= 100) {
2966                 *val = 0;
2967                 return 0;
2968         }
2969
2970         if (is_qnovo_en(chip))
2971                 ttf_mode = TTF_MODE_QNOVO;
2972         else
2973                 ttf_mode = TTF_MODE_NORMAL;
2974
2975         /* when switching TTF algorithms the TTF needs to be reset */
2976         if (chip->ttf.mode != ttf_mode) {
2977                 fg_circ_buf_clr(&chip->ttf.ibatt);
2978                 fg_circ_buf_clr(&chip->ttf.vbatt);
2979                 chip->ttf.last_ttf = 0;
2980                 chip->ttf.last_ms = 0;
2981                 chip->ttf.mode = ttf_mode;
2982         }
2983
2984         /* at least 10 samples are required to produce a stable IBATT */
2985         if (chip->ttf.ibatt.size < 10) {
2986                 *val = -1;
2987                 return 0;
2988         }
2989
2990         rc = fg_circ_buf_median(&chip->ttf.ibatt, &ibatt_avg);
2991         if (rc < 0) {
2992                 pr_err("failed to get IBATT AVG rc=%d\n", rc);
2993                 return rc;
2994         }
2995
2996         rc = fg_circ_buf_median(&chip->ttf.vbatt, &vbatt_avg);
2997         if (rc < 0) {
2998                 pr_err("failed to get VBATT AVG rc=%d\n", rc);
2999                 return rc;
3000         }
3001
3002         ibatt_avg = -ibatt_avg / MILLI_UNIT;
3003         vbatt_avg /= MILLI_UNIT;
3004
3005         /* clamp ibatt_avg to iterm */
3006         if (ibatt_avg < abs(chip->dt.sys_term_curr_ma))
3007                 ibatt_avg = abs(chip->dt.sys_term_curr_ma);
3008
3009         fg_dbg(chip, FG_TTF, "ibatt_avg=%d\n", ibatt_avg);
3010         fg_dbg(chip, FG_TTF, "vbatt_avg=%d\n", vbatt_avg);
3011
3012         rc = fg_get_battery_resistance(chip, &rbatt);
3013         if (rc < 0) {
3014                 pr_err("failed to get battery resistance rc=%d\n", rc);
3015                 return rc;
3016         }
3017
3018         rbatt /= MILLI_UNIT;
3019         fg_dbg(chip, FG_TTF, "rbatt=%d\n", rbatt);
3020
3021         rc = fg_get_sram_prop(chip, FG_SRAM_ACT_BATT_CAP, &act_cap_mah);
3022         if (rc < 0) {
3023                 pr_err("failed to get ACT_BATT_CAP rc=%d\n", rc);
3024                 return rc;
3025         }
3026
3027         rc = fg_get_sram_prop(chip, FG_SRAM_FULL_SOC, &full_soc);
3028         if (rc < 0) {
3029                 pr_err("failed to get full soc rc=%d\n", rc);
3030                 return rc;
3031         }
3032         full_soc = DIV_ROUND_CLOSEST(((u16)full_soc >> 8) * FULL_CAPACITY,
3033                                                                 FULL_SOC_RAW);
3034         act_cap_mah = full_soc * act_cap_mah / 100;
3035         fg_dbg(chip, FG_TTF, "act_cap_mah=%d\n", act_cap_mah);
3036
3037         /* estimated battery current at the CC to CV transition */
3038         switch (chip->ttf.mode) {
3039         case TTF_MODE_NORMAL:
3040                 i_cc2cv = ibatt_avg * vbatt_avg /
3041                         max(MILLI_UNIT, chip->bp.float_volt_uv / MILLI_UNIT);
3042                 break;
3043         case TTF_MODE_QNOVO:
3044                 i_cc2cv = min(
3045                         chip->ttf.cc_step.arr[MAX_CC_STEPS - 1] / MILLI_UNIT,
3046                         ibatt_avg * vbatt_avg /
3047                         max(MILLI_UNIT, chip->bp.float_volt_uv / MILLI_UNIT));
3048                 break;
3049         default:
3050                 pr_err("TTF mode %d is not supported\n", chip->ttf.mode);
3051                 break;
3052         }
3053         fg_dbg(chip, FG_TTF, "i_cc2cv=%d\n", i_cc2cv);
3054
3055         /* if we are already in CV state then we can skip estimating CC */
3056         if (chip->charge_type == POWER_SUPPLY_CHARGE_TYPE_TAPER)
3057                 goto cv_estimate;
3058
3059         /* estimated SOC at the CC to CV transition */
3060         soc_cc2cv = DIV_ROUND_CLOSEST(rbatt * i_cc2cv, OCV_SLOPE_UV);
3061         soc_cc2cv = 100 - soc_cc2cv;
3062         fg_dbg(chip, FG_TTF, "soc_cc2cv=%d\n", soc_cc2cv);
3063
3064         switch (chip->ttf.mode) {
3065         case TTF_MODE_NORMAL:
3066                 if (soc_cc2cv - msoc <= 0)
3067                         goto cv_estimate;
3068
3069                 divisor = max(100, (ibatt_avg + i_cc2cv) / 2 * 100);
3070                 t_predicted = div_s64((s64)act_cap_mah * (soc_cc2cv - msoc) *
3071                                                 HOURS_TO_SECONDS, divisor);
3072                 break;
3073         case TTF_MODE_QNOVO:
3074                 soc_per_step = 100 / MAX_CC_STEPS;
3075                 for (i = msoc / soc_per_step; i < MAX_CC_STEPS - 1; ++i) {
3076                         msoc_next_step = (i + 1) * soc_per_step;
3077                         if (i == msoc / soc_per_step)
3078                                 msoc_this_step = msoc;
3079                         else
3080                                 msoc_this_step = i * soc_per_step;
3081
3082                         /* scale ibatt by 85% to account for discharge pulses */
3083                         ibatt_this_step = min(
3084                                         chip->ttf.cc_step.arr[i] / MILLI_UNIT,
3085                                         ibatt_avg) * 85 / 100;
3086                         divisor = max(100, ibatt_this_step * 100);
3087                         t_predicted_this_step = div_s64((s64)act_cap_mah *
3088                                         (msoc_next_step - msoc_this_step) *
3089                                         HOURS_TO_SECONDS, divisor);
3090                         t_predicted += t_predicted_this_step;
3091                         fg_dbg(chip, FG_TTF, "[%d, %d] ma=%d t=%d\n",
3092                                 msoc_this_step, msoc_next_step,
3093                                 ibatt_this_step, t_predicted_this_step);
3094                 }
3095                 break;
3096         default:
3097                 pr_err("TTF mode %d is not supported\n", chip->ttf.mode);
3098                 break;
3099         }
3100
3101 cv_estimate:
3102         fg_dbg(chip, FG_TTF, "t_predicted_cc=%d\n", t_predicted);
3103
3104         iterm = max(100, abs(chip->dt.sys_term_curr_ma) + 200);
3105         fg_dbg(chip, FG_TTF, "iterm=%d\n", iterm);
3106
3107         if (chip->charge_type == POWER_SUPPLY_CHARGE_TYPE_TAPER)
3108                 tau = max(MILLI_UNIT, ibatt_avg * MILLI_UNIT / iterm);
3109         else
3110                 tau = max(MILLI_UNIT, i_cc2cv * MILLI_UNIT / iterm);
3111
3112         rc = fg_lerp(fg_ln_table, ARRAY_SIZE(fg_ln_table), tau, &tau);
3113         if (rc < 0) {
3114                 pr_err("failed to interpolate tau rc=%d\n", rc);
3115                 return rc;
3116         }
3117
3118         /* tau is scaled linearly from 95% to 100% SOC */
3119         if (msoc >= 95)
3120                 tau = tau * 2 * (100 - msoc) / 10;
3121
3122         fg_dbg(chip, FG_TTF, "tau=%d\n", tau);
3123         t_predicted_cv = div_s64((s64)act_cap_mah * rbatt * tau *
3124                                                 HOURS_TO_SECONDS, NANO_UNIT);
3125         fg_dbg(chip, FG_TTF, "t_predicted_cv=%d\n", t_predicted_cv);
3126         t_predicted += t_predicted_cv;
3127
3128         fg_dbg(chip, FG_TTF, "t_predicted_prefilter=%d\n", t_predicted);
3129         if (chip->ttf.last_ms != 0) {
3130                 delta_ms = ktime_ms_delta(ktime_get_boottime(),
3131                                           ms_to_ktime(chip->ttf.last_ms));
3132                 if (delta_ms > 10000) {
3133                         ttf_slope = div64_s64(
3134                                 (s64)(t_predicted - chip->ttf.last_ttf) *
3135                                 MICRO_UNIT, delta_ms);
3136                         if (ttf_slope > -100)
3137                                 ttf_slope = -100;
3138                         else if (ttf_slope < -2000)
3139                                 ttf_slope = -2000;
3140
3141                         t_predicted = div_s64(
3142                                 (s64)ttf_slope * delta_ms, MICRO_UNIT) +
3143                                 chip->ttf.last_ttf;
3144                         fg_dbg(chip, FG_TTF, "ttf_slope=%d\n", ttf_slope);
3145                 } else {
3146                         t_predicted = chip->ttf.last_ttf;
3147                 }
3148         }
3149
3150         /* clamp the ttf to 0 */
3151         if (t_predicted < 0)
3152                 t_predicted = 0;
3153
3154         fg_dbg(chip, FG_TTF, "t_predicted_postfilter=%d\n", t_predicted);
3155         *val = t_predicted;
3156         return 0;
3157 }
3158
3159 static int fg_get_time_to_full(struct fg_chip *chip, int *val)
3160 {
3161         int rc;
3162
3163         mutex_lock(&chip->ttf.lock);
3164         rc = fg_get_time_to_full_locked(chip, val);
3165         mutex_unlock(&chip->ttf.lock);
3166         return rc;
3167 }
3168
3169 #define CENTI_ICORRECT_C0       105
3170 #define CENTI_ICORRECT_C1       20
3171 static int fg_get_time_to_empty(struct fg_chip *chip, int *val)
3172 {
3173         int rc, ibatt_avg, msoc, full_soc, act_cap_mah, divisor;
3174
3175         rc = fg_circ_buf_median(&chip->ttf.ibatt, &ibatt_avg);
3176         if (rc < 0) {
3177                 /* try to get instantaneous current */
3178                 rc = fg_get_battery_current(chip, &ibatt_avg);
3179                 if (rc < 0) {
3180                         pr_err("failed to get battery current, rc=%d\n", rc);
3181                         return rc;
3182                 }
3183         }
3184
3185         ibatt_avg /= MILLI_UNIT;
3186         /* clamp ibatt_avg to 100mA */
3187         if (ibatt_avg < 100)
3188                 ibatt_avg = 100;
3189
3190         rc = fg_get_prop_capacity(chip, &msoc);
3191         if (rc < 0) {
3192                 pr_err("Error in getting capacity, rc=%d\n", rc);
3193                 return rc;
3194         }
3195
3196         rc = fg_get_sram_prop(chip, FG_SRAM_ACT_BATT_CAP, &act_cap_mah);
3197         if (rc < 0) {
3198                 pr_err("Error in getting ACT_BATT_CAP, rc=%d\n", rc);
3199                 return rc;
3200         }
3201
3202         rc = fg_get_sram_prop(chip, FG_SRAM_FULL_SOC, &full_soc);
3203         if (rc < 0) {
3204                 pr_err("failed to get full soc rc=%d\n", rc);
3205                 return rc;
3206         }
3207         full_soc = DIV_ROUND_CLOSEST(((u16)full_soc >> 8) * FULL_CAPACITY,
3208                                                                 FULL_SOC_RAW);
3209         act_cap_mah = full_soc * act_cap_mah / 100;
3210
3211         divisor = CENTI_ICORRECT_C0 * 100 + CENTI_ICORRECT_C1 * msoc;
3212         divisor = ibatt_avg * divisor / 100;
3213         divisor = max(100, divisor);
3214         *val = act_cap_mah * msoc * HOURS_TO_SECONDS / divisor;
3215         return 0;
3216 }
3217
3218 static int fg_update_maint_soc(struct fg_chip *chip)
3219 {
3220         int rc = 0, msoc;
3221
3222         if (!chip->dt.linearize_soc)
3223                 return 0;
3224
3225         mutex_lock(&chip->charge_full_lock);
3226         if (chip->delta_soc <= 0)
3227                 goto out;
3228
3229         rc = fg_get_msoc(chip, &msoc);
3230         if (rc < 0) {
3231                 pr_err("Error in getting msoc, rc=%d\n", rc);
3232                 goto out;
3233         }
3234
3235         if (msoc > chip->maint_soc) {
3236                 /*
3237                  * When the monotonic SOC goes above maintenance SOC, we should
3238                  * stop showing the maintenance SOC.
3239                  */
3240                 chip->delta_soc = 0;
3241                 chip->maint_soc = 0;
3242         } else if (msoc <= chip->last_msoc) {
3243                 /* MSOC is decreasing. Decrease maintenance SOC as well */
3244                 chip->maint_soc -= 1;
3245                 if (!(msoc % 10)) {
3246                         /*
3247                          * Reduce the maintenance SOC additionally by 1 whenever
3248                          * it crosses a SOC multiple of 10.
3249                          */
3250                         chip->maint_soc -= 1;
3251                         chip->delta_soc -= 1;
3252                 }
3253         }
3254
3255         fg_dbg(chip, FG_IRQ, "msoc: %d last_msoc: %d maint_soc: %d delta_soc: %d\n",
3256                 msoc, chip->last_msoc, chip->maint_soc, chip->delta_soc);
3257         chip->last_msoc = msoc;
3258 out:
3259         mutex_unlock(&chip->charge_full_lock);
3260         return rc;
3261 }
3262
3263 static int fg_esr_validate(struct fg_chip *chip)
3264 {
3265         int rc, esr_uohms;
3266         u8 buf[2];
3267
3268         if (chip->dt.esr_clamp_mohms <= 0)
3269                 return 0;
3270
3271         rc = fg_get_sram_prop(chip, FG_SRAM_ESR, &esr_uohms);
3272         if (rc < 0) {
3273                 pr_err("failed to get ESR, rc=%d\n", rc);
3274                 return rc;
3275         }
3276
3277         if (esr_uohms >= chip->dt.esr_clamp_mohms * 1000) {
3278                 pr_debug("ESR %d is > ESR_clamp\n", esr_uohms);
3279                 return 0;
3280         }
3281
3282         esr_uohms = chip->dt.esr_clamp_mohms * 1000;
3283         fg_encode(chip->sp, FG_SRAM_ESR, esr_uohms, buf);
3284         rc = fg_sram_write(chip, chip->sp[FG_SRAM_ESR].addr_word,
3285                         chip->sp[FG_SRAM_ESR].addr_byte, buf,
3286                         chip->sp[FG_SRAM_ESR].len, FG_IMA_DEFAULT);
3287         if (rc < 0) {
3288                 pr_err("Error in writing ESR, rc=%d\n", rc);
3289                 return rc;
3290         }
3291
3292         fg_dbg(chip, FG_STATUS, "ESR clamped to %duOhms\n", esr_uohms);
3293         return 0;
3294 }
3295
3296 static int fg_force_esr_meas(struct fg_chip *chip)
3297 {
3298         int rc;
3299         int esr_uohms;
3300
3301         mutex_lock(&chip->qnovo_esr_ctrl_lock);
3302         /* force esr extraction enable */
3303         rc = fg_sram_masked_write(chip, ESR_EXTRACTION_ENABLE_WORD,
3304                         ESR_EXTRACTION_ENABLE_OFFSET, BIT(0), BIT(0),
3305                         FG_IMA_DEFAULT);
3306         if (rc < 0) {
3307                 pr_err("failed to enable esr extn rc=%d\n", rc);
3308                 goto out;
3309         }
3310
3311         rc = fg_masked_write(chip, BATT_INFO_QNOVO_CFG(chip),
3312                         LD_REG_CTRL_BIT, 0);
3313         if (rc < 0) {
3314                 pr_err("Error in configuring qnovo_cfg rc=%d\n", rc);
3315                 goto out;
3316         }
3317
3318         rc = fg_masked_write(chip, BATT_INFO_TM_MISC1(chip),
3319                         ESR_REQ_CTL_BIT | ESR_REQ_CTL_EN_BIT,
3320                         ESR_REQ_CTL_BIT | ESR_REQ_CTL_EN_BIT);
3321         if (rc < 0) {
3322                 pr_err("Error in configuring force ESR rc=%d\n", rc);
3323                 goto out;
3324         }
3325
3326         /*
3327          * Release and grab the lock again after 1.5 seconds so that prepare
3328          * callback can succeed if the request comes in between.
3329          */
3330         mutex_unlock(&chip->qnovo_esr_ctrl_lock);
3331
3332         /* wait 1.5 seconds for hw to measure ESR */
3333         msleep(1500);
3334
3335         mutex_lock(&chip->qnovo_esr_ctrl_lock);
3336         rc = fg_masked_write(chip, BATT_INFO_TM_MISC1(chip),
3337                         ESR_REQ_CTL_BIT | ESR_REQ_CTL_EN_BIT,
3338                         0);
3339         if (rc < 0) {
3340                 pr_err("Error in restoring force ESR rc=%d\n", rc);
3341                 goto out;
3342         }
3343
3344         /* If qnovo is disabled, then leave ESR extraction enabled */
3345         if (!chip->qnovo_enable)
3346                 goto done;
3347
3348         rc = fg_masked_write(chip, BATT_INFO_QNOVO_CFG(chip),
3349                         LD_REG_CTRL_BIT, LD_REG_CTRL_BIT);
3350         if (rc < 0) {
3351                 pr_err("Error in restoring qnovo_cfg rc=%d\n", rc);
3352                 goto out;
3353         }
3354
3355         /* force esr extraction disable */
3356         rc = fg_sram_masked_write(chip, ESR_EXTRACTION_ENABLE_WORD,
3357                         ESR_EXTRACTION_ENABLE_OFFSET, BIT(0), 0,
3358                         FG_IMA_DEFAULT);
3359         if (rc < 0) {
3360                 pr_err("failed to disable esr extn rc=%d\n", rc);
3361                 goto out;
3362         }
3363
3364 done:
3365         fg_get_battery_resistance(chip, &esr_uohms);
3366         fg_dbg(chip, FG_STATUS, "ESR uohms = %d\n", esr_uohms);
3367 out:
3368         mutex_unlock(&chip->qnovo_esr_ctrl_lock);
3369         return rc;
3370 }
3371
3372 static int fg_prepare_for_qnovo(struct fg_chip *chip, int qnovo_enable)
3373 {
3374         int rc = 0;
3375
3376         mutex_lock(&chip->qnovo_esr_ctrl_lock);
3377         /* force esr extraction disable when qnovo enables */
3378         rc = fg_sram_masked_write(chip, ESR_EXTRACTION_ENABLE_WORD,
3379                         ESR_EXTRACTION_ENABLE_OFFSET,
3380                         BIT(0), qnovo_enable ? 0 : BIT(0),
3381                         FG_IMA_DEFAULT);
3382         if (rc < 0) {
3383                 pr_err("Error in configuring esr extraction rc=%d\n", rc);
3384                 goto out;
3385         }
3386
3387         rc = fg_masked_write(chip, BATT_INFO_QNOVO_CFG(chip),
3388                         LD_REG_CTRL_BIT,
3389                         qnovo_enable ? LD_REG_CTRL_BIT : 0);
3390         if (rc < 0) {
3391                 pr_err("Error in configuring qnovo_cfg rc=%d\n", rc);
3392                 goto out;
3393         }
3394
3395         fg_dbg(chip, FG_STATUS, "%s for Qnovo\n",
3396                 qnovo_enable ? "Prepared" : "Unprepared");
3397         chip->qnovo_enable = qnovo_enable;
3398 out:
3399         mutex_unlock(&chip->qnovo_esr_ctrl_lock);
3400         return rc;
3401 }
3402
3403 static void ttf_work(struct work_struct *work)
3404 {
3405         struct fg_chip *chip = container_of(work, struct fg_chip,
3406                                             ttf_work.work);
3407         int rc, ibatt_now, vbatt_now, ttf;
3408         ktime_t ktime_now;
3409
3410         mutex_lock(&chip->ttf.lock);
3411         if (chip->charge_status != POWER_SUPPLY_STATUS_CHARGING &&
3412                         chip->charge_status != POWER_SUPPLY_STATUS_DISCHARGING)
3413                 goto end_work;
3414
3415         rc = fg_get_battery_current(chip, &ibatt_now);
3416         if (rc < 0) {
3417                 pr_err("failed to get battery current, rc=%d\n", rc);
3418                 goto end_work;
3419         }
3420
3421         rc = fg_get_battery_voltage(chip, &vbatt_now);
3422         if (rc < 0) {
3423                 pr_err("failed to get battery voltage, rc=%d\n", rc);
3424                 goto end_work;
3425         }
3426
3427         fg_circ_buf_add(&chip->ttf.ibatt, ibatt_now);
3428         fg_circ_buf_add(&chip->ttf.vbatt, vbatt_now);
3429
3430         if (chip->charge_status == POWER_SUPPLY_STATUS_CHARGING) {
3431                 rc = fg_get_time_to_full_locked(chip, &ttf);
3432                 if (rc < 0) {
3433                         pr_err("failed to get ttf, rc=%d\n", rc);
3434                         goto end_work;
3435                 }
3436
3437                 /* keep the wake lock and prime the IBATT and VBATT buffers */
3438                 if (ttf < 0) {
3439                         /* delay for one FG cycle */
3440                         schedule_delayed_work(&chip->ttf_work,
3441                                                         msecs_to_jiffies(1500));
3442                         mutex_unlock(&chip->ttf.lock);
3443                         return;
3444                 }
3445
3446                 /* update the TTF reference point every minute */
3447                 ktime_now = ktime_get_boottime();
3448                 if (ktime_ms_delta(ktime_now,
3449                                    ms_to_ktime(chip->ttf.last_ms)) > 60000 ||
3450                                    chip->ttf.last_ms == 0) {
3451                         chip->ttf.last_ttf = ttf;
3452                         chip->ttf.last_ms = ktime_to_ms(ktime_now);
3453                 }
3454         }
3455
3456         /* recurse every 10 seconds */
3457         schedule_delayed_work(&chip->ttf_work, msecs_to_jiffies(10000));
3458 end_work:
3459         vote(chip->awake_votable, TTF_PRIMING, false, 0);
3460         mutex_unlock(&chip->ttf.lock);
3461 }
3462
3463 /* PSY CALLBACKS STAY HERE */
3464
3465 static int fg_psy_get_property(struct power_supply *psy,
3466                                        enum power_supply_property psp,
3467                                        union power_supply_propval *pval)
3468 {
3469         struct fg_chip *chip = power_supply_get_drvdata(psy);
3470         int rc = 0;
3471
3472         switch (psp) {
3473         case POWER_SUPPLY_PROP_CAPACITY:
3474                 rc = fg_get_prop_capacity(chip, &pval->intval);
3475                 break;
3476         case POWER_SUPPLY_PROP_CAPACITY_RAW:
3477                 rc = fg_get_msoc_raw(chip, &pval->intval);
3478                 break;
3479         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
3480                 if (chip->battery_missing)
3481                         pval->intval = 3700000;
3482                 else
3483                         rc = fg_get_battery_voltage(chip, &pval->intval);
3484                 break;
3485         case POWER_SUPPLY_PROP_CURRENT_NOW:
3486                 rc = fg_get_battery_current(chip, &pval->intval);
3487                 break;
3488         case POWER_SUPPLY_PROP_TEMP:
3489                 rc = fg_get_battery_temp(chip, &pval->intval);
3490                 break;
3491         case POWER_SUPPLY_PROP_COLD_TEMP:
3492                 rc = fg_get_jeita_threshold(chip, JEITA_COLD, &pval->intval);
3493                 if (rc < 0) {
3494                         pr_err("Error in reading jeita_cold, rc=%d\n", rc);
3495                         return rc;
3496                 }
3497                 break;
3498         case POWER_SUPPLY_PROP_COOL_TEMP:
3499                 rc = fg_get_jeita_threshold(chip, JEITA_COOL, &pval->intval);
3500                 if (rc < 0) {
3501                         pr_err("Error in reading jeita_cool, rc=%d\n", rc);
3502                         return rc;
3503                 }
3504                 break;
3505         case POWER_SUPPLY_PROP_WARM_TEMP:
3506                 rc = fg_get_jeita_threshold(chip, JEITA_WARM, &pval->intval);
3507                 if (rc < 0) {
3508                         pr_err("Error in reading jeita_warm, rc=%d\n", rc);
3509                         return rc;
3510                 }
3511                 break;
3512         case POWER_SUPPLY_PROP_HOT_TEMP:
3513                 rc = fg_get_jeita_threshold(chip, JEITA_HOT, &pval->intval);
3514                 if (rc < 0) {
3515                         pr_err("Error in reading jeita_hot, rc=%d\n", rc);
3516                         return rc;
3517                 }
3518                 break;
3519         case POWER_SUPPLY_PROP_RESISTANCE:
3520                 rc = fg_get_battery_resistance(chip, &pval->intval);
3521                 break;
3522         case POWER_SUPPLY_PROP_VOLTAGE_OCV:
3523                 rc = fg_get_sram_prop(chip, FG_SRAM_OCV, &pval->intval);
3524                 break;
3525         case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
3526                 pval->intval = chip->cl.nom_cap_uah;
3527                 break;
3528         case POWER_SUPPLY_PROP_RESISTANCE_ID:
3529                 pval->intval = chip->batt_id_ohms;
3530                 break;
3531         case POWER_SUPPLY_PROP_BATTERY_TYPE:
3532                 pval->strval = fg_get_battery_type(chip);
3533                 break;
3534         case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
3535                 pval->intval = chip->bp.float_volt_uv;
3536                 break;
3537         case POWER_SUPPLY_PROP_CYCLE_COUNT:
3538                 pval->intval = fg_get_cycle_count(chip);
3539                 break;
3540         case POWER_SUPPLY_PROP_CYCLE_COUNT_ID:
3541                 pval->intval = chip->cyc_ctr.id;
3542                 break;
3543         case POWER_SUPPLY_PROP_CHARGE_NOW_RAW:
3544                 rc = fg_get_charge_raw(chip, &pval->intval);
3545                 break;
3546         case POWER_SUPPLY_PROP_CHARGE_NOW:
3547                 pval->intval = chip->cl.init_cc_uah;
3548                 break;
3549         case POWER_SUPPLY_PROP_CHARGE_FULL:
3550                 pval->intval = chip->cl.learned_cc_uah;
3551                 break;
3552         case POWER_SUPPLY_PROP_CHARGE_COUNTER:
3553                 rc = fg_get_charge_counter(chip, &pval->intval);
3554                 break;
3555         case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG:
3556                 rc = fg_get_time_to_full(chip, &pval->intval);
3557                 break;
3558         case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
3559                 rc = fg_get_time_to_empty(chip, &pval->intval);
3560                 break;
3561         case POWER_SUPPLY_PROP_SOC_REPORTING_READY:
3562                 pval->intval = chip->soc_reporting_ready;
3563                 break;
3564         case POWER_SUPPLY_PROP_DEBUG_BATTERY:
3565                 pval->intval = is_debug_batt_id(chip);
3566                 break;
3567         case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
3568                 rc = fg_get_sram_prop(chip, FG_SRAM_VBATT_FULL, &pval->intval);
3569                 break;
3570         case POWER_SUPPLY_PROP_CC_STEP:
3571                 if ((chip->ttf.cc_step.sel >= 0) &&
3572                                 (chip->ttf.cc_step.sel < MAX_CC_STEPS)) {
3573                         pval->intval =
3574                                 chip->ttf.cc_step.arr[chip->ttf.cc_step.sel];
3575                 } else {
3576                         pr_err("cc_step_sel is out of bounds [0, %d]\n",
3577                                 chip->ttf.cc_step.sel);
3578                         return -EINVAL;
3579                 }
3580                 break;
3581         case POWER_SUPPLY_PROP_CC_STEP_SEL:
3582                 pval->intval = chip->ttf.cc_step.sel;
3583                 break;
3584         default:
3585                 pr_err("unsupported property %d\n", psp);
3586                 rc = -EINVAL;
3587                 break;
3588         }
3589
3590         if (rc < 0)
3591                 return -ENODATA;
3592
3593         return 0;
3594 }
3595
3596 static int fg_psy_set_property(struct power_supply *psy,
3597                                   enum power_supply_property psp,
3598                                   const union power_supply_propval *pval)
3599 {
3600         struct fg_chip *chip = power_supply_get_drvdata(psy);
3601         int rc = 0;
3602
3603         switch (psp) {
3604         case POWER_SUPPLY_PROP_CYCLE_COUNT_ID:
3605                 if ((pval->intval > 0) && (pval->intval <= BUCKET_COUNT)) {
3606                         chip->cyc_ctr.id = pval->intval;
3607                 } else {
3608                         pr_err("rejecting invalid cycle_count_id = %d\n",
3609                                 pval->intval);
3610                         return -EINVAL;
3611                 }
3612                 break;
3613         case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
3614                 rc = fg_set_constant_chg_voltage(chip, pval->intval);
3615                 break;
3616         case POWER_SUPPLY_PROP_RESISTANCE:
3617                 rc = fg_force_esr_meas(chip);
3618                 break;
3619         case POWER_SUPPLY_PROP_CHARGE_QNOVO_ENABLE:
3620                 rc = fg_prepare_for_qnovo(chip, pval->intval);
3621                 break;
3622         case POWER_SUPPLY_PROP_CC_STEP:
3623                 if ((chip->ttf.cc_step.sel >= 0) &&
3624                                 (chip->ttf.cc_step.sel < MAX_CC_STEPS)) {
3625                         chip->ttf.cc_step.arr[chip->ttf.cc_step.sel] =
3626                                                                 pval->intval;
3627                 } else {
3628                         pr_err("cc_step_sel is out of bounds [0, %d]\n",
3629                                 chip->ttf.cc_step.sel);
3630                         return -EINVAL;
3631                 }
3632                 break;
3633         case POWER_SUPPLY_PROP_CC_STEP_SEL:
3634                 if ((pval->intval >= 0) && (pval->intval < MAX_CC_STEPS)) {
3635                         chip->ttf.cc_step.sel = pval->intval;
3636                 } else {
3637                         pr_err("cc_step_sel is out of bounds [0, %d]\n",
3638                                 pval->intval);
3639                         return -EINVAL;
3640                 }
3641                 break;
3642         case POWER_SUPPLY_PROP_CHARGE_FULL:
3643                 if (chip->cl.active) {
3644                         pr_warn("Capacity learning active!\n");
3645                         return 0;
3646                 }
3647                 if (pval->intval <= 0 || pval->intval > chip->cl.nom_cap_uah) {
3648                         pr_err("charge_full is out of bounds\n");
3649                         return -EINVAL;
3650                 }
3651                 chip->cl.learned_cc_uah = pval->intval;
3652                 rc = fg_save_learned_cap_to_sram(chip);
3653                 if (rc < 0)
3654                         pr_err("Error in saving learned_cc_uah, rc=%d\n", rc);
3655                 break;
3656         case POWER_SUPPLY_PROP_COLD_TEMP:
3657                 rc = fg_set_jeita_threshold(chip, JEITA_COLD, pval->intval);
3658                 if (rc < 0) {
3659                         pr_err("Error in writing jeita_cold, rc=%d\n", rc);
3660                         return rc;
3661                 }
3662                 break;
3663         case POWER_SUPPLY_PROP_COOL_TEMP:
3664                 rc = fg_set_jeita_threshold(chip, JEITA_COOL, pval->intval);
3665                 if (rc < 0) {
3666                         pr_err("Error in writing jeita_cool, rc=%d\n", rc);
3667                         return rc;
3668                 }
3669                 break;
3670         case POWER_SUPPLY_PROP_WARM_TEMP:
3671                 rc = fg_set_jeita_threshold(chip, JEITA_WARM, pval->intval);
3672                 if (rc < 0) {
3673                         pr_err("Error in writing jeita_warm, rc=%d\n", rc);
3674                         return rc;
3675                 }
3676                 break;
3677         case POWER_SUPPLY_PROP_HOT_TEMP:
3678                 rc = fg_set_jeita_threshold(chip, JEITA_HOT, pval->intval);
3679                 if (rc < 0) {
3680                         pr_err("Error in writing jeita_hot, rc=%d\n", rc);
3681                         return rc;
3682                 }
3683                 break;
3684         default:
3685                 break;
3686         }
3687
3688         return rc;
3689 }
3690
3691 static int fg_property_is_writeable(struct power_supply *psy,
3692                                                 enum power_supply_property psp)
3693 {
3694         switch (psp) {
3695         case POWER_SUPPLY_PROP_CYCLE_COUNT_ID:
3696         case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
3697         case POWER_SUPPLY_PROP_CC_STEP:
3698         case POWER_SUPPLY_PROP_CC_STEP_SEL:
3699         case POWER_SUPPLY_PROP_CHARGE_FULL:
3700         case POWER_SUPPLY_PROP_COLD_TEMP:
3701         case POWER_SUPPLY_PROP_COOL_TEMP:
3702         case POWER_SUPPLY_PROP_WARM_TEMP:
3703         case POWER_SUPPLY_PROP_HOT_TEMP:
3704                 return 1;
3705         default:
3706                 break;
3707         }
3708
3709         return 0;
3710 }
3711
3712 static void fg_external_power_changed(struct power_supply *psy)
3713 {
3714         pr_debug("power supply changed\n");
3715 }
3716
3717 static int fg_notifier_cb(struct notifier_block *nb,
3718                 unsigned long event, void *data)
3719 {
3720         struct power_supply *psy = data;
3721         struct fg_chip *chip = container_of(nb, struct fg_chip, nb);
3722
3723         if (event != PSY_EVENT_PROP_CHANGED)
3724                 return NOTIFY_OK;
3725
3726         if (work_pending(&chip->status_change_work))
3727                 return NOTIFY_OK;
3728
3729         if ((strcmp(psy->desc->name, "battery") == 0)
3730                 || (strcmp(psy->desc->name, "usb") == 0)) {
3731                 /*
3732                  * We cannot vote for awake votable here as that takes
3733                  * a mutex lock and this is executed in an atomic context.
3734                  */
3735                 pm_stay_awake(chip->dev);
3736                 schedule_work(&chip->status_change_work);
3737         }
3738
3739         return NOTIFY_OK;
3740 }
3741
3742 static enum power_supply_property fg_psy_props[] = {
3743         POWER_SUPPLY_PROP_CAPACITY,
3744         POWER_SUPPLY_PROP_CAPACITY_RAW,
3745         POWER_SUPPLY_PROP_TEMP,
3746         POWER_SUPPLY_PROP_COLD_TEMP,
3747         POWER_SUPPLY_PROP_COOL_TEMP,
3748         POWER_SUPPLY_PROP_WARM_TEMP,
3749         POWER_SUPPLY_PROP_HOT_TEMP,
3750         POWER_SUPPLY_PROP_VOLTAGE_NOW,
3751         POWER_SUPPLY_PROP_VOLTAGE_OCV,
3752         POWER_SUPPLY_PROP_CURRENT_NOW,
3753         POWER_SUPPLY_PROP_RESISTANCE_ID,
3754         POWER_SUPPLY_PROP_RESISTANCE,
3755         POWER_SUPPLY_PROP_BATTERY_TYPE,
3756         POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
3757         POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
3758         POWER_SUPPLY_PROP_CYCLE_COUNT,
3759         POWER_SUPPLY_PROP_CYCLE_COUNT_ID,
3760         POWER_SUPPLY_PROP_CHARGE_NOW_RAW,
3761         POWER_SUPPLY_PROP_CHARGE_NOW,
3762         POWER_SUPPLY_PROP_CHARGE_FULL,
3763         POWER_SUPPLY_PROP_CHARGE_COUNTER,
3764         POWER_SUPPLY_PROP_TIME_TO_FULL_AVG,
3765         POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG,
3766         POWER_SUPPLY_PROP_SOC_REPORTING_READY,
3767         POWER_SUPPLY_PROP_DEBUG_BATTERY,
3768         POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
3769         POWER_SUPPLY_PROP_CC_STEP,
3770         POWER_SUPPLY_PROP_CC_STEP_SEL,
3771 };
3772
3773 static const struct power_supply_desc fg_psy_desc = {
3774         .name = "bms",
3775         .type = POWER_SUPPLY_TYPE_BMS,
3776         .properties = fg_psy_props,
3777         .num_properties = ARRAY_SIZE(fg_psy_props),
3778         .get_property = fg_psy_get_property,
3779         .set_property = fg_psy_set_property,
3780         .external_power_changed = fg_external_power_changed,
3781         .property_is_writeable = fg_property_is_writeable,
3782 };
3783
3784 /* INIT FUNCTIONS STAY HERE */
3785
3786 #define DEFAULT_ESR_CHG_TIMER_RETRY     8
3787 #define DEFAULT_ESR_CHG_TIMER_MAX       16
3788 static int fg_hw_init(struct fg_chip *chip)
3789 {
3790         int rc;
3791         u8 buf[4], val;
3792
3793         fg_encode(chip->sp, FG_SRAM_CUTOFF_VOLT, chip->dt.cutoff_volt_mv, buf);
3794         rc = fg_sram_write(chip, chip->sp[FG_SRAM_CUTOFF_VOLT].addr_word,
3795                         chip->sp[FG_SRAM_CUTOFF_VOLT].addr_byte, buf,
3796                         chip->sp[FG_SRAM_CUTOFF_VOLT].len, FG_IMA_DEFAULT);
3797         if (rc < 0) {
3798                 pr_err("Error in writing cutoff_volt, rc=%d\n", rc);
3799                 return rc;
3800         }
3801
3802         fg_encode(chip->sp, FG_SRAM_EMPTY_VOLT, chip->dt.empty_volt_mv, buf);
3803         rc = fg_sram_write(chip, chip->sp[FG_SRAM_EMPTY_VOLT].addr_word,
3804                         chip->sp[FG_SRAM_EMPTY_VOLT].addr_byte, buf,
3805                         chip->sp[FG_SRAM_EMPTY_VOLT].len, FG_IMA_DEFAULT);
3806         if (rc < 0) {
3807                 pr_err("Error in writing empty_volt, rc=%d\n", rc);
3808                 return rc;
3809         }
3810
3811         fg_encode(chip->sp, FG_SRAM_CHG_TERM_CURR, chip->dt.chg_term_curr_ma,
3812                 buf);
3813         rc = fg_sram_write(chip, chip->sp[FG_SRAM_CHG_TERM_CURR].addr_word,
3814                         chip->sp[FG_SRAM_CHG_TERM_CURR].addr_byte, buf,
3815                         chip->sp[FG_SRAM_CHG_TERM_CURR].len, FG_IMA_DEFAULT);
3816         if (rc < 0) {
3817                 pr_err("Error in writing chg_term_curr, rc=%d\n", rc);
3818                 return rc;
3819         }
3820
3821         fg_encode(chip->sp, FG_SRAM_SYS_TERM_CURR, chip->dt.sys_term_curr_ma,
3822                 buf);
3823         rc = fg_sram_write(chip, chip->sp[FG_SRAM_SYS_TERM_CURR].addr_word,
3824                         chip->sp[FG_SRAM_SYS_TERM_CURR].addr_byte, buf,
3825                         chip->sp[FG_SRAM_SYS_TERM_CURR].len, FG_IMA_DEFAULT);
3826         if (rc < 0) {
3827                 pr_err("Error in writing sys_term_curr, rc=%d\n", rc);
3828                 return rc;
3829         }
3830
3831         if (!(chip->wa_flags & PMI8998_V1_REV_WA)) {
3832                 fg_encode(chip->sp, FG_SRAM_CHG_TERM_BASE_CURR,
3833                         chip->dt.chg_term_base_curr_ma, buf);
3834                 rc = fg_sram_write(chip,
3835                                 chip->sp[FG_SRAM_CHG_TERM_BASE_CURR].addr_word,
3836                                 chip->sp[FG_SRAM_CHG_TERM_BASE_CURR].addr_byte,
3837                                 buf, chip->sp[FG_SRAM_CHG_TERM_BASE_CURR].len,
3838                                 FG_IMA_DEFAULT);
3839                 if (rc < 0) {
3840                         pr_err("Error in writing chg_term_base_curr, rc=%d\n",
3841                                 rc);
3842                         return rc;
3843                 }
3844         }
3845
3846         if (chip->dt.vbatt_low_thr_mv > 0) {
3847                 fg_encode(chip->sp, FG_SRAM_VBATT_LOW,
3848                         chip->dt.vbatt_low_thr_mv, buf);
3849                 rc = fg_sram_write(chip, chip->sp[FG_SRAM_VBATT_LOW].addr_word,
3850                                 chip->sp[FG_SRAM_VBATT_LOW].addr_byte, buf,
3851                                 chip->sp[FG_SRAM_VBATT_LOW].len,
3852                                 FG_IMA_DEFAULT);
3853                 if (rc < 0) {
3854                         pr_err("Error in writing vbatt_low_thr, rc=%d\n", rc);
3855                         return rc;
3856                 }
3857         }
3858
3859         if (chip->dt.delta_soc_thr > 0 && chip->dt.delta_soc_thr < 100) {
3860                 fg_encode(chip->sp, FG_SRAM_DELTA_MSOC_THR,
3861                         chip->dt.delta_soc_thr, buf);
3862                 rc = fg_sram_write(chip,
3863                                 chip->sp[FG_SRAM_DELTA_MSOC_THR].addr_word,
3864                                 chip->sp[FG_SRAM_DELTA_MSOC_THR].addr_byte,
3865                                 buf, chip->sp[FG_SRAM_DELTA_MSOC_THR].len,
3866                                 FG_IMA_DEFAULT);
3867                 if (rc < 0) {
3868                         pr_err("Error in writing delta_msoc_thr, rc=%d\n", rc);
3869                         return rc;
3870                 }
3871
3872                 fg_encode(chip->sp, FG_SRAM_DELTA_BSOC_THR,
3873                         chip->dt.delta_soc_thr, buf);
3874                 rc = fg_sram_write(chip,
3875                                 chip->sp[FG_SRAM_DELTA_BSOC_THR].addr_word,
3876                                 chip->sp[FG_SRAM_DELTA_BSOC_THR].addr_byte,
3877                                 buf, chip->sp[FG_SRAM_DELTA_BSOC_THR].len,
3878                                 FG_IMA_DEFAULT);
3879                 if (rc < 0) {
3880                         pr_err("Error in writing delta_bsoc_thr, rc=%d\n", rc);
3881                         return rc;
3882                 }
3883         }
3884
3885         /*
3886          * configure battery thermal coefficients c1,c2,c3
3887          * if its value is not zero.
3888          */
3889         if (chip->dt.batt_therm_coeffs[0] > 0) {
3890                 rc = fg_write(chip, BATT_INFO_THERM_C1(chip),
3891                         chip->dt.batt_therm_coeffs, BATT_THERM_NUM_COEFFS);
3892                 if (rc < 0) {
3893                         pr_err("Error in writing battery thermal coefficients, rc=%d\n",
3894                                 rc);
3895                         return rc;
3896                 }
3897         }
3898
3899
3900         if (chip->dt.recharge_soc_thr > 0 && chip->dt.recharge_soc_thr < 100) {
3901                 rc = fg_set_recharge_soc(chip, chip->dt.recharge_soc_thr);
3902                 if (rc < 0) {
3903                         pr_err("Error in setting recharge_soc, rc=%d\n", rc);
3904                         return rc;
3905                 }
3906         }
3907
3908         if (chip->dt.recharge_volt_thr_mv > 0) {
3909                 rc = fg_set_recharge_voltage(chip,
3910                         chip->dt.recharge_volt_thr_mv);
3911                 if (rc < 0) {
3912                         pr_err("Error in setting recharge_voltage, rc=%d\n",
3913                                 rc);
3914                         return rc;
3915                 }
3916         }
3917
3918         if (chip->dt.rsense_sel >= SRC_SEL_BATFET &&
3919                         chip->dt.rsense_sel < SRC_SEL_RESERVED) {
3920                 rc = fg_masked_write(chip, BATT_INFO_IBATT_SENSING_CFG(chip),
3921                                 SOURCE_SELECT_MASK, chip->dt.rsense_sel);
3922                 if (rc < 0) {
3923                         pr_err("Error in writing rsense_sel, rc=%d\n", rc);
3924                         return rc;
3925                 }
3926         }
3927
3928         rc = fg_set_jeita_threshold(chip, JEITA_COLD,
3929                 chip->dt.jeita_thresholds[JEITA_COLD] * 10);
3930         if (rc < 0) {
3931                 pr_err("Error in writing jeita_cold, rc=%d\n", rc);
3932                 return rc;
3933         }
3934
3935         rc = fg_set_jeita_threshold(chip, JEITA_COOL,
3936                 chip->dt.jeita_thresholds[JEITA_COOL] * 10);
3937         if (rc < 0) {
3938                 pr_err("Error in writing jeita_cool, rc=%d\n", rc);
3939                 return rc;
3940         }
3941
3942         rc = fg_set_jeita_threshold(chip, JEITA_WARM,
3943                 chip->dt.jeita_thresholds[JEITA_WARM] * 10);
3944         if (rc < 0) {
3945                 pr_err("Error in writing jeita_warm, rc=%d\n", rc);
3946                 return rc;
3947         }
3948
3949         rc = fg_set_jeita_threshold(chip, JEITA_HOT,
3950                 chip->dt.jeita_thresholds[JEITA_HOT] * 10);
3951         if (rc < 0) {
3952                 pr_err("Error in writing jeita_hot, rc=%d\n", rc);
3953                 return rc;
3954         }
3955
3956         if (chip->pmic_rev_id->pmic_subtype == PMI8998_SUBTYPE) {
3957                 chip->esr_timer_charging_default[TIMER_RETRY] =
3958                         DEFAULT_ESR_CHG_TIMER_RETRY;
3959                 chip->esr_timer_charging_default[TIMER_MAX] =
3960                         DEFAULT_ESR_CHG_TIMER_MAX;
3961         } else {
3962                 /* We don't need this for pm660 at present */
3963                 chip->esr_timer_charging_default[TIMER_RETRY] = -EINVAL;
3964                 chip->esr_timer_charging_default[TIMER_MAX] = -EINVAL;
3965         }
3966
3967         rc = fg_set_esr_timer(chip, chip->dt.esr_timer_charging[TIMER_RETRY],
3968                 chip->dt.esr_timer_charging[TIMER_MAX], true, FG_IMA_DEFAULT);
3969         if (rc < 0) {
3970                 pr_err("Error in setting ESR timer, rc=%d\n", rc);
3971                 return rc;
3972         }
3973
3974         rc = fg_set_esr_timer(chip, chip->dt.esr_timer_awake[TIMER_RETRY],
3975                 chip->dt.esr_timer_awake[TIMER_MAX], false, FG_IMA_DEFAULT);
3976         if (rc < 0) {
3977                 pr_err("Error in setting ESR timer, rc=%d\n", rc);
3978                 return rc;
3979         }
3980
3981         restore_cycle_counter(chip);
3982
3983         if (chip->dt.jeita_hyst_temp >= 0) {
3984                 val = chip->dt.jeita_hyst_temp << JEITA_TEMP_HYST_SHIFT;
3985                 rc = fg_masked_write(chip, BATT_INFO_BATT_TEMP_CFG(chip),
3986                         JEITA_TEMP_HYST_MASK, val);
3987                 if (rc < 0) {
3988                         pr_err("Error in writing batt_temp_cfg, rc=%d\n", rc);
3989                         return rc;
3990                 }
3991         }
3992
3993         get_batt_temp_delta(chip->dt.batt_temp_delta, &val);
3994         rc = fg_masked_write(chip, BATT_INFO_BATT_TMPR_INTR(chip),
3995                         CHANGE_THOLD_MASK, val);
3996         if (rc < 0) {
3997                 pr_err("Error in writing batt_temp_delta, rc=%d\n", rc);
3998                 return rc;
3999         }
4000
4001         rc = fg_rconn_config(chip);
4002         if (rc < 0) {
4003                 pr_err("Error in configuring Rconn, rc=%d\n", rc);
4004                 return rc;
4005         }
4006
4007         fg_encode(chip->sp, FG_SRAM_ESR_TIGHT_FILTER,
4008                 chip->dt.esr_tight_flt_upct, buf);
4009         rc = fg_sram_write(chip, chip->sp[FG_SRAM_ESR_TIGHT_FILTER].addr_word,
4010                         chip->sp[FG_SRAM_ESR_TIGHT_FILTER].addr_byte, buf,
4011                         chip->sp[FG_SRAM_ESR_TIGHT_FILTER].len, FG_IMA_DEFAULT);
4012         if (rc < 0) {
4013                 pr_err("Error in writing ESR tight filter, rc=%d\n", rc);
4014                 return rc;
4015         }
4016
4017         fg_encode(chip->sp, FG_SRAM_ESR_BROAD_FILTER,
4018                 chip->dt.esr_broad_flt_upct, buf);
4019         rc = fg_sram_write(chip, chip->sp[FG_SRAM_ESR_BROAD_FILTER].addr_word,
4020                         chip->sp[FG_SRAM_ESR_BROAD_FILTER].addr_byte, buf,
4021                         chip->sp[FG_SRAM_ESR_BROAD_FILTER].len, FG_IMA_DEFAULT);
4022         if (rc < 0) {
4023                 pr_err("Error in writing ESR broad filter, rc=%d\n", rc);
4024                 return rc;
4025         }
4026
4027         fg_encode(chip->sp, FG_SRAM_ESR_PULSE_THRESH,
4028                 chip->dt.esr_pulse_thresh_ma, buf);
4029         rc = fg_sram_write(chip, chip->sp[FG_SRAM_ESR_PULSE_THRESH].addr_word,
4030                         chip->sp[FG_SRAM_ESR_PULSE_THRESH].addr_byte, buf,
4031                         chip->sp[FG_SRAM_ESR_PULSE_THRESH].len, FG_IMA_DEFAULT);
4032         if (rc < 0) {
4033                 pr_err("Error in writing esr_pulse_thresh_ma, rc=%d\n", rc);
4034                 return rc;
4035         }
4036
4037         get_esr_meas_current(chip->dt.esr_meas_curr_ma, &val);
4038         rc = fg_masked_write(chip, BATT_INFO_ESR_PULL_DN_CFG(chip),
4039                         ESR_PULL_DOWN_IVAL_MASK, val);
4040         if (rc < 0) {
4041                 pr_err("Error in writing esr_meas_curr_ma, rc=%d\n", rc);
4042                 return rc;
4043         }
4044
4045         if (is_debug_batt_id(chip)) {
4046                 val = ESR_NO_PULL_DOWN;
4047                 rc = fg_masked_write(chip, BATT_INFO_ESR_PULL_DN_CFG(chip),
4048                         ESR_PULL_DOWN_MODE_MASK, val);
4049                 if (rc < 0) {
4050                         pr_err("Error in writing esr_pull_down, rc=%d\n", rc);
4051                         return rc;
4052                 }
4053         }
4054
4055         return 0;
4056 }
4057
4058 static int fg_memif_init(struct fg_chip *chip)
4059 {
4060         return fg_ima_init(chip);
4061 }
4062
4063 static int fg_adjust_timebase(struct fg_chip *chip)
4064 {
4065         int rc = 0, die_temp;
4066         s32 time_base = 0;
4067         u8 buf[2] = {0};
4068
4069         if ((chip->wa_flags & PM660_TSMC_OSC_WA) && chip->die_temp_chan) {
4070                 rc = iio_read_channel_processed(chip->die_temp_chan, &die_temp);
4071                 if (rc < 0) {
4072                         pr_err("Error in reading die_temp, rc:%d\n", rc);
4073                         return rc;
4074                 }
4075
4076                 rc = fg_lerp(fg_tsmc_osc_table, ARRAY_SIZE(fg_tsmc_osc_table),
4077                                         die_temp / 1000, &time_base);
4078                 if (rc < 0) {
4079                         pr_err("Error to lookup fg_tsmc_osc_table rc=%d\n", rc);
4080                         return rc;
4081                 }
4082
4083                 fg_encode(chip->sp, FG_SRAM_TIMEBASE, time_base, buf);
4084                 rc = fg_sram_write(chip,
4085                         chip->sp[FG_SRAM_TIMEBASE].addr_word,
4086                         chip->sp[FG_SRAM_TIMEBASE].addr_byte, buf,
4087                         chip->sp[FG_SRAM_TIMEBASE].len, FG_IMA_DEFAULT);
4088                 if (rc < 0) {
4089                         pr_err("Error in writing timebase, rc=%d\n", rc);
4090                         return rc;
4091                 }
4092         }
4093
4094         return 0;
4095 }
4096
4097 /* INTERRUPT HANDLERS STAY HERE */
4098
4099 static irqreturn_t fg_mem_xcp_irq_handler(int irq, void *data)
4100 {
4101         struct fg_chip *chip = data;
4102         u8 status;
4103         int rc;
4104
4105         rc = fg_read(chip, MEM_IF_INT_RT_STS(chip), &status, 1);
4106         if (rc < 0) {
4107                 pr_err("failed to read addr=0x%04x, rc=%d\n",
4108                         MEM_IF_INT_RT_STS(chip), rc);
4109                 return IRQ_HANDLED;
4110         }
4111
4112         fg_dbg(chip, FG_IRQ, "irq %d triggered, status:%d\n", irq, status);
4113
4114         mutex_lock(&chip->sram_rw_lock);
4115         rc = fg_clear_dma_errors_if_any(chip);
4116         if (rc < 0)
4117                 pr_err("Error in clearing DMA error, rc=%d\n", rc);
4118
4119         if (status & MEM_XCP_BIT) {
4120                 rc = fg_clear_ima_errors_if_any(chip, true);
4121                 if (rc < 0 && rc != -EAGAIN)
4122                         pr_err("Error in checking IMA errors rc:%d\n", rc);
4123         }
4124
4125         mutex_unlock(&chip->sram_rw_lock);
4126         return IRQ_HANDLED;
4127 }
4128
4129 static irqreturn_t fg_vbatt_low_irq_handler(int irq, void *data)
4130 {
4131         struct fg_chip *chip = data;
4132
4133         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4134         return IRQ_HANDLED;
4135 }
4136
4137 static irqreturn_t fg_batt_missing_irq_handler(int irq, void *data)
4138 {
4139         struct fg_chip *chip = data;
4140         u8 status;
4141         int rc;
4142
4143         rc = fg_read(chip, BATT_INFO_INT_RT_STS(chip), &status, 1);
4144         if (rc < 0) {
4145                 pr_err("failed to read addr=0x%04x, rc=%d\n",
4146                         BATT_INFO_INT_RT_STS(chip), rc);
4147                 return IRQ_HANDLED;
4148         }
4149
4150         fg_dbg(chip, FG_IRQ, "irq %d triggered sts:%d\n", irq, status);
4151         chip->battery_missing = (status & BT_MISS_BIT);
4152
4153         if (chip->battery_missing) {
4154                 chip->profile_available = false;
4155                 chip->profile_loaded = false;
4156                 chip->soc_reporting_ready = false;
4157                 return IRQ_HANDLED;
4158         }
4159
4160         clear_battery_profile(chip);
4161         schedule_delayed_work(&chip->profile_load_work, 0);
4162
4163         if (chip->fg_psy)
4164                 power_supply_changed(chip->fg_psy);
4165
4166         return IRQ_HANDLED;
4167 }
4168
4169 static irqreturn_t fg_delta_batt_temp_irq_handler(int irq, void *data)
4170 {
4171         struct fg_chip *chip = data;
4172         union power_supply_propval prop = {0, };
4173         int rc, batt_temp;
4174
4175         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4176         rc = fg_get_battery_temp(chip, &batt_temp);
4177         if (rc < 0) {
4178                 pr_err("Error in getting batt_temp\n");
4179                 return IRQ_HANDLED;
4180         }
4181
4182         rc = fg_esr_filter_config(chip, batt_temp);
4183         if (rc < 0)
4184                 pr_err("Error in configuring ESR filter rc:%d\n", rc);
4185
4186         rc = fg_slope_limit_config(chip, batt_temp);
4187         if (rc < 0)
4188                 pr_err("Error in configuring slope limiter rc:%d\n", rc);
4189
4190         rc = fg_adjust_ki_coeff_full_soc(chip, batt_temp);
4191         if (rc < 0)
4192                 pr_err("Error in configuring ki_coeff_full_soc rc:%d\n", rc);
4193
4194         if (!batt_psy_initialized(chip)) {
4195                 chip->last_batt_temp = batt_temp;
4196                 return IRQ_HANDLED;
4197         }
4198
4199         power_supply_get_property(chip->batt_psy, POWER_SUPPLY_PROP_HEALTH,
4200                 &prop);
4201         chip->health = prop.intval;
4202
4203         if (chip->last_batt_temp != batt_temp) {
4204                 rc = fg_adjust_timebase(chip);
4205                 if (rc < 0)
4206                         pr_err("Error in adjusting timebase, rc=%d\n", rc);
4207
4208                 rc = fg_adjust_recharge_voltage(chip);
4209                 if (rc < 0)
4210                         pr_err("Error in adjusting recharge_voltage, rc=%d\n",
4211                                 rc);
4212
4213                 chip->last_batt_temp = batt_temp;
4214                 power_supply_changed(chip->batt_psy);
4215         }
4216
4217         if (abs(chip->last_batt_temp - batt_temp) > 30)
4218                 pr_warn("Battery temperature last:%d current: %d\n",
4219                         chip->last_batt_temp, batt_temp);
4220         return IRQ_HANDLED;
4221 }
4222
4223 static irqreturn_t fg_first_est_irq_handler(int irq, void *data)
4224 {
4225         struct fg_chip *chip = data;
4226
4227         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4228         complete_all(&chip->soc_ready);
4229         return IRQ_HANDLED;
4230 }
4231
4232 static irqreturn_t fg_soc_update_irq_handler(int irq, void *data)
4233 {
4234         struct fg_chip *chip = data;
4235
4236         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4237         complete_all(&chip->soc_update);
4238         return IRQ_HANDLED;
4239 }
4240
4241 static irqreturn_t fg_delta_bsoc_irq_handler(int irq, void *data)
4242 {
4243         struct fg_chip *chip = data;
4244         int rc;
4245
4246         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4247         rc = fg_charge_full_update(chip);
4248         if (rc < 0)
4249                 pr_err("Error in charge_full_update, rc=%d\n", rc);
4250
4251         return IRQ_HANDLED;
4252 }
4253
4254 static irqreturn_t fg_delta_msoc_irq_handler(int irq, void *data)
4255 {
4256         struct fg_chip *chip = data;
4257         int rc;
4258
4259         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4260         fg_cycle_counter_update(chip);
4261
4262         if (chip->cl.active)
4263                 fg_cap_learning_update(chip);
4264
4265         rc = fg_charge_full_update(chip);
4266         if (rc < 0)
4267                 pr_err("Error in charge_full_update, rc=%d\n", rc);
4268
4269         rc = fg_adjust_ki_coeff_dischg(chip);
4270         if (rc < 0)
4271                 pr_err("Error in adjusting ki_coeff_dischg, rc=%d\n", rc);
4272
4273         rc = fg_update_maint_soc(chip);
4274         if (rc < 0)
4275                 pr_err("Error in updating maint_soc, rc=%d\n", rc);
4276
4277         rc = fg_esr_validate(chip);
4278         if (rc < 0)
4279                 pr_err("Error in validating ESR, rc=%d\n", rc);
4280
4281         rc = fg_adjust_timebase(chip);
4282         if (rc < 0)
4283                 pr_err("Error in adjusting timebase, rc=%d\n", rc);
4284
4285         if (batt_psy_initialized(chip))
4286                 power_supply_changed(chip->batt_psy);
4287
4288         return IRQ_HANDLED;
4289 }
4290
4291 static irqreturn_t fg_empty_soc_irq_handler(int irq, void *data)
4292 {
4293         struct fg_chip *chip = data;
4294
4295         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4296         if (batt_psy_initialized(chip))
4297                 power_supply_changed(chip->batt_psy);
4298
4299         return IRQ_HANDLED;
4300 }
4301
4302 static irqreturn_t fg_soc_irq_handler(int irq, void *data)
4303 {
4304         struct fg_chip *chip = data;
4305
4306         fg_dbg(chip, FG_IRQ, "irq %d triggered\n", irq);
4307         return IRQ_HANDLED;
4308 }
4309
4310 static irqreturn_t fg_dummy_irq_handler(int irq, void *data)
4311 {
4312         pr_debug("irq %d triggered\n", irq);
4313         return IRQ_HANDLED;
4314 }
4315
4316 static struct fg_irq_info fg_irqs[FG_IRQ_MAX] = {
4317         /* BATT_SOC irqs */
4318         [MSOC_FULL_IRQ] = {
4319                 .name           = "msoc-full",
4320                 .handler        = fg_soc_irq_handler,
4321         },
4322         [MSOC_HIGH_IRQ] = {
4323                 .name           = "msoc-high",
4324                 .handler        = fg_soc_irq_handler,
4325                 .wakeable       = true,
4326         },
4327         [MSOC_EMPTY_IRQ] = {
4328                 .name           = "msoc-empty",
4329                 .handler        = fg_empty_soc_irq_handler,
4330                 .wakeable       = true,
4331         },
4332         [MSOC_LOW_IRQ] = {
4333                 .name           = "msoc-low",
4334                 .handler        = fg_soc_irq_handler,
4335                 .wakeable       = true,
4336         },
4337         [MSOC_DELTA_IRQ] = {
4338                 .name           = "msoc-delta",
4339                 .handler        = fg_delta_msoc_irq_handler,
4340                 .wakeable       = true,
4341         },
4342         [BSOC_DELTA_IRQ] = {
4343                 .name           = "bsoc-delta",
4344                 .handler        = fg_delta_bsoc_irq_handler,
4345                 .wakeable       = true,
4346         },
4347         [SOC_READY_IRQ] = {
4348                 .name           = "soc-ready",
4349                 .handler        = fg_first_est_irq_handler,
4350                 .wakeable       = true,
4351         },
4352         [SOC_UPDATE_IRQ] = {
4353                 .name           = "soc-update",
4354                 .handler        = fg_soc_update_irq_handler,
4355         },
4356         /* BATT_INFO irqs */
4357         [BATT_TEMP_DELTA_IRQ] = {
4358                 .name           = "batt-temp-delta",
4359                 .handler        = fg_delta_batt_temp_irq_handler,
4360                 .wakeable       = true,
4361         },
4362         [BATT_MISSING_IRQ] = {
4363                 .name           = "batt-missing",
4364                 .handler        = fg_batt_missing_irq_handler,
4365                 .wakeable       = true,
4366         },
4367         [ESR_DELTA_IRQ] = {
4368                 .name           = "esr-delta",
4369                 .handler        = fg_dummy_irq_handler,
4370         },
4371         [VBATT_LOW_IRQ] = {
4372                 .name           = "vbatt-low",
4373                 .handler        = fg_vbatt_low_irq_handler,
4374                 .wakeable       = true,
4375         },
4376         [VBATT_PRED_DELTA_IRQ] = {
4377                 .name           = "vbatt-pred-delta",
4378                 .handler        = fg_dummy_irq_handler,
4379         },
4380         /* MEM_IF irqs */
4381         [DMA_GRANT_IRQ] = {
4382                 .name           = "dma-grant",
4383                 .handler        = fg_dummy_irq_handler,
4384         },
4385         [MEM_XCP_IRQ] = {
4386                 .name           = "mem-xcp",
4387                 .handler        = fg_mem_xcp_irq_handler,
4388         },
4389         [IMA_RDY_IRQ] = {
4390                 .name           = "ima-rdy",
4391                 .handler        = fg_dummy_irq_handler,
4392         },
4393 };
4394
4395 static int fg_get_irq_index_byname(const char *name)
4396 {
4397         int i;
4398
4399         for (i = 0; i < ARRAY_SIZE(fg_irqs); i++) {
4400                 if (strcmp(fg_irqs[i].name, name) == 0)
4401                         return i;
4402         }
4403
4404         pr_err("%s is not in irq list\n", name);
4405         return -ENOENT;
4406 }
4407
4408 static int fg_register_interrupts(struct fg_chip *chip)
4409 {
4410         struct device_node *child, *node = chip->dev->of_node;
4411         struct property *prop;
4412         const char *name;
4413         int rc, irq, irq_index;
4414
4415         for_each_available_child_of_node(node, child) {
4416                 of_property_for_each_string(child, "interrupt-names", prop,
4417                                                 name) {
4418                         irq = of_irq_get_byname(child, name);
4419                         if (irq < 0) {
4420                                 dev_err(chip->dev, "failed to get irq %s irq:%d\n",
4421                                         name, irq);
4422                                 return irq;
4423                         }
4424
4425                         irq_index = fg_get_irq_index_byname(name);
4426                         if (irq_index < 0)
4427                                 return irq_index;
4428
4429                         rc = devm_request_threaded_irq(chip->dev, irq, NULL,
4430                                         fg_irqs[irq_index].handler,
4431                                         IRQF_ONESHOT, name, chip);
4432                         if (rc < 0) {
4433                                 dev_err(chip->dev, "failed to register irq handler for %s rc:%d\n",
4434                                         name, rc);
4435                                 return rc;
4436                         }
4437
4438                         fg_irqs[irq_index].irq = irq;
4439                         if (fg_irqs[irq_index].wakeable)
4440                                 enable_irq_wake(fg_irqs[irq_index].irq);
4441                 }
4442         }
4443
4444         return 0;
4445 }
4446
4447 static int fg_parse_dt_property_u32_array(struct device_node *node,
4448                                 const char *prop_name, int *buf, int len)
4449 {
4450         int rc;
4451
4452         rc = of_property_count_elems_of_size(node, prop_name, sizeof(u32));
4453         if (rc < 0) {
4454                 if (rc == -EINVAL)
4455                         return 0;
4456                 else
4457                         return rc;
4458         } else if (rc != len) {
4459                 pr_err("Incorrect length %d for %s, rc=%d\n", len, prop_name,
4460                         rc);
4461                 return -EINVAL;
4462         }
4463
4464         rc = of_property_read_u32_array(node, prop_name, buf, len);
4465         if (rc < 0) {
4466                 pr_err("Error in reading %s, rc=%d\n", prop_name, rc);
4467                 return rc;
4468         }
4469
4470         return 0;
4471 }
4472
4473 static int fg_parse_slope_limit_coefficients(struct fg_chip *chip)
4474 {
4475         struct device_node *node = chip->dev->of_node;
4476         int rc, i;
4477
4478         rc = of_property_read_u32(node, "qcom,slope-limit-temp-threshold",
4479                         &chip->dt.slope_limit_temp);
4480         if (rc < 0)
4481                 return 0;
4482
4483         rc = fg_parse_dt_property_u32_array(node, "qcom,slope-limit-coeffs",
4484                 chip->dt.slope_limit_coeffs, SLOPE_LIMIT_NUM_COEFFS);
4485         if (rc < 0)
4486                 return rc;
4487
4488         for (i = 0; i < SLOPE_LIMIT_NUM_COEFFS; i++) {
4489                 if (chip->dt.slope_limit_coeffs[i] > SLOPE_LIMIT_COEFF_MAX ||
4490                         chip->dt.slope_limit_coeffs[i] < 0) {
4491                         pr_err("Incorrect slope limit coefficient\n");
4492                         return -EINVAL;
4493                 }
4494         }
4495
4496         chip->slope_limit_en = true;
4497         return 0;
4498 }
4499
4500 static int fg_parse_ki_coefficients(struct fg_chip *chip)
4501 {
4502         struct device_node *node = chip->dev->of_node;
4503         int rc, i, temp;
4504
4505         rc = of_property_read_u32(node, "qcom,ki-coeff-full-dischg", &temp);
4506         if (!rc)
4507                 chip->dt.ki_coeff_full_soc_dischg = temp;
4508
4509         rc = fg_parse_dt_property_u32_array(node, "qcom,ki-coeff-soc-dischg",
4510                 chip->dt.ki_coeff_soc, KI_COEFF_SOC_LEVELS);
4511         if (rc < 0)
4512                 return rc;
4513
4514         rc = fg_parse_dt_property_u32_array(node, "qcom,ki-coeff-med-dischg",
4515                 chip->dt.ki_coeff_med_dischg, KI_COEFF_SOC_LEVELS);
4516         if (rc < 0)
4517                 return rc;
4518
4519         rc = fg_parse_dt_property_u32_array(node, "qcom,ki-coeff-hi-dischg",
4520                 chip->dt.ki_coeff_hi_dischg, KI_COEFF_SOC_LEVELS);
4521         if (rc < 0)
4522                 return rc;
4523
4524         for (i = 0; i < KI_COEFF_SOC_LEVELS; i++) {
4525                 if (chip->dt.ki_coeff_soc[i] < 0 ||
4526                         chip->dt.ki_coeff_soc[i] > FULL_CAPACITY) {
4527                         pr_err("Error in ki_coeff_soc_dischg values\n");
4528                         return -EINVAL;
4529                 }
4530
4531                 if (chip->dt.ki_coeff_med_dischg[i] < 0 ||
4532                         chip->dt.ki_coeff_med_dischg[i] > KI_COEFF_MAX) {
4533                         pr_err("Error in ki_coeff_med_dischg values\n");
4534                         return -EINVAL;
4535                 }
4536
4537                 if (chip->dt.ki_coeff_med_dischg[i] < 0 ||
4538                         chip->dt.ki_coeff_med_dischg[i] > KI_COEFF_MAX) {
4539                         pr_err("Error in ki_coeff_med_dischg values\n");
4540                         return -EINVAL;
4541                 }
4542         }
4543         chip->ki_coeff_dischg_en = true;
4544         return 0;
4545 }
4546
4547 #define DEFAULT_CUTOFF_VOLT_MV          3200
4548 #define DEFAULT_EMPTY_VOLT_MV           2850
4549 #define DEFAULT_RECHARGE_VOLT_MV        4250
4550 #define DEFAULT_CHG_TERM_CURR_MA        100
4551 #define DEFAULT_CHG_TERM_BASE_CURR_MA   75
4552 #define DEFAULT_SYS_TERM_CURR_MA        -125
4553 #define DEFAULT_DELTA_SOC_THR           1
4554 #define DEFAULT_RECHARGE_SOC_THR        95
4555 #define DEFAULT_BATT_TEMP_COLD          0
4556 #define DEFAULT_BATT_TEMP_COOL          5
4557 #define DEFAULT_BATT_TEMP_WARM          45
4558 #define DEFAULT_BATT_TEMP_HOT           50
4559 #define DEFAULT_CL_START_SOC            15
4560 #define DEFAULT_CL_MIN_TEMP_DECIDEGC    150
4561 #define DEFAULT_CL_MAX_TEMP_DECIDEGC    450
4562 #define DEFAULT_CL_MAX_INC_DECIPERC     5
4563 #define DEFAULT_CL_MAX_DEC_DECIPERC     100
4564 #define DEFAULT_CL_MIN_LIM_DECIPERC     0
4565 #define DEFAULT_CL_MAX_LIM_DECIPERC     0
4566 #define BTEMP_DELTA_LOW                 2
4567 #define BTEMP_DELTA_HIGH                10
4568 #define DEFAULT_ESR_FLT_TEMP_DECIDEGC   100
4569 #define DEFAULT_ESR_TIGHT_FLT_UPCT      3907
4570 #define DEFAULT_ESR_BROAD_FLT_UPCT      99610
4571 #define DEFAULT_ESR_TIGHT_LT_FLT_UPCT   48829
4572 #define DEFAULT_ESR_BROAD_LT_FLT_UPCT   148438
4573 #define DEFAULT_ESR_CLAMP_MOHMS         20
4574 #define DEFAULT_ESR_PULSE_THRESH_MA     110
4575 #define DEFAULT_ESR_MEAS_CURR_MA        120
4576 static int fg_parse_dt(struct fg_chip *chip)
4577 {
4578         struct device_node *child, *revid_node, *node = chip->dev->of_node;
4579         u32 base, temp;
4580         u8 subtype;
4581         int rc;
4582
4583         if (!node)  {
4584                 dev_err(chip->dev, "device tree node missing\n");
4585                 return -ENXIO;
4586         }
4587
4588         revid_node = of_parse_phandle(node, "qcom,pmic-revid", 0);
4589         if (!revid_node) {
4590                 pr_err("Missing qcom,pmic-revid property - driver failed\n");
4591                 return -EINVAL;
4592         }
4593
4594         chip->pmic_rev_id = get_revid_data(revid_node);
4595         if (IS_ERR_OR_NULL(chip->pmic_rev_id)) {
4596                 pr_err("Unable to get pmic_revid rc=%ld\n",
4597                         PTR_ERR(chip->pmic_rev_id));
4598                 /*
4599                  * the revid peripheral must be registered, any failure
4600                  * here only indicates that the rev-id module has not
4601                  * probed yet.
4602                  */
4603                 return -EPROBE_DEFER;
4604         }
4605
4606         pr_debug("PMIC subtype %d Digital major %d\n",
4607                 chip->pmic_rev_id->pmic_subtype, chip->pmic_rev_id->rev4);
4608
4609         switch (chip->pmic_rev_id->pmic_subtype) {
4610         case PMI8998_SUBTYPE:
4611                 if (chip->pmic_rev_id->rev4 < PMI8998_V2P0_REV4) {
4612                         chip->sp = pmi8998_v1_sram_params;
4613                         chip->alg_flags = pmi8998_v1_alg_flags;
4614                         chip->wa_flags |= PMI8998_V1_REV_WA;
4615                 } else if (chip->pmic_rev_id->rev4 == PMI8998_V2P0_REV4) {
4616                         chip->sp = pmi8998_v2_sram_params;
4617                         chip->alg_flags = pmi8998_v2_alg_flags;
4618                 } else {
4619                         return -EINVAL;
4620                 }
4621                 break;
4622         case PM660_SUBTYPE:
4623                 chip->sp = pmi8998_v2_sram_params;
4624                 chip->alg_flags = pmi8998_v2_alg_flags;
4625                 chip->use_ima_single_mode = true;
4626                 if (chip->pmic_rev_id->fab_id == PM660_FAB_ID_TSMC)
4627                         chip->wa_flags |= PM660_TSMC_OSC_WA;
4628                 break;
4629         default:
4630                 return -EINVAL;
4631         }
4632
4633         if (of_get_available_child_count(node) == 0) {
4634                 dev_err(chip->dev, "No child nodes specified!\n");
4635                 return -ENXIO;
4636         }
4637
4638         for_each_available_child_of_node(node, child) {
4639                 rc = of_property_read_u32(child, "reg", &base);
4640                 if (rc < 0) {
4641                         dev_err(chip->dev, "reg not specified in node %s, rc=%d\n",
4642                                 child->full_name, rc);
4643                         return rc;
4644                 }
4645
4646                 rc = fg_read(chip, base + PERPH_SUBTYPE_REG, &subtype, 1);
4647                 if (rc < 0) {
4648                         dev_err(chip->dev, "Couldn't read subtype for base %d, rc=%d\n",
4649                                 base, rc);
4650                         return rc;
4651                 }
4652
4653                 switch (subtype) {
4654                 case FG_BATT_SOC_PMI8998:
4655                         chip->batt_soc_base = base;
4656                         break;
4657                 case FG_BATT_INFO_PMI8998:
4658                         chip->batt_info_base = base;
4659                         break;
4660                 case FG_MEM_INFO_PMI8998:
4661                         chip->mem_if_base = base;
4662                         break;
4663                 default:
4664                         dev_err(chip->dev, "Invalid peripheral subtype 0x%x\n",
4665                                 subtype);
4666                         return -ENXIO;
4667                 }
4668         }
4669
4670         rc = of_property_read_u32(node, "qcom,rradc-base", &base);
4671         if (rc < 0) {
4672                 dev_err(chip->dev, "rradc-base not specified, rc=%d\n", rc);
4673                 return rc;
4674         }
4675         chip->rradc_base = base;
4676
4677         /* Read all the optional properties below */
4678         rc = of_property_read_u32(node, "qcom,fg-cutoff-voltage", &temp);
4679         if (rc < 0)
4680                 chip->dt.cutoff_volt_mv = DEFAULT_CUTOFF_VOLT_MV;
4681         else
4682                 chip->dt.cutoff_volt_mv = temp;
4683
4684         rc = of_property_read_u32(node, "qcom,fg-empty-voltage", &temp);
4685         if (rc < 0)
4686                 chip->dt.empty_volt_mv = DEFAULT_EMPTY_VOLT_MV;
4687         else
4688                 chip->dt.empty_volt_mv = temp;
4689
4690         rc = of_property_read_u32(node, "qcom,fg-vbatt-low-thr", &temp);
4691         if (rc < 0)
4692                 chip->dt.vbatt_low_thr_mv = -EINVAL;
4693         else
4694                 chip->dt.vbatt_low_thr_mv = temp;
4695
4696         rc = of_property_read_u32(node, "qcom,fg-chg-term-current", &temp);
4697         if (rc < 0)
4698                 chip->dt.chg_term_curr_ma = DEFAULT_CHG_TERM_CURR_MA;
4699         else
4700                 chip->dt.chg_term_curr_ma = temp;
4701
4702         rc = of_property_read_u32(node, "qcom,fg-sys-term-current", &temp);
4703         if (rc < 0)
4704                 chip->dt.sys_term_curr_ma = DEFAULT_SYS_TERM_CURR_MA;
4705         else
4706                 chip->dt.sys_term_curr_ma = temp;
4707
4708         rc = of_property_read_u32(node, "qcom,fg-chg-term-base-current", &temp);
4709         if (rc < 0)
4710                 chip->dt.chg_term_base_curr_ma = DEFAULT_CHG_TERM_BASE_CURR_MA;
4711         else
4712                 chip->dt.chg_term_base_curr_ma = temp;
4713
4714         rc = of_property_read_u32(node, "qcom,fg-delta-soc-thr", &temp);
4715         if (rc < 0)
4716                 chip->dt.delta_soc_thr = DEFAULT_DELTA_SOC_THR;
4717         else
4718                 chip->dt.delta_soc_thr = temp;
4719
4720         rc = of_property_read_u32(node, "qcom,fg-recharge-soc-thr", &temp);
4721         if (rc < 0)
4722                 chip->dt.recharge_soc_thr = DEFAULT_RECHARGE_SOC_THR;
4723         else
4724                 chip->dt.recharge_soc_thr = temp;
4725
4726         rc = of_property_read_u32(node, "qcom,fg-recharge-voltage", &temp);
4727         if (rc < 0)
4728                 chip->dt.recharge_volt_thr_mv = DEFAULT_RECHARGE_VOLT_MV;
4729         else
4730                 chip->dt.recharge_volt_thr_mv = temp;
4731
4732         chip->dt.auto_recharge_soc = of_property_read_bool(node,
4733                                         "qcom,fg-auto-recharge-soc");
4734
4735         rc = of_property_read_u32(node, "qcom,fg-rsense-sel", &temp);
4736         if (rc < 0)
4737                 chip->dt.rsense_sel = SRC_SEL_BATFET_SMB;
4738         else
4739                 chip->dt.rsense_sel = (u8)temp & SOURCE_SELECT_MASK;
4740
4741         chip->dt.jeita_thresholds[JEITA_COLD] = DEFAULT_BATT_TEMP_COLD;
4742         chip->dt.jeita_thresholds[JEITA_COOL] = DEFAULT_BATT_TEMP_COOL;
4743         chip->dt.jeita_thresholds[JEITA_WARM] = DEFAULT_BATT_TEMP_WARM;
4744         chip->dt.jeita_thresholds[JEITA_HOT] = DEFAULT_BATT_TEMP_HOT;
4745         if (of_property_count_elems_of_size(node, "qcom,fg-jeita-thresholds",
4746                 sizeof(u32)) == NUM_JEITA_LEVELS) {
4747                 rc = of_property_read_u32_array(node,
4748                                 "qcom,fg-jeita-thresholds",
4749                                 chip->dt.jeita_thresholds, NUM_JEITA_LEVELS);
4750                 if (rc < 0)
4751                         pr_warn("Error reading Jeita thresholds, default values will be used rc:%d\n",
4752                                 rc);
4753         }
4754
4755         if (of_property_count_elems_of_size(node,
4756                 "qcom,battery-thermal-coefficients",
4757                 sizeof(u8)) == BATT_THERM_NUM_COEFFS) {
4758                 rc = of_property_read_u8_array(node,
4759                                 "qcom,battery-thermal-coefficients",
4760                                 chip->dt.batt_therm_coeffs,
4761                                 BATT_THERM_NUM_COEFFS);
4762                 if (rc < 0)
4763                         pr_warn("Error reading battery thermal coefficients, rc:%d\n",
4764                                 rc);
4765         }
4766
4767         rc = fg_parse_dt_property_u32_array(node, "qcom,fg-esr-timer-charging",
4768                 chip->dt.esr_timer_charging, NUM_ESR_TIMERS);
4769         if (rc < 0) {
4770                 chip->dt.esr_timer_charging[TIMER_RETRY] = -EINVAL;
4771                 chip->dt.esr_timer_charging[TIMER_MAX] = -EINVAL;
4772         }
4773
4774         rc = fg_parse_dt_property_u32_array(node, "qcom,fg-esr-timer-awake",
4775                 chip->dt.esr_timer_awake, NUM_ESR_TIMERS);
4776         if (rc < 0) {
4777                 chip->dt.esr_timer_awake[TIMER_RETRY] = -EINVAL;
4778                 chip->dt.esr_timer_awake[TIMER_MAX] = -EINVAL;
4779         }
4780
4781         rc = fg_parse_dt_property_u32_array(node, "qcom,fg-esr-timer-asleep",
4782                 chip->dt.esr_timer_asleep, NUM_ESR_TIMERS);
4783         if (rc < 0) {
4784                 chip->dt.esr_timer_asleep[TIMER_RETRY] = -EINVAL;
4785                 chip->dt.esr_timer_asleep[TIMER_MAX] = -EINVAL;
4786         }
4787
4788         chip->cyc_ctr.en = of_property_read_bool(node, "qcom,cycle-counter-en");
4789         if (chip->cyc_ctr.en)
4790                 chip->cyc_ctr.id = 1;
4791
4792         chip->dt.force_load_profile = of_property_read_bool(node,
4793                                         "qcom,fg-force-load-profile");
4794
4795         rc = of_property_read_u32(node, "qcom,cl-start-capacity", &temp);
4796         if (rc < 0)
4797                 chip->dt.cl_start_soc = DEFAULT_CL_START_SOC;
4798         else
4799                 chip->dt.cl_start_soc = temp;
4800
4801         rc = of_property_read_u32(node, "qcom,cl-min-temp", &temp);
4802         if (rc < 0)
4803                 chip->dt.cl_min_temp = DEFAULT_CL_MIN_TEMP_DECIDEGC;
4804         else
4805                 chip->dt.cl_min_temp = temp;
4806
4807         rc = of_property_read_u32(node, "qcom,cl-max-temp", &temp);
4808         if (rc < 0)
4809                 chip->dt.cl_max_temp = DEFAULT_CL_MAX_TEMP_DECIDEGC;
4810         else
4811                 chip->dt.cl_max_temp = temp;
4812
4813         rc = of_property_read_u32(node, "qcom,cl-max-increment", &temp);
4814         if (rc < 0)
4815                 chip->dt.cl_max_cap_inc = DEFAULT_CL_MAX_INC_DECIPERC;
4816         else
4817                 chip->dt.cl_max_cap_inc = temp;
4818
4819         rc = of_property_read_u32(node, "qcom,cl-max-decrement", &temp);
4820         if (rc < 0)
4821                 chip->dt.cl_max_cap_dec = DEFAULT_CL_MAX_DEC_DECIPERC;
4822         else
4823                 chip->dt.cl_max_cap_dec = temp;
4824
4825         rc = of_property_read_u32(node, "qcom,cl-min-limit", &temp);
4826         if (rc < 0)
4827                 chip->dt.cl_min_cap_limit = DEFAULT_CL_MIN_LIM_DECIPERC;
4828         else
4829                 chip->dt.cl_min_cap_limit = temp;
4830
4831         rc = of_property_read_u32(node, "qcom,cl-max-limit", &temp);
4832         if (rc < 0)
4833                 chip->dt.cl_max_cap_limit = DEFAULT_CL_MAX_LIM_DECIPERC;
4834         else
4835                 chip->dt.cl_max_cap_limit = temp;
4836
4837         rc = of_property_read_u32(node, "qcom,fg-jeita-hyst-temp", &temp);
4838         if (rc < 0)
4839                 chip->dt.jeita_hyst_temp = -EINVAL;
4840         else
4841                 chip->dt.jeita_hyst_temp = temp;
4842
4843         rc = of_property_read_u32(node, "qcom,fg-batt-temp-delta", &temp);
4844         if (rc < 0)
4845                 chip->dt.batt_temp_delta = -EINVAL;
4846         else if (temp > BTEMP_DELTA_LOW && temp <= BTEMP_DELTA_HIGH)
4847                 chip->dt.batt_temp_delta = temp;
4848
4849         chip->dt.hold_soc_while_full = of_property_read_bool(node,
4850                                         "qcom,hold-soc-while-full");
4851
4852         chip->dt.linearize_soc = of_property_read_bool(node,
4853                                         "qcom,linearize-soc");
4854
4855         rc = fg_parse_ki_coefficients(chip);
4856         if (rc < 0)
4857                 pr_err("Error in parsing Ki coefficients, rc=%d\n", rc);
4858
4859         rc = of_property_read_u32(node, "qcom,fg-rconn-mohms", &temp);
4860         if (!rc)
4861                 chip->dt.rconn_mohms = temp;
4862
4863         rc = of_property_read_u32(node, "qcom,fg-esr-filter-switch-temp",
4864                         &temp);
4865         if (rc < 0)
4866                 chip->dt.esr_flt_switch_temp = DEFAULT_ESR_FLT_TEMP_DECIDEGC;
4867         else
4868                 chip->dt.esr_flt_switch_temp = temp;
4869
4870         rc = of_property_read_u32(node, "qcom,fg-esr-tight-filter-micro-pct",
4871                         &temp);
4872         if (rc < 0)
4873                 chip->dt.esr_tight_flt_upct = DEFAULT_ESR_TIGHT_FLT_UPCT;
4874         else
4875                 chip->dt.esr_tight_flt_upct = temp;
4876
4877         rc = of_property_read_u32(node, "qcom,fg-esr-broad-filter-micro-pct",
4878                         &temp);
4879         if (rc < 0)
4880                 chip->dt.esr_broad_flt_upct = DEFAULT_ESR_BROAD_FLT_UPCT;
4881         else
4882                 chip->dt.esr_broad_flt_upct = temp;
4883
4884         rc = of_property_read_u32(node, "qcom,fg-esr-tight-lt-filter-micro-pct",
4885                         &temp);
4886         if (rc < 0)
4887                 chip->dt.esr_tight_lt_flt_upct = DEFAULT_ESR_TIGHT_LT_FLT_UPCT;
4888         else
4889                 chip->dt.esr_tight_lt_flt_upct = temp;
4890
4891         rc = of_property_read_u32(node, "qcom,fg-esr-broad-lt-filter-micro-pct",
4892                         &temp);
4893         if (rc < 0)
4894                 chip->dt.esr_broad_lt_flt_upct = DEFAULT_ESR_BROAD_LT_FLT_UPCT;
4895         else
4896                 chip->dt.esr_broad_lt_flt_upct = temp;
4897
4898         rc = fg_parse_slope_limit_coefficients(chip);
4899         if (rc < 0)
4900                 pr_err("Error in parsing slope limit coeffs, rc=%d\n", rc);
4901
4902         rc = of_property_read_u32(node, "qcom,fg-esr-clamp-mohms", &temp);
4903         if (rc < 0)
4904                 chip->dt.esr_clamp_mohms = DEFAULT_ESR_CLAMP_MOHMS;
4905         else
4906                 chip->dt.esr_clamp_mohms = temp;
4907
4908         chip->dt.esr_pulse_thresh_ma = DEFAULT_ESR_PULSE_THRESH_MA;
4909         rc = of_property_read_u32(node, "qcom,fg-esr-pulse-thresh-ma", &temp);
4910         if (!rc) {
4911                 /* ESR pulse qualification threshold range is 1-997 mA */
4912                 if (temp > 0 && temp < 997)
4913                         chip->dt.esr_pulse_thresh_ma = temp;
4914         }
4915
4916         chip->dt.esr_meas_curr_ma = DEFAULT_ESR_MEAS_CURR_MA;
4917         rc = of_property_read_u32(node, "qcom,fg-esr-meas-curr-ma", &temp);
4918         if (!rc) {
4919                 /* ESR measurement current range is 60-240 mA */
4920                 if (temp >= 60 || temp <= 240)
4921                         chip->dt.esr_meas_curr_ma = temp;
4922         }
4923
4924         return 0;
4925 }
4926
4927 static void fg_cleanup(struct fg_chip *chip)
4928 {
4929         power_supply_unreg_notifier(&chip->nb);
4930         debugfs_remove_recursive(chip->dfs_root);
4931         if (chip->awake_votable)
4932                 destroy_votable(chip->awake_votable);
4933
4934         if (chip->delta_bsoc_irq_en_votable)
4935                 destroy_votable(chip->delta_bsoc_irq_en_votable);
4936
4937         if (chip->batt_miss_irq_en_votable)
4938                 destroy_votable(chip->batt_miss_irq_en_votable);
4939
4940         if (chip->batt_id_chan)
4941                 iio_channel_release(chip->batt_id_chan);
4942
4943         dev_set_drvdata(chip->dev, NULL);
4944 }
4945
4946 static int fg_gen3_probe(struct platform_device *pdev)
4947 {
4948         struct fg_chip *chip;
4949         struct power_supply_config fg_psy_cfg;
4950         int rc, msoc, volt_uv, batt_temp;
4951
4952         chip = devm_kzalloc(&pdev->dev, sizeof(*chip), GFP_KERNEL);
4953         if (!chip)
4954                 return -ENOMEM;
4955
4956         chip->dev = &pdev->dev;
4957         chip->debug_mask = &fg_gen3_debug_mask;
4958         chip->irqs = fg_irqs;
4959         chip->charge_status = -EINVAL;
4960         chip->ki_coeff_full_soc = -EINVAL;
4961         chip->online_status = -EINVAL;
4962         chip->regmap = dev_get_regmap(chip->dev->parent, NULL);
4963         if (!chip->regmap) {
4964                 dev_err(chip->dev, "Parent regmap is unavailable\n");
4965                 return -ENXIO;
4966         }
4967
4968         chip->batt_id_chan = iio_channel_get(chip->dev, "rradc_batt_id");
4969         if (IS_ERR(chip->batt_id_chan)) {
4970                 if (PTR_ERR(chip->batt_id_chan) != -EPROBE_DEFER)
4971                         pr_err("batt_id_chan unavailable %ld\n",
4972                                 PTR_ERR(chip->batt_id_chan));
4973                 rc = PTR_ERR(chip->batt_id_chan);
4974                 chip->batt_id_chan = NULL;
4975                 return rc;
4976         }
4977
4978         rc = of_property_match_string(chip->dev->of_node,
4979                                 "io-channel-names", "rradc_die_temp");
4980         if (rc >= 0) {
4981                 chip->die_temp_chan = iio_channel_get(chip->dev,
4982                                                 "rradc_die_temp");
4983                 if (IS_ERR(chip->die_temp_chan)) {
4984                         if (PTR_ERR(chip->die_temp_chan) != -EPROBE_DEFER)
4985                                 pr_err("rradc_die_temp unavailable %ld\n",
4986                                         PTR_ERR(chip->die_temp_chan));
4987                         rc = PTR_ERR(chip->die_temp_chan);
4988                         chip->die_temp_chan = NULL;
4989                         return rc;
4990                 }
4991         }
4992
4993         chip->awake_votable = create_votable("FG_WS", VOTE_SET_ANY, fg_awake_cb,
4994                                         chip);
4995         if (IS_ERR(chip->awake_votable)) {
4996                 rc = PTR_ERR(chip->awake_votable);
4997                 chip->awake_votable = NULL;
4998                 goto exit;
4999         }
5000
5001         chip->delta_bsoc_irq_en_votable = create_votable("FG_DELTA_BSOC_IRQ",
5002                                                 VOTE_SET_ANY,
5003                                                 fg_delta_bsoc_irq_en_cb, chip);
5004         if (IS_ERR(chip->delta_bsoc_irq_en_votable)) {
5005                 rc = PTR_ERR(chip->delta_bsoc_irq_en_votable);
5006                 chip->delta_bsoc_irq_en_votable = NULL;
5007                 goto exit;
5008         }
5009
5010         chip->batt_miss_irq_en_votable = create_votable("FG_BATT_MISS_IRQ",
5011                                                 VOTE_SET_ANY,
5012                                                 fg_batt_miss_irq_en_cb, chip);
5013         if (IS_ERR(chip->batt_miss_irq_en_votable)) {
5014                 rc = PTR_ERR(chip->batt_miss_irq_en_votable);
5015                 chip->batt_miss_irq_en_votable = NULL;
5016                 goto exit;
5017         }
5018
5019         rc = fg_parse_dt(chip);
5020         if (rc < 0) {
5021                 dev_err(chip->dev, "Error in reading DT parameters, rc:%d\n",
5022                         rc);
5023                 goto exit;
5024         }
5025
5026         mutex_init(&chip->bus_lock);
5027         mutex_init(&chip->sram_rw_lock);
5028         mutex_init(&chip->cyc_ctr.lock);
5029         mutex_init(&chip->cl.lock);
5030         mutex_init(&chip->ttf.lock);
5031         mutex_init(&chip->charge_full_lock);
5032         mutex_init(&chip->qnovo_esr_ctrl_lock);
5033         init_completion(&chip->soc_update);
5034         init_completion(&chip->soc_ready);
5035         INIT_DELAYED_WORK(&chip->profile_load_work, profile_load_work);
5036         INIT_WORK(&chip->status_change_work, status_change_work);
5037         INIT_DELAYED_WORK(&chip->ttf_work, ttf_work);
5038         INIT_DELAYED_WORK(&chip->sram_dump_work, sram_dump_work);
5039
5040         rc = fg_memif_init(chip);
5041         if (rc < 0) {
5042                 dev_err(chip->dev, "Error in initializing FG_MEMIF, rc:%d\n",
5043                         rc);
5044                 goto exit;
5045         }
5046
5047         rc = fg_hw_init(chip);
5048         if (rc < 0) {
5049                 dev_err(chip->dev, "Error in initializing FG hardware, rc:%d\n",
5050                         rc);
5051                 goto exit;
5052         }
5053
5054         platform_set_drvdata(pdev, chip);
5055
5056         /* Register the power supply */
5057         fg_psy_cfg.drv_data = chip;
5058         fg_psy_cfg.of_node = NULL;
5059         fg_psy_cfg.supplied_to = NULL;
5060         fg_psy_cfg.num_supplicants = 0;
5061         chip->fg_psy = devm_power_supply_register(chip->dev, &fg_psy_desc,
5062                         &fg_psy_cfg);
5063         if (IS_ERR(chip->fg_psy)) {
5064                 pr_err("failed to register fg_psy rc = %ld\n",
5065                                 PTR_ERR(chip->fg_psy));
5066                 goto exit;
5067         }
5068
5069         chip->nb.notifier_call = fg_notifier_cb;
5070         rc = power_supply_reg_notifier(&chip->nb);
5071         if (rc < 0) {
5072                 pr_err("Couldn't register psy notifier rc = %d\n", rc);
5073                 goto exit;
5074         }
5075
5076         rc = fg_register_interrupts(chip);
5077         if (rc < 0) {
5078                 dev_err(chip->dev, "Error in registering interrupts, rc:%d\n",
5079                         rc);
5080                 goto exit;
5081         }
5082
5083         /* Keep SOC_UPDATE_IRQ disabled until we require it */
5084         if (fg_irqs[SOC_UPDATE_IRQ].irq)
5085                 disable_irq_nosync(fg_irqs[SOC_UPDATE_IRQ].irq);
5086
5087         /* Keep BSOC_DELTA_IRQ disabled until we require it */
5088         vote(chip->delta_bsoc_irq_en_votable, DELTA_BSOC_IRQ_VOTER, false, 0);
5089
5090         /* Keep BATT_MISSING_IRQ disabled until we require it */
5091         vote(chip->batt_miss_irq_en_votable, BATT_MISS_IRQ_VOTER, false, 0);
5092
5093         rc = fg_debugfs_create(chip);
5094         if (rc < 0) {
5095                 dev_err(chip->dev, "Error in creating debugfs entries, rc:%d\n",
5096                         rc);
5097                 goto exit;
5098         }
5099
5100         rc = fg_get_battery_voltage(chip, &volt_uv);
5101         if (!rc)
5102                 rc = fg_get_prop_capacity(chip, &msoc);
5103
5104         if (!rc)
5105                 rc = fg_get_battery_temp(chip, &batt_temp);
5106
5107         if (!rc) {
5108                 pr_info("battery SOC:%d voltage: %duV temp: %d id: %dKOhms\n",
5109                         msoc, volt_uv, batt_temp, chip->batt_id_ohms / 1000);
5110                 rc = fg_esr_filter_config(chip, batt_temp);
5111                 if (rc < 0)
5112                         pr_err("Error in configuring ESR filter rc:%d\n", rc);
5113         }
5114
5115         device_init_wakeup(chip->dev, true);
5116         schedule_delayed_work(&chip->profile_load_work, 0);
5117
5118         pr_debug("FG GEN3 driver probed successfully\n");
5119         return 0;
5120 exit:
5121         fg_cleanup(chip);
5122         return rc;
5123 }
5124
5125 static int fg_gen3_suspend(struct device *dev)
5126 {
5127         struct fg_chip *chip = dev_get_drvdata(dev);
5128         int rc;
5129
5130         rc = fg_esr_timer_config(chip, true);
5131         if (rc < 0)
5132                 pr_err("Error in configuring ESR timer, rc=%d\n", rc);
5133
5134         cancel_delayed_work_sync(&chip->ttf_work);
5135         if (fg_sram_dump)
5136                 cancel_delayed_work_sync(&chip->sram_dump_work);
5137         return 0;
5138 }
5139
5140 static int fg_gen3_resume(struct device *dev)
5141 {
5142         struct fg_chip *chip = dev_get_drvdata(dev);
5143         int rc;
5144
5145         rc = fg_esr_timer_config(chip, false);
5146         if (rc < 0)
5147                 pr_err("Error in configuring ESR timer, rc=%d\n", rc);
5148
5149         schedule_delayed_work(&chip->ttf_work, 0);
5150         if (fg_sram_dump)
5151                 schedule_delayed_work(&chip->sram_dump_work,
5152                                 msecs_to_jiffies(fg_sram_dump_period_ms));
5153         return 0;
5154 }
5155
5156 static const struct dev_pm_ops fg_gen3_pm_ops = {
5157         .suspend        = fg_gen3_suspend,
5158         .resume         = fg_gen3_resume,
5159 };
5160
5161 static int fg_gen3_remove(struct platform_device *pdev)
5162 {
5163         struct fg_chip *chip = dev_get_drvdata(&pdev->dev);
5164
5165         fg_cleanup(chip);
5166         return 0;
5167 }
5168
5169 static void fg_gen3_shutdown(struct platform_device *pdev)
5170 {
5171         struct fg_chip *chip = dev_get_drvdata(&pdev->dev);
5172         int rc, bsoc;
5173
5174         if (chip->charge_full) {
5175                 rc = fg_get_sram_prop(chip, FG_SRAM_BATT_SOC, &bsoc);
5176                 if (rc < 0) {
5177                         pr_err("Error in getting BATT_SOC, rc=%d\n", rc);
5178                         return;
5179                 }
5180
5181                 /* We need 2 most significant bytes here */
5182                 bsoc = (u32)bsoc >> 16;
5183
5184                 rc = fg_configure_full_soc(chip, bsoc);
5185                 if (rc < 0) {
5186                         pr_err("Error in configuring full_soc, rc=%d\n", rc);
5187                         return;
5188                 }
5189         }
5190 }
5191
5192 static const struct of_device_id fg_gen3_match_table[] = {
5193         {.compatible = FG_GEN3_DEV_NAME},
5194         {},
5195 };
5196
5197 static struct platform_driver fg_gen3_driver = {
5198         .driver = {
5199                 .name = FG_GEN3_DEV_NAME,
5200                 .owner = THIS_MODULE,
5201                 .of_match_table = fg_gen3_match_table,
5202                 .pm             = &fg_gen3_pm_ops,
5203         },
5204         .probe          = fg_gen3_probe,
5205         .remove         = fg_gen3_remove,
5206         .shutdown       = fg_gen3_shutdown,
5207 };
5208
5209 static int __init fg_gen3_init(void)
5210 {
5211         return platform_driver_register(&fg_gen3_driver);
5212 }
5213
5214 static void __exit fg_gen3_exit(void)
5215 {
5216         return platform_driver_unregister(&fg_gen3_driver);
5217 }
5218
5219 module_init(fg_gen3_init);
5220 module_exit(fg_gen3_exit);
5221
5222 MODULE_DESCRIPTION("QPNP Fuel gauge GEN3 driver");
5223 MODULE_LICENSE("GPL v2");
5224 MODULE_ALIAS("platform:" FG_GEN3_DEV_NAME);