summaryrefslogtreecommitdiff
path: root/max1720x_battery.c
blob: 8e99bc7c7d0bcc3488129f33c259ab75d6841657 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
/*
 * Fuel gauge driver for Maxim 17201/17205
 *
 * Copyright (C) 2018 Google Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#define pr_fmt(fmt) KBUILD_MODNAME ": %s " fmt, __func__

#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/iio/consumer.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/pm_runtime.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <linux/time.h>

#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h> /* register_chrdev, unregister_chrdev */
#include <linux/seq_file.h> /* seq_read, seq_lseek, single_release */
#include "gbms_power_supply.h"
#include "google_bms.h"
#include "max1720x_battery.h"
#include "maxfg_logging.h"

#include <linux/debugfs.h>

#define MAX17X0X_TPOR_MS 150

#define MAX1720X_TRECALL_MS 5
#define MAX1730X_TRECALL_MS 5
#define MAX1720X_TICLR_MS 500
#define MAX1720X_I2C_DRIVER_NAME "max_fg_irq"
#define MAX1720X_DELAY_INIT_MS 1000
#define FULLCAPNOM_STABILIZE_CYCLES 5
#define CYCLE_BUCKET_SIZE 200
#define TEMP_BUCKET_SIZE 5		/* unit is 0.1 degree C */
#define NB_CYCLE_BUCKETS 4

/* capacity drift */
#define BATTERY_DEFAULT_CYCLE_STABLE	0
#define BATTERY_DEFAULT_CYCLE_FADE	0
#define BATTERY_DEFAULT_CYCLE_BAND	10
#define BATTERY_MAX_CYCLE_BAND		20

#define HISTORY_DEVICENAME "maxfg_history"

#define FILTERCFG_TEMP_HYSTERESIS	30

#define BHI_IMPEDANCE_SOC_LO		50
#define BHI_IMPEDANCE_SOC_HI		55
#define BHI_IMPEDANCE_TEMP_LO		250
#define BHI_IMPEDANCE_TEMP_HI		300
#define BHI_IMPEDANCE_CYCLE_CNT		5
#define BHI_IMPEDANCE_TIMERH		50 /* 7*24 / 3.2hr */

#include "max1720x.h"
#include "max1730x.h"
#include "max_m5.h"

enum max17xxx_register {
	MAX17XXX_COMMAND	= MAX1720X_COMMAND,
};

enum max17xxx_nvram {
	MAX17XXX_QHCA = MAX1720X_NUSER18C,
	MAX17XXX_QHQH = MAX1720X_NUSER18D,
};

enum max17xxx_command_bits {
	MAX17XXX_COMMAND_NV_RECALL	  = 0xE001,
};

/* Capacity Estimation */
struct gbatt_capacity_estimation {
	const struct max17x0x_reg *bcea;
	struct mutex batt_ce_lock;
	struct delayed_work settle_timer;
	int cap_tsettle;
	int cap_filt_length;
	int estimate_state;
	bool cable_in;
	int delta_cc_sum;
	int delta_vfsoc_sum;
	int cap_filter_count;
	int start_cc;
	int start_vfsoc;
};

struct max1720x_rc_switch {
	struct delayed_work switch_work;
	bool available;
	bool enable;
	int soc;
	int temp;
	u16 rc1_tempco;
	u16 rc2_tempco;
	u16 rc2_learncfg;
};

#define DEFAULT_BATTERY_ID		0
#define DEFAULT_BATTERY_ID_RETRIES	5
#define DUMMY_BATTERY_ID		170

#define DEFAULT_CAP_SETTLE_INTERVAL	3
#define DEFAULT_CAP_FILTER_LENGTH	12

#define ESTIMATE_DONE		2
#define ESTIMATE_PENDING	1
#define ESTIMATE_NONE		0

#define CE_CAP_FILTER_COUNT	0
#define CE_DELTA_CC_SUM_REG	1
#define CE_DELTA_VFSOC_SUM_REG	2

#define CE_FILTER_COUNT_MAX	15

#define BHI_CAP_FCN_COUNT	3

#define DEFAULT_STATUS_CHARGE_MA	100

#pragma pack(1)
struct max17x0x_eeprom_history {
	u16 tempco;
	u16 rcomp0;
	u8 timerh;
	unsigned fullcapnom:10;
	unsigned fullcaprep:10;
	unsigned mixsoc:6;
	unsigned vfsoc:6;
	unsigned maxvolt:4;
	unsigned minvolt:4;
	unsigned maxtemp:4;
	unsigned mintemp:4;
	unsigned maxchgcurr:4;
	unsigned maxdischgcurr:4;
};
#pragma pack()


struct max1720x_history {
	int page_size;

	loff_t history_index;
	int history_count;
	bool *page_status;
	u16 *history;
};

struct max1720x_chip {
	struct device *dev;
	bool irq_shared;
	struct i2c_client *primary;
	struct i2c_client *secondary;

	int gauge_type;	/* -1 not present, 0=max1720x, 1=max1730x */
	struct max17x0x_regmap regmap;
	struct max17x0x_regmap regmap_nvram;

	struct power_supply *psy;
	struct delayed_work init_work;
	struct device_node *batt_node;

	u16 devname;
	struct max17x0x_cache_data nRAM_por;
	bool needs_reset;
	int (*fixups_fn)(struct max1720x_chip *chip);

	/* config */
	void *model_data;
	struct mutex model_lock;
	struct delayed_work model_work;
	int model_next_update;
	/* also used to restore model state from permanent storage */
	u16 reg_prop_capacity_raw;
	bool model_state_valid;	/* state read from persistent */
	int model_reload;
	bool model_ok;		/* model is running */
	bool cycle_reg_ok;	/* restore cycle count from storage complete */

	/* history */
	struct mutex history_lock;
	int hcmajor;
	struct cdev hcdev;
	struct class *hcclass;
	bool history_available;
	bool history_added;
	int history_page_size;
	int nb_history_pages;
	int nb_history_flag_reg;

	int fake_battery;
	/* for storage interface */
	struct max1720x_history history_storage;

	u16 RSense;
	u16 RConfig;

	int batt_id;
	int batt_id_defer_cnt;
	int cycle_count;
	int cycle_count_offset;
	u16 eeprom_cycle;
	u16 designcap;

	bool init_complete;
	bool resume_complete;
	bool irq_disabled;
	u16 health_status;
	int fake_capacity;
	int previous_qh;
	int current_capacity;
	int prev_charge_status;
	char serial_number[30];
	bool offmode_charger;
	s32 convgcfg_hysteresis;
	int nb_convgcfg;
	int curr_convgcfg_idx;
	s16 *temp_convgcfg;
	u16 *convgcfg_values;
	struct mutex convgcfg_lock;
	struct max1720x_dyn_filtercfg dyn_filtercfg;
	bool shadow_override;
	int nb_empty_voltage;
	u16 *empty_voltage;
	bool por;

	unsigned int debug_irq_none_cnt;
	unsigned long icnt;
	int zero_irq;

	/* fix capacity drift */
	struct max1720x_drift_data drift_data;
	int comp_update_count;
	int dxacc_update_count;

	/* Capacity Estimation */
	struct gbatt_capacity_estimation cap_estimate;
	struct logbuffer *ce_log;

	/* debug interface, register to read or write */
	u32 debug_reg_address;

	/* dump data to logbuffer periodically */
	struct logbuffer *monitor_log;
	u16 pre_repsoc;

	struct power_supply_desc max1720x_psy_desc;

	int bhi_fcn_count;
	int bhi_acim;

	struct max1720x_rc_switch rc_switch;

	/* battery current criteria for report status charge */
	u32 status_charge_threshold_ma;

	/* re-calibration */
	int bhi_recalibration_algo; /* 0:release, 1:internal */
	int bhi_target_capacity;

	struct wakeup_source *get_prop_ws;

	int timerh_base;

	/* Current Offset */
	bool current_offset_done;

	/* buffer for recording learning history */
	struct maxfg_capture_buf cb_lh;
};

#define MAX1720_EMPTY_VOLTAGE(profile, temp, cycle) \
	profile->empty_voltage[temp * NB_CYCLE_BUCKETS + cycle]


static irqreturn_t max1720x_fg_irq_thread_fn(int irq, void *obj);
static int max1720x_set_next_update(struct max1720x_chip *chip);
static int max1720x_monitor_log_data(struct max1720x_chip *chip, bool force_log);
static int max17201_init_rc_switch(struct max1720x_chip *chip);
static int max1720x_update_cycle_count(struct max1720x_chip *chip);

static bool max17x0x_reglog_init(struct max1720x_chip *chip)
{
	chip->regmap.reglog =
		devm_kzalloc(chip->dev, sizeof(*chip->regmap.reglog),
			     GFP_KERNEL);
	chip->regmap_nvram.reglog =
		devm_kzalloc(chip->dev, sizeof(*chip->regmap.reglog),
			     GFP_KERNEL);

	return chip->regmap.reglog && chip->regmap_nvram.reglog;
}

/* ------------------------------------------------------------------------- */


/* TODO: split between NV and Volatile? */




/* ------------------------------------------------------------------------- */

/*
 * offset of the register in this atom.
 * NOTE: this is the byte offset regardless of the size of the register
 */
static int max17x0x_reg_offset_of(const struct max17x0x_reg *a,
				  unsigned int reg)
{
	int i;

	switch (a->type) {
	case GBMS_ATOM_TYPE_REG:
		return (reg == a->reg) ? 0 : -EINVAL;
	case GBMS_ATOM_TYPE_ZONE:
		if (reg >= a->base && reg < a->base + a->size)
			return (reg - a->base) * 2;
		break;
	case GBMS_ATOM_TYPE_MAP:
		for (i = 0 ; i < a->size ; i++)
			if (a->map[i] == reg)
				return i * 2;
		break;
	}

	return -ERANGE;
}

static int max17x0x_reg_store_sz(struct max17x0x_regmap *map,
				 const struct max17x0x_reg *a,
				 const void *data,
				 int size)
{
	int i, ret;

	if (size > a->size)
		size = a->size;

	if (a->type == GBMS_ATOM_TYPE_MAP) {
		const u16 *b = (u16 *)data;

		if (size % 2)
			return -ERANGE;

		for (i = 0; i < size / 2 ; i++) {
			ret = regmap_write(map->regmap, a->map[i], b[i]);
			if (ret < 0)
				break;

			max17x0x_reglog_log(map->reglog, a->map[i], b[i], ret);
		}
	} else if (a->type == GBMS_ATOM_TYPE_SET) {
		ret = -EINVAL;
	} else {
		ret = regmap_raw_write(map->regmap, a->base, data, size);

		if (map->reglog) {
			const u16 *b = (u16 *)data;

			for (i = 0; i < size ; i += 2)
				max17x0x_reglog_log(map->reglog, a->base + i,
						    b[i], ret);
		}
	}

	return ret;
}

static int max17x0x_reg_load_sz(struct max17x0x_regmap *map,
				const struct max17x0x_reg *a,
				void *data,
				int size)
{
	int ret;

	if (size > a->size)
		size = a->size;

	if (a->type == GBMS_ATOM_TYPE_MAP) {
		int i;
		unsigned int tmp;
		u16 *b = (u16 *)data;

		if (size % 2)
			return -ERANGE;

		for (i = 0; i < size / 2 ; i++) {
			ret = regmap_read(map->regmap,
					  (unsigned int)a->map[i],
					  &tmp);
			if (ret < 0)
				break;
			b[i] = tmp;
		}
	} else if (a->type == GBMS_ATOM_TYPE_SET) {
		ret = -EINVAL;
	} else {
		ret = regmap_raw_read(map->regmap, a->base, data, size);
	}

	return ret;
}

#define max17x0x_reg_store(map, a, data) \
	max17x0x_reg_store_sz(map, a, data, (a)->size)

#define max17x0x_reg_load(map, a, data) \
	max17x0x_reg_load_sz(map, a, data, (a)->size)


static u16 *batt_alloc_array(int count, int size)
{
	return (u16 *)kmalloc_array(count, size, GFP_KERNEL);
}

/* CACHE ----------------------------------------------------------------- */

static int max17x0x_cache_index_of(const struct max17x0x_cache_data *cache,
				   unsigned int reg)
{
	const int offset = max17x0x_reg_offset_of(&cache->atom, reg);

	return (offset < 0) ? offset : offset / 2;
}

#define max17x0x_cache_store(cache, regmap) \
	max17x0x_reg_store(regmap, &(cache)->atom, (cache)->cache_data)

#define max17x0x_cache_load(cache, regmap) \
	max17x0x_reg_load(regmap, &(cache)->atom, (cache)->cache_data)

#define max17x0x_cache_memcmp(src, dst) \
	memcmp((src)->cache_data, (dst)->cache_data, (src)->atom.size)

static void max17x0x_cache_free(struct max17x0x_cache_data *cache)
{
	kfree(cache->cache_data);
	cache->cache_data = NULL;
}

static int max17x0x_cache_dup(struct max17x0x_cache_data *dst,
			      const struct max17x0x_cache_data *src)
{
	memcpy(dst, src, sizeof(*dst));

	dst->cache_data = (u16 *)kmalloc(src->atom.size, GFP_KERNEL);
	if (!dst->cache_data)
		return -ENOMEM;

	memcpy(dst->cache_data, src->cache_data, src->atom.size);
	return 0;
}

static int max17x0x_cache_init(struct max17x0x_cache_data *cache,
				     u16 start, int end)
{
	const int count = end - start + 1; /* includes end */

	memset(cache, 0, sizeof(*cache));

	cache->cache_data = batt_alloc_array(count, sizeof(u16));
	if (!cache->cache_data)
		return -ENOMEM;

	cache->atom.type = GBMS_ATOM_TYPE_ZONE;
	cache->atom.size = count * sizeof(u16);
	cache->atom.base = start;

	return 0;
}

static int max17x0x_nvram_cache_init(struct max17x0x_cache_data *cache,
				     int gauge_type)
{
	int ret;

	if (gauge_type == MAX1730X_GAUGE_TYPE) {
		ret = max17x0x_cache_init(cache,
					  MAX1730X_NVRAM_START,
					  MAX1730X_NVRAM_END);
	} else {
		ret = max17x0x_cache_init(cache,
					  MAX1720X_NVRAM_START,
					  MAX1720X_NVRAM_END);
	}

	return ret;
}

/* ------------------------------------------------------------------------- */

static inline int reg_to_percentage(u16 val)
{
	/* LSB: 1/256% */
	return val >> 8;
}

static inline int reg_to_twos_comp_int(u16 val)
{
	/* Convert u16 to twos complement  */
	return -(val & 0x8000) + (val & 0x7FFF);
}

static inline int reg_to_micro_amp(s16 val, u16 rsense)
{
	/* LSB: 1.5625μV/RSENSE ; Rsense LSB is 10μΩ */
	return div_s64((s64) val * 156250, rsense);
}

static inline int reg_to_deci_deg_cel(s16 val)
{
	/* LSB: 1/256°C */
	return div_s64((s64) val * 10, 256);
}

static inline int reg_to_resistance_micro_ohms(s16 val, u16 rsense)
{
	/* LSB: 1/4096 Ohm */
	return div_s64((s64) val * 1000 * rsense, 4096);
}

static inline int reg_to_cycles(u32 val, int gauge_type)
{
	if (gauge_type == MAX_M5_GAUGE_TYPE) {
		/* LSB: 1% of one cycle */
		return DIV_ROUND_CLOSEST(val, 100);
	} else {
		/* LSB: 16% of one cycle */
		return DIV_ROUND_CLOSEST(val * 16, 100);
	}
}

static inline int reg_to_seconds(s16 val)
{
	/* LSB: 5.625 seconds */
	return DIV_ROUND_CLOSEST((int) val * 5625, 1000);
}

static inline int reg_to_vempty(u16 val)
{
	return ((val >> 7) & 0x1FF) * 10;
}

static inline int reg_to_vrecovery(u16 val)
{
	return (val & 0x7F) * 40;
}

/* b/177099997 TaskPeriod ----------------------------------------------- */

static inline int reg_to_capacity_uah(u16 val, struct max1720x_chip *chip)
{
	const int lsb = max_m5_cap_lsb(chip->model_data);

	return reg_to_micro_amp_h(val, chip->RSense, lsb);
}

static inline int reg_to_time_hr(u16 val, struct max1720x_chip *chip)
{
	const int lsb = max_m5_cap_lsb(chip->model_data);

	return (val * 32 * lsb) / 10;
}

#if 0
/* TODO: will need in outliers */
static inline int capacity_uah_to_reg(int capacity, struct max1720x_chip *chip)
{
	const int lsb = max_m5_cap_lsb(chip->model_data);

	return micro_amp_h_to_reg(capacity / lsb, chip->RSense);
}
#endif

/* log ----------------------------------------------------------------- */

static void max1730x_read_log_write_status(struct max1720x_chip *chip,
					   u16 *buffer)
{
	u16 i;
	u16 data = 0;
	const struct max17x0x_reg *hsty;

	hsty = max17x0x_find_by_tag(&chip->regmap_nvram, MAX17X0X_TAG_HSTY);
	if (!hsty)
		return;

	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1730X_COMMAND_HISTORY_RECALL_WRITE_0);
	msleep(MAX1730X_TRECALL_MS);
	for (i = hsty->map[1]; i <= hsty->map[3]; i++) {
		(void)REGMAP_READ(&chip->regmap_nvram, i, &data);
		*buffer++ = data;
	}
}

static void max1730x_read_log_valid_status(struct max1720x_chip *chip,
					   u16 *buffer)
{
	u16 i;
	u16 data = 0;
	const struct max17x0x_reg *hsty;

	hsty = max17x0x_find_by_tag(&chip->regmap_nvram, MAX17X0X_TAG_HSTY);

	if (!hsty)
		return;

	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1730X_COMMAND_HISTORY_RECALL_VALID_0);
	msleep(MAX1730X_TRECALL_MS);
	(void)REGMAP_READ(&chip->regmap_nvram, hsty->map[4], &data);
	*buffer++ = data;

	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1730X_COMMAND_HISTORY_RECALL_VALID_1);
	msleep(MAX1730X_TRECALL_MS);
	for (i = hsty->map[0]; i <= hsty->map[2]; i++) {
		(void)REGMAP_READ(&chip->regmap_nvram, i, &data);
		*buffer++ = data;
	}
}

static void max1720x_read_log_write_status(struct max1720x_chip *chip,
					   u16 *buffer)
{
	int i;
	u16 data = 0;

	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1720X_COMMAND_HISTORY_RECALL_WRITE_0);
	msleep(MAX1720X_TRECALL_MS);
	for (i = MAX1720X_NVRAM_HISTORY_WRITE_STATUS_START;
	     i <= MAX1720X_NVRAM_HISTORY_END; i++) {
		(void)REGMAP_READ(&chip->regmap_nvram, i, &data);
		*buffer++ = data;
	}
	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1720X_COMMAND_HISTORY_RECALL_WRITE_1);
	msleep(MAX1720X_TRECALL_MS);
	for (i = MAX1720X_HISTORY_START;
	     i <= MAX1720X_NVRAM_HISTORY_WRITE_STATUS_END; i++) {
		(void)REGMAP_READ(&chip->regmap_nvram, i, &data);
		*buffer++ = data;
	}
}

static void max1720x_read_log_valid_status(struct max1720x_chip *chip,
					   u16 *buffer)
{
	int i;
	u16 data = 0;

	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1720X_COMMAND_HISTORY_RECALL_VALID_0);
	msleep(MAX1720X_TRECALL_MS);
	for (i = MAX1720X_NVRAM_HISTORY_VALID_STATUS_START;
	     i <= MAX1720X_NVRAM_HISTORY_END; i++) {
		(void)REGMAP_READ(&chip->regmap_nvram, i, &data);
		*buffer++ = data;
	}
	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1720X_COMMAND_HISTORY_RECALL_VALID_1);
	msleep(MAX1720X_TRECALL_MS);
	for (i = MAX1720X_HISTORY_START;
	     i <= MAX1720X_NVRAM_HISTORY_END; i++) {
		(void)REGMAP_READ(&chip->regmap_nvram, i, &data);
		*buffer++ = data;
	}
	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1720X_COMMAND_HISTORY_RECALL_VALID_2);
	msleep(MAX1720X_TRECALL_MS);
	for (i = MAX1720X_HISTORY_START;
	     i <= MAX1720X_NVRAM_HISTORY_VALID_STATUS_END; i++) {
		(void)REGMAP_READ(&chip->regmap_nvram, i, &data);
		*buffer++ = data;
	}
}

/* @return the number of pages or negative for error */
static int get_battery_history_status(struct max1720x_chip *chip,
				      bool *page_status)
{
	u16 *write_status, *valid_status;
	int i, addr_offset, bit_offset, nb_history_pages;
	int valid_history_entry_count = 0;

	write_status = batt_alloc_array(chip->nb_history_flag_reg, sizeof(u16));
	if (!write_status)
		return -ENOMEM;

	valid_status = batt_alloc_array(chip->nb_history_flag_reg, sizeof(u16));
	if (!valid_status) {
		kfree(write_status);
		return -ENOMEM;
	}

	if (chip->gauge_type == MAX1730X_GAUGE_TYPE) {
		max1730x_read_log_write_status(chip, write_status);
		max1730x_read_log_valid_status(chip, valid_status);
		nb_history_pages = MAX1730X_N_OF_HISTORY_PAGES;
	} else {
		max1720x_read_log_write_status(chip, write_status);
		max1720x_read_log_valid_status(chip, valid_status);
		nb_history_pages = MAX1720X_N_OF_HISTORY_PAGES;
	}

	/* Figure out the pages with valid history entry */
	for (i = 0; i < nb_history_pages; i++) {
		addr_offset = i / 8;
		bit_offset = i % 8;
		page_status[i] =
		    ((write_status[addr_offset] & BIT(bit_offset)) ||
		     (write_status[addr_offset] & BIT(bit_offset + 8))) &&
		    ((valid_status[addr_offset] & BIT(bit_offset)) ||
		     (valid_status[addr_offset] & BIT(bit_offset + 8)));
		if (page_status[i])
			valid_history_entry_count++;
	}

	kfree(write_status);
	kfree(valid_status);

	return valid_history_entry_count;
}

static void get_battery_history(struct max1720x_chip *chip,
				bool *page_status, u16 *history)
{
	int i, j, index = 0;
	u16 data = 0;
	const struct max17x0x_reg *hsty;
	u16 command_base = (chip->gauge_type == MAX1730X_GAUGE_TYPE)
		? MAX1730X_READ_HISTORY_CMD_BASE
		: MAX1720X_READ_HISTORY_CMD_BASE;

	hsty = max17x0x_find_by_tag(&chip->regmap_nvram, MAX17X0X_TAG_HSTY);
	if (!hsty)
		return;

	for (i = 0; i < chip->nb_history_pages; i++) {
		if (!page_status[i])
			continue;
		REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
			     command_base + i);
		msleep(MAX1720X_TRECALL_MS);
		for (j = 0; j < chip->history_page_size; j++) {
			(void)REGMAP_READ(&chip->regmap_nvram,
					  (unsigned int)hsty->map[0] + j,
					  &data);
			history[index * chip->history_page_size + j] = data;
		}
		index++;
	}
}

static int format_battery_history_entry(char *temp, int size,
					int page_size, u16 *line)
{
	int length = 0, i;

	for (i = 0; i < page_size; i++) {
		length += scnprintf(temp + length,
			size - length, "%04x ",
			line[i]);
	}

	if (length > 0)
		temp[--length] = 0;
	return length;
}

/* @return number of valid entries */
static int max1720x_history_read(struct max1720x_chip *chip,
				 struct max1720x_history *hi)
{
	memset(hi, 0, sizeof(*hi));

	hi->page_status = kcalloc(chip->nb_history_pages,
				sizeof(bool), GFP_KERNEL);
	if (!hi->page_status)
		return -ENOMEM;


	hi->history_count = get_battery_history_status(chip, hi->page_status);
	if (hi->history_count < 0) {
		goto error_exit;
	} else if (hi->history_count != 0) {
		const int size = hi->history_count * chip->history_page_size;

		hi->page_size = chip->history_page_size;
		hi->history = batt_alloc_array(size, sizeof(u16));
		if (!hi->history) {
			hi->history_count = -ENOMEM;
			goto error_exit;
		}

		get_battery_history(chip, hi->page_status, hi->history);
	}

	return hi->history_count;

error_exit:
	kfree(hi->page_status);
	hi->page_status = NULL;
	return hi->history_count;

}

static void max1720x_history_free(struct max1720x_history *hi)
{
	kfree(hi->page_status);
	kfree(hi->history);

	hi->history = NULL;
	hi->page_status = NULL;
	hi->history_count = -1;
	hi->history_index = 0;
}


/*
 * Removed the following properties:
 *   POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG
 *   POWER_SUPPLY_PROP_TIME_TO_FULL_AVG
 *   POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
 *   POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
 * Need to keep the number of properies under UEVENT_NUM_ENVP (minus # of
 * standard uevent variables).
 */
static enum power_supply_property max1720x_battery_props[] = {
	POWER_SUPPLY_PROP_STATUS,
	POWER_SUPPLY_PROP_HEALTH,
	POWER_SUPPLY_PROP_CAPACITY,		/* replace with _RAW */
	POWER_SUPPLY_PROP_CHARGE_COUNTER,
	POWER_SUPPLY_PROP_CHARGE_FULL,
	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,	/* used from gbattery */
	POWER_SUPPLY_PROP_CURRENT_AVG,		/* candidate for tier switch */
	POWER_SUPPLY_PROP_CURRENT_NOW,
	POWER_SUPPLY_PROP_CYCLE_COUNT,
	POWER_SUPPLY_PROP_PRESENT,
	POWER_SUPPLY_PROP_TEMP,
	POWER_SUPPLY_PROP_VOLTAGE_AVG,
	POWER_SUPPLY_PROP_VOLTAGE_NOW,
	POWER_SUPPLY_PROP_VOLTAGE_OCV,
	POWER_SUPPLY_PROP_TECHNOLOGY,
	POWER_SUPPLY_PROP_SERIAL_NUMBER,
};

/* ------------------------------------------------------------------------- */

static ssize_t max1720x_get_offmode_charger(struct device *dev,
					    struct device_attribute *attr,
					    char *buf)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);

	return scnprintf(buf, PAGE_SIZE, "%hhd\n", chip->offmode_charger);
}

static ssize_t max1720x_set_offmode_charger(struct device *dev,
					    struct device_attribute *attr,
					    const char *buf, size_t count)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);

	if (kstrtobool(buf, &chip->offmode_charger))
		return -EINVAL;

	return count;
}

static DEVICE_ATTR(offmode_charger, 0660,
		   max1720x_get_offmode_charger,
		   max1720x_set_offmode_charger);


static ssize_t max1720x_model_show_state(struct device *dev,
					 struct device_attribute *attr,
					 char *buf)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);
	ssize_t len = 0;

	if (!chip->model_data)
		return -EINVAL;

	mutex_lock(&chip->model_lock);
	len += scnprintf(&buf[len], PAGE_SIZE, "ModelNextUpdate: %d\n",
			 chip->model_next_update);
	len += max_m5_model_state_cstr(&buf[len], PAGE_SIZE - len,
				       chip->model_data);
	mutex_unlock(&chip->model_lock);

	return len;
}

/*
 * force is true when changing the model via debug props.
 * NOTE: call holding model_lock
 */
static int max1720x_model_reload(struct max1720x_chip *chip, bool force)
{
	const bool disabled = chip->model_reload == MAX_M5_LOAD_MODEL_DISABLED;
	const bool pending = chip->model_reload != MAX_M5_LOAD_MODEL_IDLE;
	int version_now, version_load;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return -EINVAL;

	pr_debug("model_reload=%d force=%d pending=%d disabled=%d\n",
		 chip->model_reload, force, pending, disabled);

	if (!force && (pending || disabled))
		return -EEXIST;

	version_now = max_m5_model_read_version(chip->model_data);
	version_load = max_m5_fg_model_version(chip->model_data);

	if (!force && version_now == version_load)
		return -EEXIST;

	/* REQUEST -> IDLE or set to the number of retries */
	dev_info(chip->dev, "Schedule Load FG Model, ID=%d, ver:%d->%d cap_lsb:%d->%d\n",
			chip->batt_id,
			version_now,
			version_load,
			max_m5_model_get_cap_lsb(chip->model_data),
			max_m5_cap_lsb(chip->model_data));

	chip->model_reload = MAX_M5_LOAD_MODEL_REQUEST;
	chip->model_ok = false;
	mod_delayed_work(system_wq, &chip->model_work, 0);

	return 0;
}

static ssize_t max1720x_model_set_state(struct device *dev,
					struct device_attribute *attr,
					const char *buf, size_t count)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);
	int ret;

	if (!chip->model_data)
		return -EINVAL;

	mutex_lock(&chip->model_lock);

	/* read current state from gauge */
	ret = max_m5_model_read_state(chip->model_data);
	if (ret < 0) {
		mutex_unlock(&chip->model_lock);
		return ret;
	}

	/* overwrite with userland, will commit at cycle count */
	ret = max_m5_model_state_sscan(chip->model_data, buf, count);
	if (ret == 0) {
		/* force model state (valid) */
		chip->model_state_valid = true;
		max1720x_model_reload(chip, true);
	}

	mutex_unlock(&chip->model_lock);
	return count;
}




/* resistance and impedance ------------------------------------------------ */

static int max17x0x_read_resistance_avg(struct max1720x_chip *chip)
{
	u16 ravg;
	int ret = 0;

	ret = gbms_storage_read(GBMS_TAG_RAVG, &ravg, sizeof(ravg));
	if (ret < 0)
		return ret;

	return reg_to_resistance_micro_ohms(ravg, chip->RSense);
}

static int max17x0x_read_resistance_raw(struct max1720x_chip *chip)
{
	u16 data;
	int ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_RCELL, &data);
	if (ret < 0)
		return ret;

	return data;
}

static int max17x0x_read_resistance(struct max1720x_chip *chip)
{
	int rslow;

	rslow = max17x0x_read_resistance_raw(chip);
	if (rslow < 0)
		return rslow;

	return reg_to_resistance_micro_ohms(rslow, chip->RSense);
}


/* ----------------------------------------------------------------------- */

static DEVICE_ATTR(m5_model_state, 0640, max1720x_model_show_state,
		   max1720x_model_set_state);

static ssize_t gmsr_show(struct device *dev,
				 struct device_attribute *attr,
				 char *buff)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);
	ssize_t len = 0;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return -EINVAL;

	mutex_lock(&chip->model_lock);
	len = max_m5_gmsr_state_cstr(&buff[len], PAGE_SIZE);
	mutex_unlock(&chip->model_lock);

	return len;
}

static const DEVICE_ATTR_RO(gmsr);

/* Was POWER_SUPPLY_PROP_RESISTANCE_ID */
static ssize_t resistance_id_show(struct device *dev,
				 struct device_attribute *attr,
				 char *buff)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);

	return scnprintf(buff, PAGE_SIZE, "%d\n", chip->batt_id);
}

static const DEVICE_ATTR_RO(resistance_id);

/* Was POWER_SUPPLY_PROP_RESISTANCE */
static ssize_t resistance_show(struct device *dev,
				 struct device_attribute *attr,
				 char *buff)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);

	return scnprintf(buff, PAGE_SIZE, "%d\n", max17x0x_read_resistance(chip));
}

static const DEVICE_ATTR_RO(resistance);

static ssize_t rc_switch_enable_store(struct device *dev, struct device_attribute *attr,
				      const char *buff, size_t count)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);
	bool curr_enable = chip->rc_switch.enable;
	int ret;

	if (kstrtobool(buff, &chip->rc_switch.enable))
		return -EINVAL;

	/* Set back to original INI setting when disable */
	if (curr_enable == true && chip->rc_switch.enable == false) {
		ret = REGMAP_WRITE(&chip->regmap, MAX_M5_LEARNCFG, chip->rc_switch.rc2_learncfg);
		dev_info(chip->dev, "Disable RC switch, recover to learncfg %#x. ret=%d",
			 chip->rc_switch.rc2_learncfg, ret);
	}

	mod_delayed_work(system_wq, &chip->rc_switch.switch_work, 0);

	return count;
}

static ssize_t rc_switch_enable_show(struct device *dev,
				     struct device_attribute *attr, char *buff)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);

	return scnprintf(buff, PAGE_SIZE, "%d\n", chip->rc_switch.enable);
}

static const DEVICE_ATTR_RW(rc_switch_enable);


static ssize_t fg_learning_events_show(struct device *dev,
				       struct device_attribute *attr, char *buf)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);

	return maxfg_show_captured_buffer(&chip->cb_lh, buf, PAGE_SIZE);
}

static ssize_t fg_learning_events_store(struct device *dev,
					      struct device_attribute *attr,
					      const char *buf, size_t count)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);
	int value, ret;

	ret = kstrtoint(buf, 0, &value);
	if (ret < 0)
		return ret;

	if (value == 0)
		maxfg_clear_capture_buf(&chip->cb_lh);

	return count;
}

static DEVICE_ATTR_RW(fg_learning_events);

/* lsb 1/256, race with max1720x_model_work()  */
static int max1720x_get_capacity_raw(struct max1720x_chip *chip, u16 *data)
{
	return REGMAP_READ(&chip->regmap, chip->reg_prop_capacity_raw, data);
}

int max1720x_get_capacity(struct i2c_client *client, int *iic_raw)
{
	struct max1720x_chip *chip;
	u16 temp;
	int ret;

	if (!client || !iic_raw)
		return -EINVAL;

	chip = i2c_get_clientdata(client);
	if (!chip)
		return -ENODEV;

	/* check the rules on reg_prop_capacity_raw */
	ret = max1720x_get_capacity_raw(chip, &temp);
	if (ret == 0)
		*iic_raw = ((int) temp) / 256;

	return ret;
}
EXPORT_SYMBOL_GPL(max1720x_get_capacity);

int max1720x_get_voltage_now(struct i2c_client *client, int *volt)
{
	struct max1720x_chip *chip;
	u16 temp;
	int ret;

	if (!client || !volt)
		return -EINVAL;

	chip = i2c_get_clientdata(client);
	if (!chip)
		return -ENODEV;

	ret = max17x0x_reg_read(&chip->regmap, MAX17X0X_TAG_vcel, &temp);
	if (ret == 0)
		*volt = reg_to_micro_volt(temp);

	return ret;
}
EXPORT_SYMBOL_GPL(max1720x_get_voltage_now);

static int max1720x_get_battery_soc(struct max1720x_chip *chip)
{
	u16 data;
	int capacity, err;

	if (chip->fake_capacity >= 0 && chip->fake_capacity <= 100)
		return chip->fake_capacity;

	err = REGMAP_READ(&chip->regmap, MAX1720X_REPSOC, &data);
	if (err)
		return err;
	capacity = reg_to_percentage(data);

	if (capacity == 100 && chip->offmode_charger)
		chip->fake_capacity = 100;

	return capacity;
}

static int max1720x_get_battery_vfsoc(struct max1720x_chip *chip)
{
	u16 data;
	int capacity, err;


	err = max17x0x_reg_read(&chip->regmap, MAX17X0X_TAG_vfsoc, &data);
	if (err)
		return err;
	capacity = reg_to_percentage(data);

	return capacity;
}

/* TODO: factor with the one in google_bms.c */
static char *psy_status_str[] = {
	"Unknown", "Charging", "Discharging", "NotCharging", "Full"
};

static void max1720x_prime_battery_qh_capacity(struct max1720x_chip *chip,
					       int status)
{
	u16  mcap = 0, data = 0;

	(void)max17x0x_reg_read(&chip->regmap, MAX17X0X_TAG_mcap, &mcap);
	chip->current_capacity = mcap;

	(void)REGMAP_READ(&chip->regmap, MAX1720X_QH, &data);
	chip->previous_qh = reg_to_twos_comp_int(data);

	if (chip->regmap_nvram.regmap) {
		REGMAP_WRITE(&chip->regmap_nvram, MAX17XXX_QHCA, ~mcap);
		dev_dbg(chip->dev, "Capacity primed to %d on %s\n",
			mcap, psy_status_str[status]);

		REGMAP_WRITE(&chip->regmap_nvram, MAX17XXX_QHQH, data);
		dev_dbg(chip->dev, "QH primed to %d on %s\n",
			data, psy_status_str[status]);
	}
}

/* NOTE: the gauge doesn't know if we are current limited to */
static int max1720x_get_battery_status(struct max1720x_chip *chip)
{
	u16 data = 0;
	int current_now, current_avg, ichgterm, vfsoc, soc, fullsocthr;
	int status = POWER_SUPPLY_STATUS_UNKNOWN, err;

	err = max17x0x_reg_read(&chip->regmap, MAX17X0X_TAG_curr, &data);
	if (err)
		return -EIO;
	current_now = -reg_to_micro_amp(data, chip->RSense);

	err = max17x0x_reg_read(&chip->regmap, MAX17X0X_TAG_avgc, &data);
	if (err)
		return -EIO;
	current_avg = -reg_to_micro_amp(data, chip->RSense);

	if (chip->status_charge_threshold_ma) {
		ichgterm = chip->status_charge_threshold_ma * 1000;
	} else {
		err = REGMAP_READ(&chip->regmap, MAX1720X_ICHGTERM, &data);
		if (err)
			return -EIO;
		ichgterm = reg_to_micro_amp(data, chip->RSense);
	}

	err = REGMAP_READ(&chip->regmap, MAX1720X_FULLSOCTHR, &data);
	if (err)
		return -EIO;
	fullsocthr = reg_to_percentage(data);

	soc = max1720x_get_battery_soc(chip);
	if (soc < 0)
		return -EIO;

	vfsoc = max1720x_get_battery_vfsoc(chip);
	if (vfsoc < 0)
		return -EIO;

	if (current_avg > -ichgterm && current_avg <= 0) {

		if (soc >= fullsocthr) {
			const bool needs_prime = (chip->prev_charge_status ==
						  POWER_SUPPLY_STATUS_CHARGING);

			status = POWER_SUPPLY_STATUS_FULL;
			if (needs_prime)
				max1720x_prime_battery_qh_capacity(chip,
								   status);
		} else {
			status = POWER_SUPPLY_STATUS_NOT_CHARGING;
		}

	} else if (current_now >= -ichgterm)  {
		status = POWER_SUPPLY_STATUS_DISCHARGING;
	} else {
		status = POWER_SUPPLY_STATUS_CHARGING;
		if (chip->prev_charge_status == POWER_SUPPLY_STATUS_DISCHARGING
		    && current_avg  < -ichgterm)
			max1720x_prime_battery_qh_capacity(chip, status);
	}

	if (status != chip->prev_charge_status)
		dev_dbg(chip->dev, "s=%d->%d c=%d avg_c=%d ichgt=%d vfsoc=%d soc=%d fullsocthr=%d\n",
				    chip->prev_charge_status,
				    status, current_now, current_avg,
				    ichgterm, vfsoc, soc, fullsocthr);

	chip->prev_charge_status = status;

	return status;
}

static int max1720x_get_battery_health(struct max1720x_chip *chip)
{
	/* For health report what ever was recently alerted and clear it */

	if (chip->health_status & MAX1720X_STATUS_VMX) {
		chip->health_status &= ~MAX1720X_STATUS_VMX;
		return POWER_SUPPLY_HEALTH_OVERVOLTAGE;
	}

	if ((chip->health_status & MAX1720X_STATUS_TMN) &&
	    (chip->RConfig & MAX1720X_CONFIG_TS)) {
		chip->health_status &= ~MAX1720X_STATUS_TMN;
		return POWER_SUPPLY_HEALTH_COLD;
	}

	if ((chip->health_status & MAX1720X_STATUS_TMX) &&
	    (chip->RConfig & MAX1720X_CONFIG_TS)) {
		chip->health_status &= ~MAX1720X_STATUS_TMX;
		return POWER_SUPPLY_HEALTH_HOT;
	}

	return POWER_SUPPLY_HEALTH_GOOD;
}

static int max1720x_update_battery_qh_based_capacity(struct max1720x_chip *chip)
{
	u16 data;
	int current_qh, err = 0;

	if (chip->por)
		return -EINVAL;

	err = REGMAP_READ(&chip->regmap, MAX1720X_QH, &data);
	if (err)
		return err;

	current_qh = reg_to_twos_comp_int(data);

	/* QH value accumulates as battery charges */
	chip->current_capacity -= (chip->previous_qh - current_qh);
	chip->previous_qh = current_qh;

	return 0;
}

static void max1720x_restore_battery_qh_capacity(struct max1720x_chip *chip)
{
	int ret;
	int current_qh, nvram_qh;
	u16 data = 0, nvram_capacity;

	/* not available without shadow */
	if (!chip->regmap_nvram.regmap) {
		max1720x_prime_battery_qh_capacity(chip,
						   POWER_SUPPLY_STATUS_UNKNOWN);
		return;
	}

	/* Capacity data is stored as complement so it will not be zero. Using
	 * zero case to detect new un-primed pack
	 */
	ret = REGMAP_READ(&chip->regmap_nvram, MAX17XXX_QHCA, &data);
	if (!ret && data == 0) {
		max1720x_prime_battery_qh_capacity(chip,
						   POWER_SUPPLY_STATUS_UNKNOWN);
		return;
	}

	nvram_capacity = ~data;

	ret = REGMAP_READ(&chip->regmap_nvram, MAX17XXX_QHQH, &data);
	if (ret) {
		max1720x_prime_battery_qh_capacity(chip,
						   POWER_SUPPLY_STATUS_UNKNOWN);
		return;
	}
	nvram_qh = reg_to_twos_comp_int(data);

	ret = REGMAP_READ(&chip->regmap, MAX1720X_QH, &data);
	if (ret) {
		max1720x_prime_battery_qh_capacity(chip,
						   POWER_SUPPLY_STATUS_UNKNOWN);
		return;
	}
	current_qh = reg_to_twos_comp_int(data);

	/* QH value accumulates as battery discharges */
	chip->current_capacity = (int) nvram_capacity - (nvram_qh - current_qh);
	dev_info(chip->dev, "Capacity restored to %d\n",
		 chip->current_capacity);
	chip->previous_qh = current_qh;
	dev_info(chip->dev, "QH value restored to %d\n",
		 chip->previous_qh);

	/* init chip for max1720x done here, change to RepSOC */
	chip->reg_prop_capacity_raw = MAX1720X_REPSOC;
}

static void max1720x_handle_update_nconvgcfg(struct max1720x_chip *chip,
					     int temp)
{
	int idx = -1;

	if (chip->temp_convgcfg == NULL)
		return;

	if (temp <= chip->temp_convgcfg[0]) {
		idx = 0;
	} else if (temp > chip->temp_convgcfg[chip->nb_convgcfg - 1]) {
		idx = chip->nb_convgcfg - 1;
	} else {
		for (idx = 1 ; idx < chip->nb_convgcfg; idx++) {
			if (temp > chip->temp_convgcfg[idx - 1] &&
			    temp <= chip->temp_convgcfg[idx])
				break;
		}
	}
	mutex_lock(&chip->convgcfg_lock);
	/* We want to switch to higher slot only if above temp + hysteresis
	 * but when temperature drops, we want to change at the level
	 */
	if ((idx != chip->curr_convgcfg_idx) &&
	    (chip->curr_convgcfg_idx == -1 || idx < chip->curr_convgcfg_idx ||
	     temp >= chip->temp_convgcfg[chip->curr_convgcfg_idx] +
	     chip->convgcfg_hysteresis)) {
		struct max17x0x_regmap *regmap;

		if (chip->gauge_type == MAX_M5_GAUGE_TYPE)
			regmap = &chip->regmap;
		else
			regmap = &chip->regmap_nvram;

		REGMAP_WRITE(regmap, MAX1720X_NCONVGCFG, chip->convgcfg_values[idx]);
		chip->curr_convgcfg_idx = idx;
		dev_info(chip->dev, "updating nConvgcfg to 0x%04x as temp is %d (idx:%d)\n",
			 chip->convgcfg_values[idx], temp, idx);
	}
	mutex_unlock(&chip->convgcfg_lock);
}

static void max1720x_handle_update_filtercfg(struct max1720x_chip *chip,
					     int temp)
{
	struct max1720x_dyn_filtercfg *filtercfg = &chip->dyn_filtercfg;
	s16 hysteresis_temp;
	u16 filtercfg_val;

	if (filtercfg->disable_dynamic_filtercfg)
		return;

	if (filtercfg->temp == -1)
		return;

	if (chip->por)
		return;

	mutex_lock(&filtercfg->lock);
	if (temp <= filtercfg->temp)
		filtercfg_val = filtercfg->adjust_val;
	else
		filtercfg_val = filtercfg->default_val;

	hysteresis_temp = filtercfg->temp + filtercfg->hysteresis;
	if ((filtercfg_val != filtercfg->curr_val) &&
	    (filtercfg->curr_val == 0 || temp < filtercfg->temp ||
	     temp >= hysteresis_temp)) {
		REGMAP_WRITE(&chip->regmap, MAX1720X_FILTERCFG, filtercfg_val);
		dev_info(chip->dev, "updating filtercfg to 0x%04x as temp is %d\n",
			 filtercfg_val, temp);
		filtercfg->curr_val = filtercfg_val;
	}
	mutex_unlock(&filtercfg->lock);
}

#define EEPROM_CC_OVERFLOW_BIT	BIT(15)
#define MAXIM_CYCLE_COUNT_RESET 655
static int max1720x_restore_battery_cycle(struct max1720x_chip *chip)
{
	int ret;
	u16 eeprom_cycle, reg_cycle;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return -EINVAL;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_CYCLES, &reg_cycle);
	if (ret < 0) {
		dev_info(chip->dev, "Fail to read reg %#x (%d)", MAX1720X_CYCLES, ret);
		return ret;
	}

	ret = gbms_storage_read(GBMS_TAG_CNHS, &eeprom_cycle, sizeof(eeprom_cycle));
	if (ret < 0) {
		dev_info(chip->dev, "Fail to read eeprom cycle count (%d)", ret);
		return ret;
	}

	if (eeprom_cycle == 0xFFFF) { /* empty storage */
		reg_cycle /= 2;	/* save half value to record over 655 cycles case */
		ret = gbms_storage_write(GBMS_TAG_CNHS, &reg_cycle, sizeof(reg_cycle));
		if (ret < 0)
			dev_info(chip->dev, "Fail to write eeprom cycle (%d)", ret);
		else
			chip->eeprom_cycle = reg_cycle;

		chip->cycle_reg_ok = true;
		return 0;
	}

	if (eeprom_cycle & EEPROM_CC_OVERFLOW_BIT)
		chip->cycle_count_offset = MAXIM_CYCLE_COUNT_RESET;

	chip->eeprom_cycle = eeprom_cycle;
	eeprom_cycle = eeprom_cycle << 1;
	dev_info(chip->dev, "reg_cycle:%d, eeprom_cycle:%d, cycle_count_offset:%d, update:%c",
		 reg_cycle, eeprom_cycle, chip->cycle_count_offset,
		 eeprom_cycle > reg_cycle ? 'Y' : 'N');
	if (eeprom_cycle > reg_cycle) {
		ret = REGMAP_WRITE_VERIFY(&chip->regmap, MAX1720X_CYCLES, eeprom_cycle);
		if (ret < 0) {
			dev_err(chip->dev, "fail to update cycles (%d)", ret);
			return ret;
		}
	}

	chip->cycle_reg_ok = true;
	max1720x_update_cycle_count(chip);

	return 0;
}

static u16 max1720x_save_battery_cycle(const struct max1720x_chip *chip,
				       u16 reg_cycle)
{
	int ret = 0;
	u16 eeprom_cycle = chip->eeprom_cycle;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return eeprom_cycle;

	if (chip->por || reg_cycle == 0)
		return eeprom_cycle;

	/* save half value to record over 655 cycles case */
	reg_cycle /= 2;

	/* Over 655 cycles */
	if (reg_cycle < eeprom_cycle)
		reg_cycle |= EEPROM_CC_OVERFLOW_BIT;

	if (reg_cycle <= eeprom_cycle)
		return eeprom_cycle;

	ret = gbms_storage_write(GBMS_TAG_CNHS, &reg_cycle,
				sizeof(reg_cycle));
	if (ret < 0) {
		dev_info(chip->dev, "Fail to write %d eeprom cycle count (%d)", reg_cycle, ret);
	} else {
		dev_dbg(chip->dev, "update saved cycle:%d -> %d\n", eeprom_cycle, reg_cycle);
		eeprom_cycle = reg_cycle;
	}

	return eeprom_cycle;
}

#define MAX17201_HIST_CYCLE_COUNT_OFFSET	0x4
#define MAX17201_HIST_TIME_OFFSET		0xf

/* WA for cycle count reset.
 * max17201 fuel gauge rolls over the cycle count to 0 and burns
 * an history entry with 0 cycles when the cycle count exceeds
 * 655. This code workaround the issue adding 655 to the cycle
 * count if the fuel gauge history has an entry with 0 cycles and
 * non 0 time-in-field.
 */
static int max1720x_get_cycle_count_offset(struct max1720x_chip *chip)
{
	int offset = 0;
	/*
	 * uses history on devices that have it (max1720x), use EEPROM
	 * in others. it might be written in terms of storage.
	 */
	if (chip->gauge_type == MAX_M5_GAUGE_TYPE) {
		offset = MAXIM_CYCLE_COUNT_RESET;
	} else {
		int i, history_count;
		struct max1720x_history hi;

		if (!chip->history_page_size)
			return 0;

		mutex_lock(&chip->history_lock);
		history_count = max1720x_history_read(chip, &hi);
		if (history_count < 0) {
			mutex_unlock(&chip->history_lock);
			return 0;
		}
		for (i = 0; i < history_count; i++) {
			u16 *entry = &hi.history[i * chip->history_page_size];

			if (entry[MAX17201_HIST_CYCLE_COUNT_OFFSET] == 0 &&
			    entry[MAX17201_HIST_TIME_OFFSET] != 0) {
				offset += MAXIM_CYCLE_COUNT_RESET;
				break;
			}
		}
		mutex_unlock(&chip->history_lock);

		dev_dbg(chip->dev, "history_count=%d page_size=%d i=%d offset=%d\n",
			history_count, chip->history_page_size, i, offset);

		max1720x_history_free(&hi);
	}

	return offset;
}

static int max1720x_get_cycle_count(struct max1720x_chip *chip)
{
	return chip->cycle_count;
}

static int max1720x_update_cycle_count(struct max1720x_chip *chip)
{
	int err, cycle_count;
	u16 reg_cycle;

	/*
	 * Corner case: battery under 3V hit POR without irq.
	 * cycles reset in this situation, incorrect data
	 */
	if (chip->por)
		return -ECANCELED;

	/* if cycle reg hasn't been restored from storage, restore it before update cycle count */
	if (!chip->cycle_reg_ok && chip->gauge_type == MAX_M5_GAUGE_TYPE &&
	    max_m5_recal_state(chip->model_data) == RE_CAL_STATE_IDLE) {
		err = max1720x_restore_battery_cycle(chip);
		if (err < 0)
			dev_err(chip->dev, "%s cannot restore cycle count (%d)\n", __func__, err);

		return err;
	}

	err = REGMAP_READ(&chip->regmap, MAX1720X_CYCLES, &reg_cycle);
	if (err < 0)
		return err;

	if (chip->gauge_type == MAX_M5_GAUGE_TYPE && max_m5_recal_state(chip->model_data))
			reg_cycle += max_m5_recal_cycle(chip->model_data);

	cycle_count = reg_to_cycles((u32)reg_cycle, chip->gauge_type) + chip->cycle_count_offset;
	if (cycle_count < chip->cycle_count) {
		chip->cycle_count_offset = max1720x_get_cycle_count_offset(chip);
		chip->model_next_update = -1;
		dev_info(chip->dev, "cycle count last:%d, now:%d => cycle_count_offset:%d\n",
			 chip->cycle_count, cycle_count, chip->cycle_count_offset);
	}

	chip->eeprom_cycle = max1720x_save_battery_cycle(chip, reg_cycle);

	chip->cycle_count = cycle_count;

	if (chip->model_ok && reg_cycle >= chip->model_next_update) {
		err = max1720x_set_next_update(chip);
		if (err < 0)
			dev_err(chip->dev, "%s cannot set next update (%d)\n", __func__, err);
	}

	return chip->cycle_count;
}

static void max1720x_handle_update_empty_voltage(struct max1720x_chip *chip,
						 int temp)
{
	int cycle, cycle_idx, temp_idx, chg_st, ret = 0;
	u16 empty_volt_cfg, reg, vempty = 0;

	if (chip->empty_voltage == NULL)
		return;

	chg_st = max1720x_get_battery_status(chip);
	if (chg_st < 0)
		return;

	cycle = max1720x_get_cycle_count(chip);
	if (cycle < 0)
		return;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_VEMPTY, &vempty);
	if (ret < 0)
		return;

	cycle_idx = cycle / CYCLE_BUCKET_SIZE;
	if (cycle_idx > (NB_CYCLE_BUCKETS - 1))
		cycle_idx = NB_CYCLE_BUCKETS - 1;

	if (temp < 0) {
		temp_idx = 0;
	} else {
		const int idx = temp / TEMP_BUCKET_SIZE + 1;
		const int temp_buckets = chip->nb_empty_voltage /
					 NB_CYCLE_BUCKETS;

		temp_idx = idx < (temp_buckets - 1) ? idx : (temp_buckets - 1);
	}

	empty_volt_cfg = MAX1720_EMPTY_VOLTAGE(chip, temp_idx, cycle_idx);
	reg = (empty_volt_cfg / 10) << 7 | (vempty & 0x7F);
	if ((reg > vempty) ||
	    (reg < vempty && chg_st != POWER_SUPPLY_STATUS_DISCHARGING)) {
		REGMAP_WRITE(&chip->regmap, MAX1720X_VEMPTY, reg);

		pr_debug("updating empty_voltage to %d(0x%04X), temp:%d(%d), cycle:%d(%d)\n",
				empty_volt_cfg, reg,
				temp, temp_idx,
				cycle, cycle_idx);
	}
}

/* Capacity Estimation functions*/
static int batt_ce_regmap_read(struct max17x0x_regmap *map,
			       const struct max17x0x_reg *bcea,
			       u32 reg, u16 *data)
{
	int err;
	u16 val;

	if (!bcea)
		return -EINVAL;

	err = REGMAP_READ(map, bcea->map[reg], &val);
	if (err)
		return err;

	switch(reg) {
	case CE_DELTA_CC_SUM_REG:
	case CE_DELTA_VFSOC_SUM_REG:
		*data = val;
		break;
	case CE_CAP_FILTER_COUNT:
		val = val & 0x0F00;
		*data = val >> 8;
		break;
	default:
		break;
	}

	return err;
}

static int batt_ce_regmap_write(struct max17x0x_regmap *map,
				const struct max17x0x_reg *bcea,
				u32 reg, u16 data)
{
	int err = -EINVAL;
	u16 val;

	if (!bcea)
		return -EINVAL;

	switch(reg) {
	case CE_DELTA_CC_SUM_REG:
	case CE_DELTA_VFSOC_SUM_REG:
		err = REGMAP_WRITE(map, bcea->map[reg], data);
		break;
	case CE_CAP_FILTER_COUNT:
		err = REGMAP_READ(map, bcea->map[reg], &val);
		if (err)
			return err;
		val = val & 0xF0FF;
		if (data > CE_FILTER_COUNT_MAX)
			val = val | 0x0F00;
		else
			val = val | (data << 8);
		err = REGMAP_WRITE(map, bcea->map[reg], val);
		break;
	default:
		break;
	}

	return err;
}

static void batt_ce_dump_data(const struct gbatt_capacity_estimation *cap_esti,
			      struct logbuffer *log)
{
	logbuffer_log(log, "cap_filter_count: %d"
			    " start_cc: %d"
			    " start_vfsoc: %d"
			    " delta_cc_sum: %d"
			    " delta_vfsoc_sum: %d"
			    " state: %d"
			    " cable: %d",
			    cap_esti->cap_filter_count,
			    cap_esti->start_cc,
			    cap_esti->start_vfsoc,
			    cap_esti->delta_cc_sum,
			    cap_esti->delta_vfsoc_sum,
			    cap_esti->estimate_state,
			    cap_esti->cable_in);
}

static int batt_ce_load_data(struct max17x0x_regmap *map,
			     struct gbatt_capacity_estimation *cap_esti)
{
	u16 data;
	const struct max17x0x_reg *bcea = cap_esti->bcea;

	cap_esti->estimate_state = ESTIMATE_NONE;
	if (batt_ce_regmap_read(map, bcea, CE_DELTA_CC_SUM_REG, &data) == 0)
		cap_esti->delta_cc_sum = data;
	else
		cap_esti->delta_cc_sum = 0;

	if (batt_ce_regmap_read(map, bcea, CE_DELTA_VFSOC_SUM_REG, &data) == 0)
		cap_esti->delta_vfsoc_sum = data;
	else
		cap_esti->delta_vfsoc_sum = 0;

	if (batt_ce_regmap_read(map, bcea, CE_CAP_FILTER_COUNT, &data) == 0)
		cap_esti->cap_filter_count = data;
	else
		cap_esti->cap_filter_count = 0;
	return 0;
}

/* call holding &cap_esti->batt_ce_lock */
static void batt_ce_store_data(struct max17x0x_regmap *map,
			       struct gbatt_capacity_estimation *cap_esti)
{
	if (cap_esti->cap_filter_count <= CE_FILTER_COUNT_MAX) {
		batt_ce_regmap_write(map, cap_esti->bcea,
					  CE_CAP_FILTER_COUNT,
					  cap_esti->cap_filter_count);
	}

	batt_ce_regmap_write(map, cap_esti->bcea,
				  CE_DELTA_VFSOC_SUM_REG,
				  cap_esti->delta_vfsoc_sum);
	batt_ce_regmap_write(map, cap_esti->bcea,
				  CE_DELTA_CC_SUM_REG,
				  cap_esti->delta_cc_sum);
}

/* call holding &cap_esti->batt_ce_lock */
static void batt_ce_stop_estimation(struct gbatt_capacity_estimation *cap_esti,
				   int reason)
{
	cap_esti->estimate_state = reason;
	cap_esti->start_vfsoc = 0;
	cap_esti->start_cc = 0;
}

static int batt_ce_full_estimate(struct gbatt_capacity_estimation *ce)
{
	return (ce->cap_filter_count > 0) && (ce->delta_vfsoc_sum > 0) ?
		ce->delta_cc_sum / ce->delta_vfsoc_sum : -1;
}

/* Measure the deltaCC, deltaVFSOC and CapacityFiltered */
static void batt_ce_capacityfiltered_work(struct work_struct *work)
{
	struct max1720x_chip *chip = container_of(work, struct max1720x_chip,
					    cap_estimate.settle_timer.work);
	struct gbatt_capacity_estimation *cap_esti = &chip->cap_estimate;
	const int lsb = max_m5_cap_lsb(chip->model_data);
	int settle_cc = 0, settle_vfsoc = 0;
	int delta_cc = 0, delta_vfsoc = 0;
	int cc_sum = 0, vfsoc_sum = 0;
	bool valid_estimate = false;
	int rc = 0;
	int data;

	mutex_lock(&cap_esti->batt_ce_lock);

	/* race with disconnect */
	if (!cap_esti->cable_in ||
	    cap_esti->estimate_state != ESTIMATE_PENDING) {
		goto exit;
	}

	rc = max1720x_update_battery_qh_based_capacity(chip);
	if (rc < 0)
		goto ioerr;

	settle_cc = reg_to_micro_amp_h(chip->current_capacity, chip->RSense, lsb);

	data = max1720x_get_battery_vfsoc(chip);
	if (data < 0)
		goto ioerr;

	settle_vfsoc = data;
	settle_cc = settle_cc / 1000;
	delta_cc = settle_cc - cap_esti->start_cc;
	delta_vfsoc = settle_vfsoc - cap_esti->start_vfsoc;

	if ((delta_cc > 0) && (delta_vfsoc > 0)) {

		cc_sum = delta_cc + cap_esti->delta_cc_sum;
		vfsoc_sum = delta_vfsoc + cap_esti->delta_vfsoc_sum;

		if (cap_esti->cap_filter_count >= cap_esti->cap_filt_length) {
			const int filter_divisor = cap_esti->cap_filt_length;

			cc_sum -= cap_esti->delta_cc_sum/filter_divisor;
			vfsoc_sum -= cap_esti->delta_vfsoc_sum/filter_divisor;
		}

		cap_esti->cap_filter_count++;
		cap_esti->delta_cc_sum = cc_sum;
		cap_esti->delta_vfsoc_sum = vfsoc_sum;
		batt_ce_store_data(&chip->regmap_nvram, &chip->cap_estimate);

		valid_estimate = true;
	}

ioerr:
	batt_ce_stop_estimation(cap_esti, ESTIMATE_DONE);

exit:
	logbuffer_log(chip->ce_log,
		"valid=%d settle[cc=%d, vfsoc=%d], delta[cc=%d,vfsoc=%d] ce[%d]=%d",
		valid_estimate,
		settle_cc, settle_vfsoc, delta_cc, delta_vfsoc,
		cap_esti->cap_filter_count,
		batt_ce_full_estimate(cap_esti));

	mutex_unlock(&cap_esti->batt_ce_lock);

	/* force to update uevent to framework side. */
	if (valid_estimate)
		power_supply_changed(chip->psy);
}

/*
 * batt_ce_init(): estimate_state = ESTIMATE_NONE
 * batt_ce_start(): estimate_state = ESTIMATE_NONE -> ESTIMATE_PENDING
 * batt_ce_capacityfiltered_work(): ESTIMATE_PENDING->ESTIMATE_DONE
 */
static int batt_ce_start(struct gbatt_capacity_estimation *cap_esti,
			 int cap_tsettle_ms)
{
	mutex_lock(&cap_esti->batt_ce_lock);

	/* Still has cable and estimate is not pending or cancelled */
	if (!cap_esti->cable_in || cap_esti->estimate_state != ESTIMATE_NONE)
		goto done;

	pr_info("EOC: Start the settle timer\n");
	cap_esti->estimate_state = ESTIMATE_PENDING;
	schedule_delayed_work(&cap_esti->settle_timer,
		msecs_to_jiffies(cap_tsettle_ms));

done:
	mutex_unlock(&cap_esti->batt_ce_lock);
	return 0;
}

static int batt_ce_init(struct gbatt_capacity_estimation *cap_esti,
			struct max1720x_chip *chip)
{
	int rc, vfsoc;
	const int lsb = max_m5_cap_lsb(chip->model_data);

	rc = max1720x_update_battery_qh_based_capacity(chip);
	if (rc < 0)
		return -EIO;

	vfsoc = max1720x_get_battery_vfsoc(chip);
	if (vfsoc < 0)
		return -EIO;

	cap_esti->start_vfsoc = vfsoc;
	cap_esti->start_cc = reg_to_micro_amp_h(chip->current_capacity,
						chip->RSense, lsb) / 1000;
	/* Capacity Estimation starts only when the state is NONE */
	cap_esti->estimate_state = ESTIMATE_NONE;
	return 0;
}

/* ------------------------------------------------------------------------- */

#define SEL_RES_AVG		0
#define SEL_RES_FILTER_COUNT	1
static int batt_res_registers(struct max1720x_chip *chip, bool bread,
			      int isel, u16 *data)
{
	int err = -EINVAL;
	const struct max17x0x_reg *bres;
	u16 res_filtered, res_filt_count, val;

	bres = max17x0x_find_by_tag(&chip->regmap_nvram, MAX17X0X_TAG_BRES);
	if (!bres)
		return err;

	switch (isel) {
	case SEL_RES_AVG:
		if (bread) {
			err = REGMAP_READ(&chip->regmap_nvram, bres->map[0],
					  &res_filtered);
			if (err)
				return err;

			*data = res_filtered;
			return 0;
		}
		err = REGMAP_WRITE(&chip->regmap_nvram, bres->map[0], *data);
		break;
	case SEL_RES_FILTER_COUNT:
		err = REGMAP_READ(&chip->regmap_nvram, bres->map[1], &val);
		if (err)
			return err;

		if (bread) {
			res_filt_count = (val & 0xF000) >> 12;
			*data = res_filt_count;
			return 0;
		}

		res_filt_count = (val & 0x0FFF) | (*data << 12);
		err = REGMAP_WRITE(&chip->regmap_nvram, bres->map[1],
				   res_filt_count);
		break;
	default:
		break;
	}

	return err;
}

static int max1720x_health_write_ai(u16 act_impedance, u16 act_timerh)
{
	int ret;

	ret = gbms_storage_write(GBMS_TAG_ACIM, &act_impedance, sizeof(act_impedance));
	if (ret < 0)
		return -EIO;

	ret = gbms_storage_write(GBMS_TAG_THAS, &act_timerh, sizeof(act_timerh));
	if (ret < 0)
		return -EIO;

	return 0;
}

/* call holding chip->model_lock */
static int max1720x_check_impedance(struct max1720x_chip *chip, u16 *th)
{
	struct max17x0x_regmap *map = &chip->regmap;
	int soc, temp, cycle_count, ret;
	u16 data, timerh;

	if (!chip->model_state_valid)
		return -EAGAIN;

	soc = max1720x_get_battery_soc(chip);
	if (soc < BHI_IMPEDANCE_SOC_LO || soc > BHI_IMPEDANCE_SOC_HI)
		return -EAGAIN;

	ret = max17x0x_reg_read(map, MAX17X0X_TAG_temp, &data);
	if (ret < 0)
		return -EIO;

	temp = reg_to_deci_deg_cel(data);
	if (temp < BHI_IMPEDANCE_TEMP_LO || temp > BHI_IMPEDANCE_TEMP_HI)
		return -EAGAIN;

	cycle_count = max1720x_get_cycle_count(chip);
	if (cycle_count < 0)
		return -EINVAL;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_TIMERH, &timerh);
	if (ret < 0 || timerh == 0)
		return -EINVAL;

	/* wait for a few cyles and time in field before validating the value */
	if (cycle_count < BHI_IMPEDANCE_CYCLE_CNT || timerh < BHI_IMPEDANCE_TIMERH)
		return -ENODATA;

	*th = timerh;
	return 0;
}

/* will return error if the value is not valid  */
static int max1720x_health_get_ai(struct max1720x_chip *chip)
{
	u16 act_impedance, act_timerh;
	int ret;

	if (chip->bhi_acim != 0)
		return chip->bhi_acim;

	/* read both and recalculate for compatibility */
	ret = gbms_storage_read(GBMS_TAG_ACIM, &act_impedance, sizeof(act_impedance));
	if (ret < 0)
		return -EIO;

	ret = gbms_storage_read(GBMS_TAG_THAS, &act_timerh, sizeof(act_timerh));
	if (ret < 0)
		return -EIO;

	/* need to get starting impedance (if qualified) */
	if (act_impedance == 0xffff || act_timerh == 0xffff)
		return -EINVAL;

	/* not zero, not negative */
	chip->bhi_acim = reg_to_resistance_micro_ohms(act_impedance, chip->RSense);;

	/* TODO: corrrect impedance with timerh */

	dev_info(chip->dev, "%s: chip->bhi_acim =%d act_impedance=%x act_timerh=%x\n",
		 __func__, chip->bhi_acim, act_impedance, act_timerh);

	return chip->bhi_acim;
}

/* will return negative if the value is not qualified */
static int max1720x_health_read_impedance(struct max1720x_chip *chip)
{
	u16 timerh;
	int ret;

	ret = max1720x_check_impedance(chip, &timerh);
	if (ret < 0)
		return -EINVAL;

	return max17x0x_read_resistance(chip);
}

/* in hours */
static int max1720x_get_age(struct max1720x_chip *chip)
{
	u16 timerh;
	int ret;

	/* model not ready */
	if (chip->por)
		return -ENODATA;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_TIMERH, &timerh);
	if (ret < 0)
		return -ENODATA;

	return reg_to_time_hr(timerh + chip->timerh_base, chip);
}

#define MAX_HIST_FULLCAP	0x3FF
static int max1720x_get_fade_rate(struct max1720x_chip *chip, int *fade_rate)
{
	struct max17x0x_eeprom_history hist = { 0 };
	int bhi_fcn_count = chip->bhi_fcn_count;
	int ret, ratio, i, fcn_sum = 0;
	u16 hist_idx;

	ret = gbms_storage_read(GBMS_TAG_HCNT, &hist_idx, sizeof(hist_idx));
	if (ret < 0) {
		dev_err(chip->dev, "failed to get history index (%d)\n", ret);
		return -EIO;
	}

	dev_dbg(chip->dev, "%s: hist_idx=%d\n", __func__, hist_idx);

	/* no fade for new battery (less than 30 cycles) */
	if (hist_idx < bhi_fcn_count)
		return 0;

	while (hist_idx >= BATT_MAX_HIST_CNT && bhi_fcn_count > 1) {
		hist_idx--;
		bhi_fcn_count--;
		if (bhi_fcn_count == 1) {
			hist_idx = BATT_MAX_HIST_CNT - 1;
			break;
		}
	}

	for (i = bhi_fcn_count; i ; i--, hist_idx--) {
		ret = gbms_storage_read_data(GBMS_TAG_HIST, &hist,
					     sizeof(hist), hist_idx);

		dev_dbg(chip->dev, "%s: idx=%d hist.fc=%d (%x) ret=%d\n", __func__,
			hist_idx, hist.fullcapnom, hist.fullcapnom, ret);

		if (ret < 0)
			return -EINVAL;

		/* hist.fullcapnom = fullcapnom * 800 / designcap */
		fcn_sum += hist.fullcapnom;
	}

	/* convert from max17x0x_eeprom_history to percent */
	ratio = fcn_sum / (bhi_fcn_count * 8);

	/* allow negative value when capacity larger than design */
	*fade_rate = 100 - ratio;

	return 0;
}

static void max1720x_update_timer_base(struct max1720x_chip *chip)
{
	struct max17x0x_eeprom_history hist = { 0 };
	int ret, i, time_pre, time_now;

	for (i = 0; i < BATT_MAX_HIST_CNT; i++) {
		ret = gbms_storage_read_data(GBMS_TAG_HIST, &hist, sizeof(hist), i);
		if (ret < 0)
			return;

		if (hist.timerh == 0xFF)
			continue;

		/* convert to register value */
		time_now = hist.timerh * 7200 / 192;

		if (time_pre == 0)
			time_pre = time_now;

		if (time_now < time_pre)
			chip->timerh_base += time_pre;

		time_pre = time_now;
	}

	dev_info(chip->dev, "timerh_base: %#X\n", chip->timerh_base);
}

static int max1720x_current_offset_fix(struct max1720x_chip *chip)
{
	u16 cotrim, coff;
	int ret = 0;

	if (chip->current_offset_done || chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX_M5_COTRIM, &cotrim);
	if (ret < 0)
		return ret;

	coff = ((-1) * (s16)cotrim + 1) / 2; /* round up */
	ret = REGMAP_WRITE(&chip->regmap, MAX_M5_COFF, coff);
	if (ret < 0)
		return ret;

	dev_info(chip->dev, "%s: CoTrim:%#x, set COff:%#x\n", __func__, cotrim, coff);

	return ret;
}

static int max1720x_monitor_log_learning(struct max1720x_chip *chip, bool force)
{
	const bool seed = !chip->cb_lh.latest_entry;
	bool log_it;
	char *buf;
	int ret;

	/* do nothing if no changes on dpacc/dqacc or relaxation */
	log_it = force || seed ||
	         maxfg_ce_relaxed(&chip->regmap,  MAX_M5_FSTAT_RELDT | MAX_M5_FSTAT_RELDT2,
				(u16 *)chip->cb_lh.latest_entry);
	if (!log_it)
		return 0;

	ret = maxfg_capture_registers(&chip->cb_lh);
	if (ret < 0) {
		dev_dbg(chip->dev, "cannot read learning parameters (%d)\n", ret);
		return ret;
	}

	/* no need to log at boot */
	if (seed)
		return 0;

	buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;

	ret = maxfg_capture_to_cstr(&chip->cb_lh.config,
				    (u16 *)chip->cb_lh.latest_entry,
				    buf, PAGE_SIZE);
	if (ret > 0)
		gbms_logbuffer_devlog(chip->monitor_log, chip->dev,
				      LOGLEVEL_INFO, 0, LOGLEVEL_INFO,
				      "learn %s", buf);

	kfree(buf);

	return 0;
}

static int max1720x_get_property(struct power_supply *psy,
				 enum power_supply_property psp,
				 union power_supply_propval *val)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)
					power_supply_get_drvdata(psy);
	struct max17x0x_regmap *map = &chip->regmap;
	int rc, err = 0;
	u16 data = 0;
	int idata;

	__pm_stay_awake(chip->get_prop_ws);
	mutex_lock(&chip->model_lock);

	pm_runtime_get_sync(chip->dev);
	if (!chip->init_complete || !chip->resume_complete) {
		pm_runtime_put_sync(chip->dev);
		mutex_unlock(&chip->model_lock);
		__pm_relax(chip->get_prop_ws);
		return -EAGAIN;
	}
	pm_runtime_put_sync(chip->dev);

	switch (psp) {
	case POWER_SUPPLY_PROP_STATUS:
		err = max1720x_get_battery_status(chip);
		if (err < 0)
			break;

		/*
		 * Capacity estimation must run only once.
		 * NOTE: this is a getter with a side effect
		 */
		val->intval = err;
		if (err == POWER_SUPPLY_STATUS_FULL)
			batt_ce_start(&chip->cap_estimate,
				      chip->cap_estimate.cap_tsettle);
		/* check for relaxation event and log it */
		max1720x_monitor_log_learning(chip, false);

		/* return data ok */
		err = 0;
		break;
	case POWER_SUPPLY_PROP_HEALTH:
		val->intval = max1720x_get_battery_health(chip);
		break;
	case GBMS_PROP_CAPACITY_RAW:
		err = max1720x_get_capacity_raw(chip, &data);
		if (err == 0)
			val->intval = (int)data;
		break;
	case POWER_SUPPLY_PROP_CAPACITY:
		idata = max1720x_get_battery_soc(chip);
		if (idata < 0) {
			err = idata;
			break;
		}

		val->intval = idata;
		break;
	case POWER_SUPPLY_PROP_CHARGE_COUNTER:
		err = max1720x_update_battery_qh_based_capacity(chip);
		if (err < 0)
			break;

		val->intval = reg_to_capacity_uah(chip->current_capacity, chip);
		break;
	case POWER_SUPPLY_PROP_CHARGE_FULL:
		/*
		 * Snap charge_full to DESIGNCAP during early charge cycles to
		 * prevent large fluctuations in FULLCAPNOM. MAX1720X_CYCLES LSB
		 * is 16%
		 */
		err = max1720x_get_cycle_count(chip);
		if (err < 0)
			break;

		/* err is cycle_count */
		if (err <= FULLCAPNOM_STABILIZE_CYCLES)
			err = REGMAP_READ(map, MAX1720X_DESIGNCAP, &data);
		else
			err = REGMAP_READ(map, MAX1720X_FULLCAPNOM, &data);

		if (err == 0)
			val->intval = reg_to_capacity_uah(data, chip);
		break;
	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
		err = REGMAP_READ(map, MAX1720X_DESIGNCAP, &data);
		if (err == 0)
			val->intval = reg_to_capacity_uah(data, chip);
		break;
	/* current is positive value when flowing to device */
	case POWER_SUPPLY_PROP_CURRENT_AVG:
		err = max17x0x_reg_read(map, MAX17X0X_TAG_avgc, &data);
		if (err == 0)
			val->intval = -reg_to_micro_amp(data, chip->RSense);
		break;
	/* current is positive value when flowing to device */
	case POWER_SUPPLY_PROP_CURRENT_NOW:
		err = max17x0x_reg_read(map, MAX17X0X_TAG_curr, &data);
		if (err == 0)
			val->intval = -reg_to_micro_amp(data, chip->RSense);
		break;
	case POWER_SUPPLY_PROP_CYCLE_COUNT:
		err = max1720x_get_cycle_count(chip);
		if (err < 0)
			break;
		/* err is cycle_count */
		val->intval = err;
		/* return data ok */
		err = 0;
		break;
	case POWER_SUPPLY_PROP_PRESENT:

		if (chip->fake_battery != -1) {
			val->intval = chip->fake_battery;
		} else if (chip->gauge_type == -1) {
			val->intval = 0;
		} else {

			err = REGMAP_READ(map, MAX1720X_STATUS, &data);
			if (err < 0)
				break;

			/* BST is 0 when the battery is present */
			val->intval = !(data & MAX1720X_STATUS_BST);
			if (!val->intval)
				break;

			/* chip->por prevent garbage in cycle count */
			chip->por = (data & MAX1720X_STATUS_POR) != 0;
			if (chip->por && chip->model_ok &&
			    chip->model_reload != MAX_M5_LOAD_MODEL_REQUEST) {
				/* trigger reload model and clear of POR */
				mutex_unlock(&chip->model_lock);
				__pm_relax(chip->get_prop_ws);
				max1720x_fg_irq_thread_fn(-1, chip);
				return err;
			}
		}
		break;
	case POWER_SUPPLY_PROP_TEMP:
		err = max17x0x_reg_read(map, MAX17X0X_TAG_temp, &data);
		if (err < 0)
			break;

		val->intval = reg_to_deci_deg_cel(data);
		max1720x_handle_update_nconvgcfg(chip, val->intval);
		max1720x_handle_update_filtercfg(chip, val->intval);
		max1720x_handle_update_empty_voltage(chip, val->intval);
		break;
	case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
		err = REGMAP_READ(map, MAX1720X_TTE, &data);
		if (err == 0)
			val->intval = reg_to_seconds(data);
		break;
	case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG:
		err = REGMAP_READ(map, MAX1720X_TTF, &data);
		if (err == 0)
			val->intval = reg_to_seconds(data);
		break;
	case POWER_SUPPLY_PROP_TIME_TO_FULL_NOW:
		val->intval = -1;
		break;
	case POWER_SUPPLY_PROP_VOLTAGE_AVG:
		err = REGMAP_READ(map, MAX1720X_AVGVCELL, &data);
		if (err == 0)
			val->intval = reg_to_micro_volt(data);
		break;
	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
		/* LSB: 20mV */
		err = max17x0x_reg_read(map, MAX17X0X_TAG_mmdv, &data);
		if (err == 0)
			val->intval = ((data >> 8) & 0xFF) * 20000;
		break;
	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
		/* LSB: 20mV */
		err = max17x0x_reg_read(map, MAX17X0X_TAG_mmdv, &data);
		if (err == 0)
			val->intval = (data & 0xFF) * 20000;
		break;
	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
		err = max17x0x_reg_read(map, MAX17X0X_TAG_vcel, &data);
		if (err == 0)
			val->intval = reg_to_micro_volt(data);
		break;
	case POWER_SUPPLY_PROP_VOLTAGE_OCV:
		rc = max17x0x_reg_read(map, MAX17X0X_TAG_vfocv, &data);
		if (rc == -EINVAL) {
			val->intval = -1;
			break;
		}
		val->intval = reg_to_micro_volt(data);
		break;
	case POWER_SUPPLY_PROP_TECHNOLOGY:
		val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
		break;
	case POWER_SUPPLY_PROP_SERIAL_NUMBER:
		val->strval = chip->serial_number;
		break;
	case GBMS_PROP_HEALTH_ACT_IMPEDANCE:
		val->intval = max1720x_health_get_ai(chip);
		break;
	case GBMS_PROP_HEALTH_IMPEDANCE:
		val->intval = max1720x_health_read_impedance(chip);
		break;
	case GBMS_PROP_RESISTANCE:
		val->intval = max17x0x_read_resistance(chip);
		break;
	case GBMS_PROP_RESISTANCE_RAW:
		val->intval = max17x0x_read_resistance_raw(chip);
		break;
	case GBMS_PROP_RESISTANCE_AVG:
		val->intval = max17x0x_read_resistance_avg(chip);
		break;
	case GBMS_PROP_BATTERY_AGE:
		val->intval = max1720x_get_age(chip);
		break;
	case GBMS_PROP_CHARGE_FULL_ESTIMATE:
		val->intval = batt_ce_full_estimate(&chip->cap_estimate);
		break;
	case GBMS_PROP_CAPACITY_FADE_RATE:
		err = max1720x_get_fade_rate(chip, &val->intval);
		break;
	case GBMS_PROP_BATT_ID:
		val->intval = chip->batt_id;
		break;
	case GBMS_PROP_RECAL_FG:
		if (chip->gauge_type == MAX_M5_GAUGE_TYPE)
			val->intval = max_m5_recal_state(chip->model_data);
		break;
	default:
		err = -EINVAL;
		break;
	}

	if (err < 0)
		pr_debug("error %d reading prop %d\n", err, psp);

	mutex_unlock(&chip->model_lock);
	__pm_relax(chip->get_prop_ws);

	return err;
}

/* needs mutex_lock(&chip->model_lock); */
static int max1720x_health_update_ai(struct max1720x_chip *chip, int impedance)
{
	const u16 act_impedance = impedance / 100;
	unsigned int rcell = 0xffff;
	u16 timerh = 0xffff;
	int ret;

	if (impedance) {

		/* mOhms to reg */
		rcell = (impedance * 4096) / (1000 * chip->RSense);
		if (rcell > 0xffff) {
			pr_err("value=%d, rcell=%d out of bounds\n", impedance, rcell);
			return -ERANGE;
		}

		ret = REGMAP_READ(&chip->regmap, MAX1720X_TIMERH, &timerh);
		if (ret < 0 || timerh == 0)
			return -EIO;
	}

	ret = max1720x_health_write_ai(act_impedance, timerh);
	if (ret == 0)
		chip->bhi_acim = 0;

	return ret;
}


static void max1720x_fixup_capacity(struct max1720x_chip *chip, int plugged)
{
	struct max1720x_drift_data *ddata = &chip->drift_data;
	int ret, cycle_count, cap_lsb;
	u16 data16;

	/* do not execute when POR is set */
	ret = REGMAP_READ(&chip->regmap, MAX1720X_STATUS, &data16);
	if (ret < 0 || data16 & MAX1720X_STATUS_POR)
		return;

	/* capacity outliers: fix rcomp0, tempco */
	ret = max1720x_fixup_comp(ddata, &chip->regmap, plugged);
	if (ret > 0) {
		chip->comp_update_count += 1;

		data16 = chip->comp_update_count;
		ret = gbms_storage_write(GBMS_TAG_CMPC, &data16, sizeof(data16));
		if (ret < 0)
			dev_err(chip->dev, "update comp stats (%d)\n", ret);
	}

	cycle_count = max1720x_get_cycle_count(chip);
	if (cycle_count < 0) {
		dev_err(chip->dev, "cannot read cycle_count (%d)\n",
			cycle_count);
		return;
	}

	/* capacity outliers: fix capacity */
	cap_lsb = max_m5_cap_lsb(chip->model_data);
	ret = max1720x_fixup_dxacc(ddata, &chip->regmap, cycle_count, plugged, cap_lsb);
	if (ret > 0) {
		chip->dxacc_update_count += 1;

		data16 = chip->dxacc_update_count;
		ret = gbms_storage_write(GBMS_TAG_DXAC, &data16, sizeof(data16));
		if (ret < 0)
			dev_err(chip->dev, "update cap stats (%d)\n", ret);
	}

}

static int max1720x_set_recalibration(struct max1720x_chip *chip, int cap)
{
	int rc = 0;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE || max_m5_recal_state(chip->model_data))
		return 0;

	if (cap)
		chip->bhi_target_capacity = cap;

	rc = m5_init_custom_parameters(chip->dev, chip->model_data, chip->batt_node ?
				       chip->batt_node : chip->dev->of_node);
	if (rc == 0)
		rc = max_m5_recalibration(chip->model_data, chip->bhi_recalibration_algo,
					  (u16)chip->bhi_target_capacity);
	return rc;
}

static int max1720x_set_property(struct power_supply *psy,
				 enum power_supply_property psp,
				 const union power_supply_propval *val)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)
					power_supply_get_drvdata(psy);
	struct gbatt_capacity_estimation *ce = &chip->cap_estimate;
	int delay_ms = 0;
	int rc = 0;

	mutex_lock(&chip->model_lock);
	pm_runtime_get_sync(chip->dev);
	if (!chip->init_complete || !chip->resume_complete) {
		pm_runtime_put_sync(chip->dev);
		mutex_unlock(&chip->model_lock);
		return -EAGAIN;
	}
	pm_runtime_put_sync(chip->dev);
	mutex_unlock(&chip->model_lock);

	switch (psp) {
	case GBMS_PROP_BATT_CE_CTRL:

		mutex_lock(&ce->batt_ce_lock);

		if (chip->gauge_type == MAX_M5_GAUGE_TYPE &&
		    !chip->model_state_valid) {
			mutex_unlock(&ce->batt_ce_lock);
			return -EAGAIN;
		}

		if (val->intval) {

			if (!ce->cable_in) {
				rc = batt_ce_init(ce, chip);
				ce->cable_in = (rc == 0);
			}

		} else if (ce->cable_in) {
			if (ce->estimate_state == ESTIMATE_PENDING)
				cancel_delayed_work_sync(&ce->settle_timer);

			/* race with batt_ce_capacityfiltered_work() */
			batt_ce_stop_estimation(ce, ESTIMATE_NONE);
			batt_ce_dump_data(ce, chip->ce_log);
			ce->cable_in = false;
		}
		mutex_unlock(&ce->batt_ce_lock);


		/* check cycle count, save state, check drift if needed */
		delay_ms = max1720x_check_drift_delay(&chip->drift_data);
		mod_delayed_work(system_wq, &chip->model_work,
				 msecs_to_jiffies(delay_ms));

		break;
	case GBMS_PROP_HEALTH_ACT_IMPEDANCE:
		mutex_lock(&chip->model_lock);
		rc = max1720x_health_update_ai(chip, val->intval);
		mutex_unlock(&chip->model_lock);
		break;
	case GBMS_PROP_FG_REG_LOGGING:
		max1720x_monitor_log_data(chip, !!val->intval);
		break;
	case GBMS_PROP_RECAL_FG:
		max1720x_set_recalibration(chip, val->intval);
		break;
	default:
		return -EINVAL;
	}

	if (rc < 0)
		return rc;

	return 0;
}

static int max1720x_property_is_writeable(struct power_supply *psy,
					  enum power_supply_property psp)
{
	switch (psp) {
	case GBMS_PROP_BATT_CE_CTRL:
	case GBMS_PROP_HEALTH_ACT_IMPEDANCE:
		return 1;
	default:
		break;
	}

	return 0;
}

static int max1720x_monitor_log_data(struct max1720x_chip *chip, bool force_log)
{
	u16 data, repsoc, vfsoc, avcap, repcap, fullcap, fullcaprep;
	u16 fullcapnom, qh0, qh, dqacc, dpacc, qresidual, fstat, rcomp0, cycles;
	u16 learncfg, tempco, filtercfg, mixcap, vfremcap, vcell, ibat;
	int ret = 0, charge_counter = -1;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_REPSOC, &data);
	if (ret < 0)
		return ret;

	repsoc = (data >> 8) & 0x00FF;
	if (repsoc == chip->pre_repsoc && !force_log)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_VFSOC, &vfsoc);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_AVCAP, &avcap);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_REPCAP, &repcap);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_FULLCAP, &fullcap);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_FULLCAPREP, &fullcaprep);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_FULLCAPNOM, &fullcapnom);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_QH0, &qh0);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_QH, &qh);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_DQACC, &dqacc);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_DPACC, &dpacc);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_QRESIDUAL, &qresidual);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_FSTAT, &fstat);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_LEARNCFG, &learncfg);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_TEMPCO, &tempco);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_FILTERCFG, &filtercfg);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_MIXCAP, &mixcap);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_VFREMCAP, &vfremcap);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_VCELL, &vcell);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_CURRENT, &ibat);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_RCOMP0, &rcomp0);
	if (ret < 0)
		return ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_CYCLES, &cycles);
	if (ret < 0)
		return ret;

	ret = max1720x_update_battery_qh_based_capacity(chip);
	if (ret == 0)
		charge_counter = reg_to_capacity_uah(chip->current_capacity, chip);

	gbms_logbuffer_prlog(chip->monitor_log, LOGLEVEL_INFO, 0, LOGLEVEL_INFO,
			     "%s %02X:%04X %02X:%04X %02X:%04X %02X:%04X %02X:%04X"
			     " %02X:%04X %02X:%04X %02X:%04X %02X:%04X %02X:%04X %02X:%04X"
			     " %02X:%04X %02X:%04X %02X:%04X %02X:%04X %02X:%04X %02X:%04X"
			     " %02X:%04X %02X:%04X %02X:%04X %02X:%04X %02X:%04X CC:%d",
			     chip->max1720x_psy_desc.name, MAX1720X_REPSOC, data, MAX1720X_VFSOC,
			     vfsoc, MAX1720X_AVCAP, avcap, MAX1720X_REPCAP, repcap,
			     MAX1720X_FULLCAP, fullcap, MAX1720X_FULLCAPREP, fullcaprep,
			     MAX1720X_FULLCAPNOM, fullcapnom, MAX1720X_QH0, qh0,
			     MAX1720X_QH, qh, MAX1720X_DQACC, dqacc, MAX1720X_DPACC, dpacc,
			     MAX1720X_QRESIDUAL, qresidual, MAX1720X_FSTAT, fstat,
			     MAX1720X_LEARNCFG, learncfg, MAX1720X_TEMPCO, tempco,
			     MAX1720X_FILTERCFG, filtercfg, MAX1720X_MIXCAP, mixcap,
			     MAX1720X_VFREMCAP, vfremcap, MAX1720X_VCELL, vcell,
			     MAX1720X_CURRENT, ibat, MAX1720X_RCOMP0, rcomp0,
			     MAX1720X_CYCLES, cycles, charge_counter);

	chip->pre_repsoc = repsoc;

	return ret;
}

/*
 * A fuel gauge reset resets only the fuel gauge operation without resetting IC
 * hardware. This is useful for testing different configurations without writing
 * nonvolatile memory.
 * TODO: add a lock around fg_reset to prevent SW from accessing the gauge until
 * the delay for volatile register access (rset->map[2]) expires. Need a lock
 * only if using this after _init()
 */
static int max17x0x_fg_reset(struct max1720x_chip *chip)
{
	const struct max17x0x_reg *rset;
	bool done = false;
	int err;

	rset = max17x0x_find_by_tag(&chip->regmap_nvram, MAX17X0X_TAG_rset);
	if (!rset)
		return -EINVAL;

	dev_info(chip->dev, "FG_RESET addr=%x value=%x delay=%d\n",
			    rset->map16[0], rset->map16[1], rset->map16[2]);

	err = REGMAP_WRITE(&chip->regmap, rset->map16[0], rset->map16[1]);
	if (err < 0) {
		dev_err(chip->dev, "FG_RESET error writing Config2 (%d)\n",
				   err);
	} else {
		int loops = 10; /* 10 * MAX17X0X_TPOR_MS = 1.5 secs */
		u16 cfg2 = 0;

		for ( ; loops ; loops--) {
			msleep(MAX17X0X_TPOR_MS);

			err = REGMAP_READ(&chip->regmap, rset->map16[0], &cfg2);
			done = (err == 0) && !(cfg2 & rset->map16[1]);
			if (done) {
				msleep(rset->map16[2]);
				break;
			}
		}

		if (!done)
			dev_err(chip->dev, "FG_RESET error rst not clearing\n");
		else
			dev_info(chip->dev, "FG_RESET cleared in %dms\n",
				loops * MAX17X0X_TPOR_MS + rset->map16[2]);

	}

	return 0;
}

int max17x0x_sw_reset(struct i2c_client *client)
{
	struct max1720x_chip *chip = i2c_get_clientdata(client);

	if (!chip)
		return -ENODEV;

	return max17x0x_fg_reset(chip);
}
EXPORT_SYMBOL_GPL(max17x0x_sw_reset);

/*
 * A full reset restores the ICs to their power-up state the same as if power
 * had been cycled.
 */
static int max1720x_full_reset(struct max1720x_chip *chip)
{
	if (chip->gauge_type == MAX1730X_GAUGE_TYPE) {
		/*
		 * a full (hw) reset on max1730x cause charge and discharge FET
		 * to toggle and the device will lose power. Will need to
		 * connect the device to a charger to get max1730x firmware to
		 * start and max1730x to close the FETs. Never send a HW reset
		 * to a 1730x while in system...
		 */
		dev_warn(chip->dev, "ignore full reset of fuel gauge\n");
		return 0;
	}

	REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
		     MAX1720X_COMMAND_HARDWARE_RESET);

	msleep(MAX17X0X_TPOR_MS);

	return 0;
}

#define IRQ_STORM_TRIGGER_SECONDS		60
#define IRQ_STORM_TRIGGER_MAX_COUNTS		50
static bool max1720x_fg_irq_storm_check(struct max1720x_chip *chip)
{
	int now_time = 0, interval_time, irq_cnt;
	bool storm = false;
	static int stime;

	chip->icnt++;

	now_time = div_u64(ktime_to_ns(ktime_get_boottime()), NSEC_PER_SEC);
	if (now_time < IRQ_STORM_TRIGGER_SECONDS) {
		stime = now_time;
		chip->icnt = 0;
	}

	interval_time = now_time - stime;
	if (interval_time  > IRQ_STORM_TRIGGER_SECONDS) {
		irq_cnt = chip->icnt * 100;
		irq_cnt /= (interval_time * 100 / IRQ_STORM_TRIGGER_SECONDS);

		storm = irq_cnt > IRQ_STORM_TRIGGER_MAX_COUNTS;
		if (!storm) {
			stime = now_time;
			chip->icnt = 0;
		}
	}

	return storm;
}


static irqreturn_t max1720x_fg_irq_thread_fn(int irq, void *obj)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)obj;
	u16 fg_status, fg_status_clr;
	bool storm = false;
	int err = 0;

	if (!chip || (irq != -1 && irq != chip->primary->irq)) {
		WARN_ON_ONCE(1);
		return IRQ_NONE;
	}

	if (chip->gauge_type == -1)
		return IRQ_NONE;

	pm_runtime_get_sync(chip->dev);
	if (irq != -1 && (!chip->init_complete || !chip->resume_complete)) {
		if (chip->init_complete && !chip->irq_disabled) {
			chip->irq_disabled = true;
			disable_irq_nosync(chip->primary->irq);
		}
		pm_runtime_put_sync(chip->dev);
		return IRQ_HANDLED;
	}

	pm_runtime_put_sync(chip->dev);

	err = REGMAP_READ(&chip->regmap, MAX1720X_STATUS, &fg_status);
	if (err)
		return IRQ_NONE;

	/* disable storm check and spurius with shared interrupts */
	if (!chip->irq_shared) {

		storm = max1720x_fg_irq_storm_check(chip);
		if (storm) {
			u16 fg_alarm = 0;

			if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
				err = REGMAP_READ(&chip->regmap, MAX1720X_ALARM,
						&fg_alarm);

			dev_warn(chip->dev, "sts:%04x, alarm:%04x, cnt:%lu err=%d\n",
				fg_status, fg_alarm, chip->icnt, err);
		}

		if (fg_status == 0) {
			chip->debug_irq_none_cnt++;
			pr_debug("spurius: fg_status=0 cnt=%d\n",
				chip->debug_irq_none_cnt);
			/* rate limit spurius interrupts */
			msleep(MAX1720X_TICLR_MS);
			return IRQ_HANDLED;
		}
	} else if (fg_status == 0) {
		/*
		 * Disable rate limiting for when interrupt is shared.
		 * NOTE: this might need to be re-evaluated at some later point
		 */
		return IRQ_NONE;
	}

	/* only used to report health */
	chip->health_status |= fg_status;

	/*
	 * write 0 to clear will loose interrupts when we don't write 1 to the
	 * bits that are not set. Just inverting fg_status cause an interrupt
	 * storm, only setting the bits marked as "host must clear" in the DS
	 * seems to work eg:
	 *
	 * fg_status_clr = fg_status
	 * fg_status_clr |= MAX1720X_STATUS_POR | MAX1720X_STATUS_DSOCI
	 *                | MAX1720X_STATUS_BI;
	 *
	 * If the above logic is sound, we probably need to set also the bits
	 * that config mark as "host must clear". Maxim to confirm.
	 */
	fg_status_clr = fg_status;

	if (fg_status & MAX1720X_STATUS_POR) {
		const bool no_battery = chip->fake_battery == 0;

		mutex_lock(&chip->model_lock);
		chip->por = true;
		chip->cycle_reg_ok = false;
		if (no_battery) {
			fg_status_clr &= ~MAX1720X_STATUS_POR;
		} else {
			dev_warn(chip->dev, "POR is set(%04x), model reload:%d\n",
				 fg_status, chip->model_reload);
			/*
			 * trigger model load if not on-going, clear POR only when
			 * model loading done successfully
			 */
			if (chip->model_reload != MAX_M5_LOAD_MODEL_REQUEST)
				max1720x_model_reload(chip, false);
		}
		mutex_unlock(&chip->model_lock);
	}

	if (fg_status & MAX1720X_STATUS_IMN)
		pr_debug("IMN is set\n");

	if (fg_status & MAX1720X_STATUS_BST)
		pr_debug("BST is set\n");

	if (fg_status & MAX1720X_STATUS_IMX)
		pr_debug("IMX is set\n");

	if (fg_status & MAX1720X_STATUS_DSOCI) {
		fg_status_clr &= ~MAX1720X_STATUS_DSOCI;
		pr_debug("DSOCI is set\n");
	}
	if (fg_status & MAX1720X_STATUS_VMN) {
		if (chip->RConfig & MAX1720X_CONFIG_VS)
			fg_status_clr &= ~MAX1720X_STATUS_VMN;
		pr_debug("VMN is set\n");
	}
	if (fg_status & MAX1720X_STATUS_TMN) {
		if (chip->RConfig & MAX1720X_CONFIG_TS)
			fg_status_clr &= ~MAX1720X_STATUS_TMN;
		pr_debug("TMN is set\n");
	}
	if (fg_status & MAX1720X_STATUS_SMN) {
		if (chip->RConfig & MAX1720X_CONFIG_SS)
			fg_status_clr &= ~MAX1720X_STATUS_SMN;
		pr_debug("SMN is set\n");
	}
	if (fg_status & MAX1720X_STATUS_BI)
		pr_debug("BI is set\n");

	if (fg_status & MAX1720X_STATUS_VMX) {
		if (chip->RConfig & MAX1720X_CONFIG_VS)
			fg_status_clr &= ~MAX1720X_STATUS_VMX;
		pr_debug("VMX is set\n");
	}
	if (fg_status & MAX1720X_STATUS_TMX) {
		if (chip->RConfig & MAX1720X_CONFIG_TS)
			fg_status_clr &= ~MAX1720X_STATUS_TMX;
		pr_debug("TMX is set\n");
	}
	if (fg_status & MAX1720X_STATUS_SMX) {
		if (chip->RConfig & MAX1720X_CONFIG_SS)
			fg_status_clr &= ~MAX1720X_STATUS_SMX;
		pr_debug("SMX is set\n");
	}

	if (fg_status & MAX1720X_STATUS_BR)
		pr_debug("BR is set\n");

	/* NOTE: should always clear everything even if we lose state */
	REGMAP_WRITE(&chip->regmap, MAX1720X_STATUS, fg_status_clr);

	/* SOC interrupts need to go through all the time */
	if (fg_status & MAX1720X_STATUS_DSOCI) {
		const bool plugged = chip->cap_estimate.cable_in;

		if (max1720x_check_drift_on_soc(&chip->drift_data))
			max1720x_fixup_capacity(chip, plugged);

		if (storm) {
			pr_debug("Force power_supply_change in storm\n");
		} else {
			max1720x_monitor_log_learning(chip, false);
			max1720x_monitor_log_data(chip, false);
			if (chip->gauge_type == MAX_M5_GAUGE_TYPE)
				max_m5_check_recal_state(chip->model_data,
							 chip->bhi_recalibration_algo,
							 chip->eeprom_cycle);
			max1720x_update_cycle_count(chip);
		}

		storm = false;
	}

	if (chip->psy && !storm)
		power_supply_changed(chip->psy);

	/*
	 * oneshot w/o filter will unmask on return but gauge will take up
	 * to 351 ms to clear ALRM1.
	 * NOTE: can do this masking on gauge side (Config, 0x1D) and using a
	 * workthread to re-enable.
	 */
	if (irq != -1)
		msleep(MAX1720X_TICLR_MS);


	return IRQ_HANDLED;
}

/* used to find batt_node and chemistry dependent FG overrides */
static int max1720x_read_batt_id(int *batt_id, const struct max1720x_chip *chip)
{
	bool defer;
	int rc = 0;
	struct device_node *node = chip->dev->of_node;
	u32 temp_id = 0;

	/* force the value in kohm */
	rc = of_property_read_u32(node, "maxim,force-batt-id", &temp_id);
	if (rc == 0) {
		dev_warn(chip->dev, "forcing battery RID %d\n", temp_id);
		*batt_id = temp_id;
		return 0;
	}

	/* return the value in kohm */
	rc = gbms_storage_read(GBMS_TAG_BRID, &temp_id, sizeof(temp_id));
	defer = (rc == -EPROBE_DEFER) ||
		(rc == -EINVAL) ||
		((rc == 0) && (temp_id == -EINVAL));
	if (defer)
		return -EPROBE_DEFER;

	if (rc < 0) {
		dev_err(chip->dev, "failed to get batt-id rc=%d\n", rc);
		*batt_id = -1;
		return -EPROBE_DEFER;
	}

	*batt_id = temp_id;
	return 0;
}

/*  */
static struct device_node *max1720x_find_batt_node(struct max1720x_chip *chip)
{
	const int batt_id = chip->batt_id;
	const struct device *dev = chip->dev;
	struct device_node *config_node, *child_node;
	u32 batt_id_range = 20, batt_id_kohm;
	int ret;

	config_node = of_find_node_by_name(dev->of_node, "maxim,config");
	if (!config_node) {
		dev_warn(dev, "Failed to find maxim,config setting\n");
		return NULL;
	}

	ret = of_property_read_u32(dev->of_node, "maxim,batt-id-range-pct",
				   &batt_id_range);
	if (ret && ret == -EINVAL)
		dev_warn(dev, "failed to read maxim,batt-id-range-pct\n");

	for_each_child_of_node(config_node, child_node) {
		ret = of_property_read_u32(child_node, "maxim,batt-id-kohm",
					   &batt_id_kohm);
		if (ret != 0)
			continue;

		/* only look for matching algo_ver if set */
		if (chip->drift_data.algo_ver != MAX1720X_DA_VER_NONE) {
			u32 algo_ver;

			ret = of_property_read_u32(child_node,
						   "maxim,algo-version",
						   &algo_ver);
			if (ret == 0 && chip->drift_data.algo_ver != algo_ver)
				continue;
		}

		if (!batt_id_range && batt_id == batt_id_kohm)
			return child_node;
		if ((batt_id < (batt_id_kohm * (100 + batt_id_range) / 100)) &&
		    (batt_id > (batt_id_kohm * (100 - batt_id_range) / 100)))
			return child_node;
	}

	return NULL;
}

static int max17x0x_apply_regval_shadow(struct max1720x_chip *chip,
					struct device_node *node,
					struct max17x0x_cache_data *nRAM,
					int nb)
{
	u16 *regs;
	int ret, i;
	const char *propname = (chip->gauge_type == MAX1730X_GAUGE_TYPE) ?
		 "maxim,n_regval_1730x" : "maxim,n_regval_1720x";

	if (!node || nb <= 0)
		return 0;

	if (nb & 1) {
		dev_warn(chip->dev, "%s %s u16 elems count is not even: %d\n",
			 node->name, propname, nb);
		return -EINVAL;
	}

	regs = batt_alloc_array(nb, sizeof(u16));
	if (!regs)
		return -ENOMEM;

	ret = of_property_read_u16_array(node, propname, regs, nb);
	if (ret) {
		dev_warn(chip->dev, "failed to read %s: %d\n", propname, ret);
		goto shadow_out;
	}

	for (i = 0; i < nb; i += 2) {
		const int idx = max17x0x_cache_index_of(nRAM, regs[i]);
		nRAM->cache_data[idx] = regs[i + 1];
	}

shadow_out:
	kfree(regs);
	return ret;
}

/* support for initial batch of ill configured max1720x packs */
static void max1720x_consistency_check(struct max17x0x_cache_data *cache)
{
	int nvcfg_idx = max17x0x_cache_index_of(cache, MAX1720X_NNVCFG0);
	int ncgain_idx = max17x0x_cache_index_of(cache, MAX1720X_NCGAIN);
	u16 *nRAM_updated = cache->cache_data;

	if ((nRAM_updated[nvcfg_idx] & MAX1720X_NNVCFG0_ENCG) &&
		((nRAM_updated[ncgain_idx] == 0) ||
		(nRAM_updated[ncgain_idx] == 0x0400)))
		nRAM_updated[ncgain_idx] = 0x4000;
}

static int max17x0x_read_dt_version(struct device_node *node,
				    int gauge_type, u8 *reg, u8 *val)
{
	int ret;
	const char *propname;
	u8 version[2];

	if (gauge_type == MAX1730X_GAUGE_TYPE) {
		propname = "maxim,n_regval_1730x_ver";
	} else if (gauge_type == MAX1720X_GAUGE_TYPE) {
		propname = "maxim,n_regval_1720x_ver";
	} else {
		return -ENOTSUPP;
	}

	ret = of_property_read_u8_array(node, propname,
					version,
					sizeof(version));
	if (ret < 0)
		return -ENODATA;

	*reg = version[0];
	*val = version[1];

	return 0;
}

static int max17x0x_read_dt_version_por(struct device_node *node,
					int gauge_type, u8 *reg, u8 *val)
{
	int ret;
	const char *propname;
	u8 version[2];

	if (gauge_type == MAX1730X_GAUGE_TYPE) {
		propname = "maxim,n_regval_1730x_ver_por";
	} else if (gauge_type == MAX1720X_GAUGE_TYPE) {
		propname = "maxim,n_regval_1720x_ver_por";
	} else {
		return -ENOTSUPP;
	}

	ret = of_property_read_u8_array(node, propname,
					version,
					sizeof(version));
	if (ret < 0)
		return -ENODATA;

	*reg = version[0];
	*val = version[1];

	return 0;
}

static int max17x0x_handle_dt_shadow_config(struct max1720x_chip *chip)
{
	int ret, rc, glob_cnt;
	const char *propname = NULL;
	struct max17x0x_cache_data nRAM_c;
	struct max17x0x_cache_data nRAM_u;
	int ver_idx = -1;
	u8 vreg, vval;

	/* for devices that don't support max1720x_fg_reset() */
	if (!chip->shadow_override || chip->gauge_type == -1)
		return 0;

	if (chip->gauge_type == MAX1730X_GAUGE_TYPE)
		propname = "maxim,n_regval_1730x";
	else
		propname = "maxim,n_regval_1720x";

	ret = max17x0x_nvram_cache_init(&nRAM_c, chip->gauge_type);
	if (ret < 0)
		return ret;

	ret = max17x0x_cache_load(&nRAM_c, &chip->regmap_nvram);
	if (ret < 0) {
		dev_err(chip->dev, "Failed to read config from shadow RAM\n");
		goto error_out;
	}

	ret = max17x0x_cache_dup(&nRAM_u, &nRAM_c);
	if (ret < 0)
		goto error_out;

	/* apply overrides */
	if (chip->batt_node) {
		int batt_cnt;

		batt_cnt = of_property_count_elems_of_size(chip->batt_node,
							   propname,
							   sizeof(u16));
		max17x0x_apply_regval_shadow(chip, chip->batt_node,
					     &nRAM_u,
					     batt_cnt);
	}

	glob_cnt = of_property_count_elems_of_size(chip->dev->of_node,
						   propname,
						   sizeof(u16));
	max17x0x_apply_regval_shadow(chip, chip->dev->of_node,
				     &nRAM_u,
				     glob_cnt);

	if (chip->gauge_type == MAX1720X_GAUGE_TYPE)
		max1720x_consistency_check(&nRAM_u);

	rc = max17x0x_read_dt_version(chip->dev->of_node,
				      chip->gauge_type, &vreg, &vval);
	if (rc == 0) {
		/*
		 * Versioning enforced: reset the gauge (and overwrite
		 * version) only if the version in device tree is
		 * greater than the version in the gauge.
		 */
		ver_idx = max17x0x_cache_index_of(&nRAM_u, vreg);
		if (ver_idx < 0) {
			dev_err(chip->dev, "version register %x is not mapped\n",
					vreg);
		} else if ((nRAM_u.cache_data[ver_idx] & 0xff) < vval) {
			/*
			 * force version in dt, will write (and reset fg)
			 * only when less than the version in nRAM_c
			 */
			dev_info(chip->dev,
				"DT version updated %d -> %d\n",
				nRAM_u.cache_data[ver_idx] & 0xff,
				vval);

			nRAM_u.cache_data[ver_idx] &= 0xff00;
			nRAM_u.cache_data[ver_idx] |= vval;
			chip->needs_reset = true;
		}
	}

	if (max17x0x_cache_memcmp(&nRAM_c, &nRAM_u)) {
		bool fg_reset = false;

		if (ver_idx < 0) {
			/*
			 * Versioning not enforced: nConvgCfg take effect
			 * without resetting the gauge
			 */
			const int idx = max17x0x_cache_index_of(&nRAM_u,
							MAX1720X_NCONVGCFG);
			nRAM_c.cache_data[idx] = nRAM_u.cache_data[idx];
			fg_reset = max17x0x_cache_memcmp(&nRAM_u, &nRAM_c) != 0;
		}

		ret = max17x0x_cache_store(&nRAM_u, &chip->regmap_nvram);
		if (ret < 0) {
			dev_err(chip->dev,
				"Failed to write config from shadow RAM\n");
			goto error_out;
		}

		/* different reason for reset */
		if (fg_reset) {
			chip->needs_reset = true;
			dev_info(chip->dev,
				"DT config differs from shadow, resetting\n");
		}
	}

error_out:
	max17x0x_cache_free(&nRAM_c);
	max17x0x_cache_free(&nRAM_u);

	return ret;
}

static int max17x0x_apply_regval_register(struct max1720x_chip *chip,
					struct device_node *node)
{
	int cnt, ret = 0, idx, err;
	u16 *regs, data;
	const char *propname;

	propname = (chip->gauge_type == MAX1730X_GAUGE_TYPE) ?
		 "maxim,r_regval_1730x" : "maxim,r_regval_1720x";

	cnt =  of_property_count_elems_of_size(node, propname, sizeof(u16));
	if (!node || cnt <= 0)
		return 0;

	if (cnt & 1) {
		dev_warn(chip->dev, "%s %s u16 elems count is not even: %d\n",
			 node->name, propname, cnt);
		return -EINVAL;
	}

	regs = batt_alloc_array(cnt, sizeof(u16));
	if (!regs)
		return -ENOMEM;

	ret = of_property_read_u16_array(node, propname, regs, cnt);
	if (ret) {
		dev_warn(chip->dev, "failed to read %s %s: %d\n",
			 node->name, propname, ret);
		goto register_out;
	}

	for (idx = 0; idx < cnt; idx += 2) {
		if (max1720x_is_reg(chip->dev, regs[idx])) {
			err = REGMAP_READ(&chip->regmap, regs[idx], &data);
			if (!err && data != regs[idx + 1])
				REGMAP_WRITE(&chip->regmap, regs[idx],
					     regs[idx + 1]);
		}
	}
register_out:
	kfree(regs);
	return ret;
}

static int max17x0x_handle_dt_register_config(struct max1720x_chip *chip)
{
	int ret = 0;

	if (chip->batt_node)
		ret = max17x0x_apply_regval_register(chip, chip->batt_node);

	if (ret)
		return ret;

	ret = max17x0x_apply_regval_register(chip, chip->dev->of_node);

	return ret;
}

static int max1720x_handle_dt_nconvgcfg(struct max1720x_chip *chip)
{
	int ret = 0, i;
	struct device_node *node = chip->dev->of_node;

	chip->curr_convgcfg_idx = -1;
	mutex_init(&chip->convgcfg_lock);

	ret = of_property_read_u32(node, "google,cap-tsettle",
				   (u32 *)&chip->cap_estimate.cap_tsettle);
	if (ret < 0)
		chip->cap_estimate.cap_tsettle = DEFAULT_CAP_SETTLE_INTERVAL;
	chip->cap_estimate.cap_tsettle =
				chip->cap_estimate.cap_tsettle * 60 * 1000;

	ret = of_property_read_u32(node, "google,cap-filt-length",
				   (u32 *)&chip->cap_estimate.cap_filt_length);
	if (ret < 0)
		chip->cap_estimate.cap_filt_length = DEFAULT_CAP_FILTER_LENGTH;

	chip->nb_convgcfg =
	    of_property_count_elems_of_size(node, "maxim,nconvgcfg-temp-limits",
					    sizeof(s16));
	if (!chip->nb_convgcfg)
		return 0;

	ret = of_property_read_s32(node, "maxim,nconvgcfg-temp-hysteresis",
				   &chip->convgcfg_hysteresis);
	if (ret < 0)
		chip->convgcfg_hysteresis = 10;
	else if (chip->convgcfg_hysteresis < 0)
			chip->convgcfg_hysteresis = 10;
	if (ret == 0)
		dev_info(chip->dev, "%s maxim,nconvgcfg-temp-hysteresis = %d\n",
			 node->name, chip->convgcfg_hysteresis);

	if (chip->nb_convgcfg != of_property_count_elems_of_size(node,
						  "maxim,nconvgcfg-values",
						  sizeof(u16))) {
		dev_warn(chip->dev, "%s maxim,nconvgcfg-values and maxim,nconvgcfg-temp-limits are missmatching number of elements\n",
			 node->name);
		return -EINVAL;
	}
	chip->temp_convgcfg = (s16 *)devm_kmalloc_array(chip->dev,
							chip->nb_convgcfg,
							sizeof(s16),
								GFP_KERNEL);
	if (!chip->temp_convgcfg)
		return -ENOMEM;

	chip->convgcfg_values = (u16 *)devm_kmalloc_array(chip->dev,
							  chip->nb_convgcfg,
							  sizeof(u16),
							  GFP_KERNEL);
	if (!chip->convgcfg_values) {
		devm_kfree(chip->dev, chip->temp_convgcfg);
		chip->temp_convgcfg = NULL;
		return -ENOMEM;
	}

	ret = of_property_read_u16_array(node, "maxim,nconvgcfg-temp-limits",
					 (u16 *) chip->temp_convgcfg,
					 chip->nb_convgcfg);
	if (ret) {
		dev_warn(chip->dev, "failed to read maxim,nconvgcfg-temp-limits: %d\n",
			 ret);
		goto error;
	}

	ret = of_property_read_u16_array(node, "maxim,nconvgcfg-values",
					 chip->convgcfg_values,
					 chip->nb_convgcfg);
	if (ret) {
		dev_warn(chip->dev, "failed to read maxim,nconvgcfg-values: %d\n",
			 ret);
		goto error;
	}
	for (i = 1; i < chip->nb_convgcfg; i++) {
		if (chip->temp_convgcfg[i] < chip->temp_convgcfg[i-1]) {
			dev_warn(chip->dev, "nconvgcfg-temp-limits idx:%d < idx:%d\n",
				 i, i-1);
			goto error;
		}
		if ((chip->temp_convgcfg[i] - chip->temp_convgcfg[i-1])
		    <= chip->convgcfg_hysteresis) {
			dev_warn(chip->dev, "nconvgcfg-temp-hysteresis smaller than idx:%d, idx:%d\n",
				 i, i-1);
			goto error;
		}
	}

	chip->nb_empty_voltage = of_property_count_elems_of_size(node,
								 "maxim,empty-voltage",
								 sizeof(u16));
	if (chip->nb_empty_voltage > 0 &&
	    chip->nb_empty_voltage % NB_CYCLE_BUCKETS == 0) {
		chip->empty_voltage = (u16 *)devm_kmalloc_array(chip->dev,
							chip->nb_empty_voltage,
							sizeof(u16),
							GFP_KERNEL);
		if (!chip->empty_voltage)
			goto error;

		ret = of_property_read_u16_array(node, "maxim,empty-voltage",
						chip->empty_voltage,
						chip->nb_empty_voltage);
		if (ret) {
			dev_warn(chip->dev,
				 "failed to read maxim,empty-voltage: %d\n",
				 ret);
		}
	} else
		dev_warn(chip->dev,
			 "maxim,empty-voltage is missmatching the number of elements, nb = %d\n",
			 chip->nb_empty_voltage);
error:
	if (ret) {
		devm_kfree(chip->dev, chip->temp_convgcfg);
		devm_kfree(chip->dev, chip->convgcfg_values);
		chip->temp_convgcfg = NULL;
	}

	return ret;
}

static int max1720x_handle_dt_filtercfg(struct max1720x_chip *chip)
{
	struct device_node *node = chip->dev->of_node;
	struct max1720x_dyn_filtercfg *filtercfg = &chip->dyn_filtercfg;
	int ret = 0;

	mutex_init(&filtercfg->lock);

	ret = of_property_read_s32(node, "maxim,filtercfg-temp",
				   &filtercfg->temp);
	if (ret)
		goto not_enable;

	ret = of_property_read_s32(node, "maxim,filtercfg-temp-hysteresis",
				   &filtercfg->hysteresis);
	if (ret)
		filtercfg->hysteresis = FILTERCFG_TEMP_HYSTERESIS;

	ret = of_property_read_u16(node, "maxim,filtercfg-default",
				   &filtercfg->default_val);
	if (ret)
		goto not_enable;

	ret = of_property_read_u16(node, "maxim,filtercfg-adjust",
				   &filtercfg->adjust_val);
	if (ret)
		goto not_enable;

	dev_info(chip->dev, "%s filtercfg: temp:%d(hys:%d), default:%#X adjust:%#X\n",
		 node->name, filtercfg->temp, filtercfg->hysteresis,
		 filtercfg->default_val, filtercfg->adjust_val);

	return ret;

not_enable:
	filtercfg->temp = -1;
	return ret;
}

static int get_irq_none_cnt(void *data, u64 *val)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)data;

	*val = chip->debug_irq_none_cnt;
	return 0;
}

static int set_irq_none_cnt(void *data, u64 val)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)data;

	if (val == 0)
		chip->debug_irq_none_cnt = 0;
	return 0;
}

DEFINE_SIMPLE_ATTRIBUTE(irq_none_cnt_fops, get_irq_none_cnt,
	set_irq_none_cnt, "%llu\n");


static int debug_fg_reset(void *data, u64 val)
{
	struct max1720x_chip *chip = data;
	int ret;

	if (val == 0)
		ret = max17x0x_fg_reset(chip);
	else if (val == 1)
		ret = max1720x_full_reset(chip);
	else
		ret = -EINVAL;

	return ret;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_fg_reset_fops, NULL, debug_fg_reset, "%llu\n");

static int debug_ce_start(void *data, u64 val)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)data;

	batt_ce_start(&chip->cap_estimate, val);
	return 0;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_ce_start_fops, NULL, debug_ce_start, "%llu\n");

/* Model reload will be disabled if the node is not found */
static int max1720x_init_model(struct max1720x_chip *chip)
{
	const bool no_battery = chip->fake_battery == 0;
	void *model_data;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return 0;

	if (no_battery)
		return 0;

	/* ->batt_id negative for no lookup */
	if (chip->batt_id >= 0) {
		chip->batt_node = max1720x_find_batt_node(chip);
		pr_debug("node found=%d for ID=%d algo=%d\n",
			 !!chip->batt_node, chip->batt_id,
			 chip->drift_data.algo_ver);
	}

	/* reset state (if needed) */
	if (chip->model_data) {
		devm_kfree(chip->dev, chip->model_data);
		chip->model_data = NULL;
	}

	/* TODO: split allocation and initialization */
	model_data = max_m5_init_data(chip->dev, chip->batt_node ?
				      chip->batt_node : chip->dev->of_node,
				      &chip->regmap);
	if (IS_ERR(model_data))
		return PTR_ERR(model_data);

	chip->model_data = model_data;

	if (!chip->batt_node) {
		dev_warn(chip->dev, "No child node for ID=%d, algo=%d\n",
			 chip->batt_id, chip->drift_data.algo_ver);
		chip->model_reload = MAX_M5_LOAD_MODEL_DISABLED;
	} else {
		u32 data32;
		int rc;

		/* align algo_ver for capacity drift to model */
		rc = of_property_read_u32(chip->batt_node, "maxim,algo-version",
					  &data32);
		if (rc == 0)
			chip->drift_data.algo_ver = data32;

		pr_debug("model_data ok for ID=%d, algo=%d\n",
			 chip->batt_id, chip->drift_data.algo_ver);
		chip->model_reload = MAX_M5_LOAD_MODEL_IDLE;
		chip->designcap = max_m5_get_designcap(chip->model_data);
	}

	return 0;
}

/* change battery_id and cause reload of the FG model */
static int debug_batt_id_set(void *data, u64 val)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)data;
	int ret;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return -EINVAL;

	mutex_lock(&chip->model_lock);

	chip->batt_id = val;

	/* re-init the model data (lookup in DT) */
	ret = max1720x_init_model(chip);
	if (ret == 0) {
		/* lookup tempco and learncfg in DT */
		max17201_init_rc_switch(chip);
		max1720x_model_reload(chip, true);
	}

	mutex_unlock(&chip->model_lock);

	dev_info(chip->dev, "Force model for batt_id=%llu (%d)\n", val, ret);
	return 0;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_batt_id_fops, NULL, debug_batt_id_set, "%llu\n");

/*
 * dump with "cat /d/max1720x/nvram_por | xxd"
 * NOTE: for testing add a setter that initialize chip->nRAM_por (if not
 * initialized) and use _load() to read NVRAM.
 */
static ssize_t debug_get_nvram_por(struct file *filp,
				   char __user *buf,
				   size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	int size;

	if (!chip || !chip->nRAM_por.cache_data)
		return -ENODATA;

	size = chip->nRAM_por.atom.size > count ?
			count : chip->nRAM_por.atom.size;

	return simple_read_from_buffer(buf, count, ppos,
		chip->nRAM_por.cache_data,
		size);
}

BATTERY_DEBUG_ATTRIBUTE(debug_nvram_por_fops, debug_get_nvram_por, NULL);

static int debug_fake_battery_set(void *data, u64 val)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)data;

	chip->fake_battery = (int)val;
	return 0;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_fake_battery_fops, NULL,
			debug_fake_battery_set, "%llu\n");


static int max1720x_log_learn_set(void *data, u64 val)
{
	struct max1720x_chip *chip = data;

       max1720x_monitor_log_learning(chip, true);
       return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(debug_log_learn_fops, NULL, max1720x_log_learn_set, "%llu\n");


static void max17x0x_reglog_dump(struct max17x0x_reglog *regs,
				 size_t size,
				 char *buff)
{
	int i, len = 0;

	for (i = 0; i < NB_REGMAP_MAX; i++) {
		if (size <= len)
			break;
		if (test_bit(i, regs->valid))
			len += scnprintf(&buff[len], size - len, "%02X:%04X\n",
					 i, regs->data[i]);
	}

	if (len == 0)
		scnprintf(buff, size, "No record\n");
}

static ssize_t debug_get_reglog_writes(struct file *filp,
				       char __user *buf,
				       size_t count, loff_t *ppos)
{
	char *buff;
	ssize_t rc = 0;
	struct max17x0x_reglog *reglog =
				(struct max17x0x_reglog *)filp->private_data;

	buff = kmalloc(count, GFP_KERNEL);
	if (!buff)
		return -ENOMEM;

	max17x0x_reglog_dump(reglog, count, buff);
	rc = simple_read_from_buffer(buf, count, ppos, buff, strlen(buff));

	kfree(buff);

	return rc;
}

BATTERY_DEBUG_ATTRIBUTE(debug_reglog_writes_fops,
			debug_get_reglog_writes, NULL);

static ssize_t max1720x_show_custom_model(struct file *filp, char __user *buf,
					  size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	char *tmp;
	int len;

	if (!chip->model_data)
		return -EINVAL;

	tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!tmp)
		return -ENOMEM;

	mutex_lock(&chip->model_lock);
	len = max_m5_fg_model_cstr(tmp, PAGE_SIZE, chip->model_data);
	mutex_unlock(&chip->model_lock);

	if (len > 0)
		len = simple_read_from_buffer(buf, count,  ppos, tmp, len);

	kfree(tmp);

	return len;
}

static ssize_t max1720x_set_custom_model(struct file *filp,
					 const char __user *user_buf,
					 size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	char *tmp;
	int ret;

	if (!chip->model_data)
		return -EINVAL;

	tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!tmp)
		return -ENOMEM;

	ret = simple_write_to_buffer(tmp, PAGE_SIZE, ppos, user_buf, count);
	if (!ret) {
		kfree(tmp);
		return -EFAULT;
	}

	mutex_lock(&chip->model_lock);
	ret = max_m5_fg_model_sscan(chip->model_data, tmp, count);
	if (ret < 0)
		count = ret;
	mutex_unlock(&chip->model_lock);

	kfree(tmp);

	return count;
}

BATTERY_DEBUG_ATTRIBUTE(debug_m5_custom_model_fops, max1720x_show_custom_model,
			max1720x_set_custom_model);

static ssize_t max1720x_show_model_reg(struct file *filp, char __user *buf,
				       size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	const struct max17x0x_regmap *map = &chip->regmap;
	u32 reg_address;
	unsigned int data;
	char *tmp;
	int len = 0, ret, rc;

	if (!map->regmap) {
		pr_err("Failed to read, no regmap\n");
		return -EIO;
	}

	tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!tmp)
		return -ENOMEM;

	rc = max_m5_model_lock(map->regmap, false);
	if (rc < 0)
		pr_warn("unlock fail, rc=%d\n", rc);

	for (reg_address = MAX_M5_FG_MODEL_START;
	     reg_address < MAX_M5_FG_MODEL_START + MAX_M5_FG_MODEL_SIZE ; reg_address++) {
		ret = regmap_read(map->regmap, reg_address, &data);
		if (ret < 0)
			continue;

		len += scnprintf(tmp + len, PAGE_SIZE - len, "%02x: %04x\n", reg_address, data);
	}

	rc = max_m5_model_lock(map->regmap, true);
	if (rc < 0)
		pr_warn("lock fail, rc=%d\n", rc);

	if (len > 0)
		len = simple_read_from_buffer(buf, count, ppos, tmp, len);

	kfree(tmp);

	return len;
}

BATTERY_DEBUG_ATTRIBUTE(debug_model_reg_fops, max1720x_show_model_reg, NULL);


static int debug_sync_model(void *data, u64 val)
{
	struct max1720x_chip *chip = data;
	int ret;

	if (!chip->model_data)
		return -EINVAL;

	/* re-read new state from Fuel gauge, save to storage  */
	ret = max_m5_model_read_state(chip->model_data);
	if (ret == 0) {
		ret = max_m5_model_check_state(chip->model_data);
		if (ret < 0)
			pr_warn("%s: warning invalid state %d\n", __func__, ret);

		ret = max_m5_save_state_data(chip->model_data);
	}

	return ret;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_sync_model_fops, NULL, debug_sync_model, "%llu\n");


static ssize_t max1720x_show_debug_data(struct file *filp, char __user *buf,
					size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	char msg[8];
	u16 data;
	int ret;

	ret = REGMAP_READ(&chip->regmap, chip->debug_reg_address, &data);
	if (ret < 0)
		return ret;

	ret = scnprintf(msg, sizeof(msg), "%x\n", data);

	return simple_read_from_buffer(buf, count, ppos, msg, ret);
}

static ssize_t max1720x_set_debug_data(struct file *filp,
				       const char __user *user_buf,
				       size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	char temp[8] = { };
	u16 data;
	int ret;

	ret = simple_write_to_buffer(temp, sizeof(temp) - 1, ppos, user_buf, count);
	if (!ret)
		return -EFAULT;

	ret = kstrtou16(temp, 16, &data);
	if (ret < 0)
		return ret;

	ret =  REGMAP_WRITE(&chip->regmap, chip->debug_reg_address, data);
	if (ret < 0)
		return ret;

	return count;
}

BATTERY_DEBUG_ATTRIBUTE(debug_reg_data_fops, max1720x_show_debug_data,
			max1720x_set_debug_data);

static ssize_t max1720x_show_reg_all(struct file *filp, char __user *buf,
					size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	const struct max17x0x_regmap *map = &chip->regmap;
	u32 reg_address;
	unsigned int data;
	char *tmp;
	int ret = 0, len = 0;

	if (!map->regmap) {
		pr_err("Failed to read, no regmap\n");
		return -EIO;
	}

	tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!tmp)
		return -ENOMEM;

	for (reg_address = 0; reg_address <= 0xFF; reg_address++) {
		ret = regmap_read(map->regmap, reg_address, &data);
		if (ret < 0)
			continue;

		len += scnprintf(tmp + len, PAGE_SIZE - len, "%02x: %04x\n", reg_address, data);
	}

	if (len > 0)
		len = simple_read_from_buffer(buf, count,  ppos, tmp, strlen(tmp));

	kfree(tmp);

	return len;
}

BATTERY_DEBUG_ATTRIBUTE(debug_reg_all_fops, max1720x_show_reg_all, NULL);

static ssize_t max1720x_show_nvreg_all(struct file *filp, char __user *buf,
					size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;
	const struct max17x0x_regmap *map = &chip->regmap_nvram;
	u32 reg_address;
	unsigned int data;
	char *tmp;
	int ret = 0, len = 0;

	if (!map->regmap) {
		pr_err("Failed to read, no regmap\n");
		return -EIO;
	}

	tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!tmp)
		return -ENOMEM;

	for (reg_address = 0; reg_address <= 0xFF; reg_address++) {
		ret = regmap_read(map->regmap, reg_address, &data);
		if (ret < 0)
			continue;

		len += scnprintf(tmp + len, PAGE_SIZE - len, "%02x: %04x\n", reg_address, data);
	}

	if (len > 0)
		len = simple_read_from_buffer(buf, count,  ppos, tmp, strlen(tmp));

	kfree(tmp);

	return len;
}

BATTERY_DEBUG_ATTRIBUTE(debug_nvreg_all_fops, max1720x_show_nvreg_all, NULL);

static ssize_t max1720x_force_psy_update(struct file *filp,
					 const char __user *user_buf,
					 size_t count, loff_t *ppos)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)filp->private_data;

	if (chip->psy)
		power_supply_changed(chip->psy);

	return count;
}

BATTERY_DEBUG_ATTRIBUTE(debug_force_psy_update_fops, NULL,
			max1720x_force_psy_update);

static int debug_cnhs_reset(void *data, u64 val)
{
	struct max1720x_chip *chip = data;
	u16 reset_val;
	int ret;

	reset_val = (u16)val;

	ret = gbms_storage_write(GBMS_TAG_CNHS, &reset_val,
				sizeof(reset_val));
	dev_info(chip->dev, "reset CNHS to %d, (ret=%d)\n", reset_val, ret);

	return ret == sizeof(reset_val) ? 0 : ret;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_reset_cnhs_fops, NULL, debug_cnhs_reset, "%llu\n");

static int debug_gmsr_reset(void *data, u64 val)
{
	struct max1720x_chip *chip = data;
	int ret;

	ret = max_m5_reset_state_data(chip->model_data);
	dev_info(chip->dev, "reset GMSR (ret=%d)\n", ret);

	return ret;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_reset_gmsr_fops, NULL, debug_gmsr_reset, "%llu\n");

static int debug_current_offset(void *data, u64 val)
{
	struct max1720x_chip *chip = data;
	int ret = 0;

	if (!val || chip->current_offset_done)
		return ret;

	ret = max1720x_current_offset_fix(chip);
	if (ret < 0)
		dev_info(chip->dev, "%s: current_offset fail (ret=%d)\n", __func__, ret);
	else
		chip->current_offset_done = true;

	return ret;
}

DEFINE_SIMPLE_ATTRIBUTE(debug_current_offset_fops, NULL, debug_current_offset, "%llu\n");

/*
 * TODO: add the building blocks of google capacity
 *
 * case POWER_SUPPLY_PROP_DELTA_CC_SUM:
 *	val->intval = chip->cap_estimate.delta_cc_sum;
 *	break;
 * case POWER_SUPPLY_PROP_DELTA_VFSOC_SUM:
 *	val->intval = chip->cap_estimate.delta_vfsoc_sum;
 *	break;
 */

static ssize_t act_impedance_store(struct device *dev,
			       struct device_attribute *attr,
			       const char *buf, size_t count) {
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);
	int value, ret = 0;

	ret = kstrtoint(buf, 0, &value);
	if (ret < 0)
		return ret;

	mutex_lock(&chip->model_lock);

	ret = max1720x_health_update_ai(chip, value);
	if (ret == 0)
		chip->bhi_acim = 0;

	dev_info(chip->dev, "value=%d  (%d)\n", value, ret);

	mutex_unlock(&chip->model_lock);
	return count;
}

static ssize_t act_impedance_show(struct device *dev,
			      struct device_attribute *attr, char *buf)
{
	struct power_supply *psy = container_of(dev, struct power_supply, dev);
	struct max1720x_chip *chip = power_supply_get_drvdata(psy);

	return scnprintf(buf, PAGE_SIZE, "%d\n", max1720x_health_get_ai(chip));
}

static const DEVICE_ATTR_RW(act_impedance);


static int max17x0x_init_sysfs(struct max1720x_chip *chip)
{
	struct dentry *de;
	int ret;

	/* stats */
	ret = device_create_file(&chip->psy->dev, &dev_attr_act_impedance);
	if (ret)
		dev_err(&chip->psy->dev, "Failed to create act_impedance\n");

	de = debugfs_create_dir(chip->max1720x_psy_desc.name, 0);
	if (IS_ERR_OR_NULL(de))
		return -ENOENT;

	debugfs_create_file("irq_none_cnt", 0644, de, chip, &irq_none_cnt_fops);
	debugfs_create_file("nvram_por", 0440, de, chip, &debug_nvram_por_fops);
	debugfs_create_file("fg_reset", 0400, de, chip, &debug_fg_reset_fops);
	debugfs_create_file("ce_start", 0400, de, chip, &debug_ce_start_fops);
	debugfs_create_file("fake_battery", 0400, de, chip, &debug_fake_battery_fops);
	debugfs_create_file("batt_id", 0600, de, chip, &debug_batt_id_fops);
	debugfs_create_file("force_psy_update", 0600, de, chip, &debug_force_psy_update_fops);
	debugfs_create_file("log_learn", 0400, de, chip, &debug_log_learn_fops);

	if (chip->regmap.reglog)
		debugfs_create_file("regmap_writes", 0440, de,
					chip->regmap.reglog,
					&debug_reglog_writes_fops);

	if (chip->regmap_nvram.reglog)
		debugfs_create_file("regmap_nvram_writes", 0440, de,
					chip->regmap_nvram.reglog,
					&debug_reglog_writes_fops);

	if (chip->gauge_type == MAX_M5_GAUGE_TYPE) {
		debugfs_create_file("fg_model", 0444, de, chip,
				    &debug_m5_custom_model_fops);
		debugfs_create_file("model_registers", 0444, de, chip,
				    &debug_model_reg_fops);
	}
	debugfs_create_bool("model_ok", 0444, de, &chip->model_ok);
	debugfs_create_file("sync_model", 0400, de, chip,
			    &debug_sync_model_fops);

	/* capacity drift fixup, one of MAX1720X_DA_VER_* */
	debugfs_create_u32("algo_ver", 0644, de, &chip->drift_data.algo_ver);

	/* new debug interface */
	debugfs_create_u32("address", 0600, de, &chip->debug_reg_address);
	debugfs_create_file("data", 0600, de, chip, &debug_reg_data_fops);

	/* dump all registers */
	debugfs_create_file("registers", 0444, de, chip, &debug_reg_all_fops);

	if (chip->regmap_nvram.regmap)
		debugfs_create_file("nv_registers", 0444, de, chip, &debug_nvreg_all_fops);

	/* reset fg eeprom data for debugging */
	if (chip->gauge_type == MAX_M5_GAUGE_TYPE) {
		debugfs_create_file("cnhs_reset", 0400, de, chip, &debug_reset_cnhs_fops);
		debugfs_create_file("gmsr_reset", 0400, de, chip, &debug_reset_gmsr_fops);
		debugfs_create_file("current_offset", 0444, de, chip, &debug_current_offset_fops);
		debugfs_create_u32("bhi_target_capacity", 0644, de, &chip->bhi_target_capacity);
		debugfs_create_u32("bhi_recalibration_algo", 0644, de,
				   &chip->bhi_recalibration_algo);
	}

	/* capacity fade */
	debugfs_create_u32("bhi_fcn_count", 0644, de, &chip->bhi_fcn_count);

	/* dynamic filtercfg for testing */
	debugfs_create_bool("disable_dynamic_filtercfg", 0444, de,
			    &chip->dyn_filtercfg.disable_dynamic_filtercfg);

	return 0;
}

static u16 max1720x_read_rsense(const struct max1720x_chip *chip)
{
	u32 rsense_default = 500;
	int dt_rsense, ret;
	u16 rsense = 0;

	ret = of_property_read_u32(chip->dev->of_node, "maxim,rsense-default",
				   &rsense_default);
	dt_rsense = ret == 0;

	/* read from NVRAM if present */
	if (chip->regmap_nvram.regmap) {

		ret = REGMAP_READ(&chip->regmap_nvram, MAX1720X_NRSENSE, &rsense);
		if (ret == 0 && dt_rsense && rsense != rsense_default) {
			dev_warn(chip->dev, "RSense %d, forcing to %d uOhm\n",
				 rsense * 10, rsense_default * 10);

			rsense = rsense_default;
		}
	}

	if (!rsense)
		rsense = rsense_default;

	return rsense;
}

/*
 * The BCNT, QHQH and QHCA for 17202 modify these common registers
 * 0x18C, 0x18D, 0x18E, 0x18F, 0x1B2, 0x1B4 which will default to 0 after
 * the recovery procedure. The map changes the content of 0x1C4, 0x1C5 which
 * are not used (and should be 0 unless used by a future version of SW) as well
 * as 0x1CD, 0x1CE used for nManfctrName1/2 which might change. 0x1DF is the
 * INI checksum that will change with updates and cannot be used for this test.
 * The only register left is 0x1D7 (MAX1730X_NPROTCFG), that is the register
 * that the code will used to determine the corruption.
 */
static int max1730x_check_prot(struct max1720x_chip *chip, u16 devname)
{
	int needs_recall = 0;
	u16 nprotcfg;
	int ret;

	/* check protection registers */
	ret = REGMAP_READ(&chip->regmap_nvram, MAX1730X_NPROTCFG, &nprotcfg);
	if (ret < 0)
		return -EIO;

	if (devname == MAX1730X_GAUGE_PASS1)
		needs_recall = (nprotcfg != MAX1730X_NPROTCFG_PASS1);
	else /* pass2 */
		needs_recall = (nprotcfg != MAX1730X_NPROTCFG_PASS2);

	return needs_recall;
}

static int max17x0x_nvram_recall(struct max1720x_chip *chip)
{
	REGMAP_WRITE(&chip->regmap,
			MAX17XXX_COMMAND,
			MAX17XXX_COMMAND_NV_RECALL);
	msleep(MAX17X0X_TPOR_MS);
	return 0;
}

/* TODO: move to google/max1730x_battery.c, enable with build config */
static int max1730x_fixups(struct max1720x_chip *chip)
{
	int ret;

	struct device_node *node = chip->dev->of_node;
	bool write_back = false, write_ndata = false;
	const u16 val = 0x280B;
	u16 ndata = 0, bak = 0;

	/* b/123026365 */
	if (of_property_read_bool(node, "maxim,enable-nv-check")) {
		const u16 devname = (chip->devname >> 4);
		int needs_recall;

		needs_recall = max1730x_check_prot(chip, devname);
		if (needs_recall < 0) {
			dev_err(chip->dev, "error reading fg NV configuration\n");
		} else if (needs_recall == 0) {
			/* all good.. */
		} else if (devname == MAX1730X_GAUGE_PASS1) {
			dev_err(chip->dev, "***********************************************\n");
			dev_err(chip->dev, "WARNING: need to restore FG NV configuration to\n");
			dev_err(chip->dev, "default values. THE DEVICE WILL LOOSE POWER.\n");
			dev_err(chip->dev, "*******************************************\n");
			msleep(MSEC_PER_SEC);
			REGMAP_WRITE(&chip->regmap, MAX17XXX_COMMAND,
				     MAX1720X_COMMAND_HARDWARE_RESET);
			msleep(MAX17X0X_TPOR_MS);
		} else {
			dev_err(chip->dev, "Restoring FG NV configuration to sane values\n");

			if (!chip->needs_reset) {
				ret = max17x0x_nvram_recall(chip);
				if (ret == 0)
					chip->needs_reset = true;
			}

			REGMAP_WRITE(&chip->regmap_nvram,
					MAX1730X_NPROTCFG,
					MAX1730X_NPROTCFG_PASS2);
		}
	} else {
		dev_err(chip->dev, "nv-check disabled\n");
	}

	/* b/122605202 */
	ret = REGMAP_READ(&chip->regmap_nvram, MAX1730X_NVPRTTH1, &ndata);
	if (ret == 0)
		ret = REGMAP_READ(&chip->regmap, MAX1730X_NVPRTTH1BAK, &bak);
	if (ret < 0)
		return -EIO;

	if (ndata == MAX1730X_NVPRTTH1_CHARGING)
		write_back = (bak != val);
	else
		write_ndata = (ndata != val);

	if (write_back || write_ndata) {
		ret = REGMAP_WRITE(&chip->regmap,
				   MAX1730X_NVPRTTH1BAK, val);
		if (ret == 0)
			ret = REGMAP_WRITE(&chip->regmap_nvram,
					   MAX1730X_NVPRTTH1, val);
		if (ret == 0)
			ret = REGMAP_WRITE(&chip->regmap,
					   MAX1730X_NVPRTTH1BAK, val);
	}

	if (ret < 0)
		dev_info(chip->dev, "failed to update 0x0D6=%x 0x1D0=%x to %x (%d)\n",
			 bak, ndata, val, ret);
	else if (write_back)
		dev_info(chip->dev, "0x0D6=%x 0x1D0=%x updated to %x (%d)\n",
			 bak, ndata, val, ret);
	else if (write_ndata)
		dev_info(chip->dev, "0x1D0=%x updated to %x (%d)\n",
			ndata, val, ret);

	return ret;
}

static int max17x0x_dump_param(struct max1720x_chip *chip)
{
	int ret;
	u16 data;

	ret = max17x0x_reg_read(&chip->regmap, MAX17X0X_TAG_cnfg,
				&chip->RConfig);
	if (ret < 0)
		return ret;

	dev_info(chip->dev, "Config: 0x%04x\n", chip->RConfig);

	ret = REGMAP_READ(&chip->regmap, MAX1720X_ICHGTERM, &data);
	if (ret < 0)
		return ret;

	dev_info(chip->dev, "IChgTerm: %d\n",
		 reg_to_micro_amp(data, chip->RSense));

	ret = REGMAP_READ(&chip->regmap, MAX1720X_VEMPTY, &data);
	if (ret < 0)
		return ret;

	dev_info(chip->dev, "VEmpty: VE=%dmV VR=%dmV\n",
		 reg_to_vempty(data), reg_to_vrecovery(data));

	return 0;
}

static int max1720x_clear_por(struct max1720x_chip *chip)
{
	u16 data;
	int ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_STATUS, &data);
	if (ret < 0)
		return ret;

	if ((data & MAX1720X_STATUS_POR) == 0)
		return 0;

	return regmap_update_bits(chip->regmap.regmap,
				  MAX1720X_STATUS,
				  MAX1720X_STATUS_POR,
				  0x0);
}

/* read state from fg (if needed) and set the next update field */
static int max1720x_set_next_update(struct max1720x_chip *chip)
{
	int rc;
	u16 reg_cycle;

	/* do not save data when battery ID not clearly or under recalibration */
	if (chip->batt_id == DEFAULT_BATTERY_ID)
		return 0;

	rc = REGMAP_READ(&chip->regmap, MAX1720X_CYCLES, &reg_cycle);
	if (rc < 0)
		return rc;

	if (chip->model_next_update && reg_cycle < chip->model_next_update)
		return 0;

	/* read new state from Fuel gauge, save to storage if needed */
	rc = max_m5_model_read_state(chip->model_data);
	if (rc == 0) {
		rc = max_m5_model_check_state(chip->model_data);
		if (rc < 0) {
			pr_debug("%s: fg model state is corrupt rc=%d\n",
				 __func__, rc);
			return -EINVAL;
		}
	}

	if (rc == 0 && chip->model_next_update)
		rc = max_m5_save_state_data(chip->model_data);
	if (rc == 0)
		chip->model_next_update = (reg_cycle + (1 << 6)) &
					  ~((1 << 6) - 1);

	pr_debug("%s: reg_cycle=%d next_update=%d rc=%d\n", __func__,
		 reg_cycle, chip->model_next_update, rc);

	return 0;
}

static int max1720x_model_load(struct max1720x_chip *chip)
{
	int ret;

	/* retrieve model state from permanent storage only on boot */
	if (!chip->model_state_valid) {

		/*
		 * retrieve state from storage: retry on -EAGAIN as long as
		 * model_reload > _IDLE
		 */
		ret = max_m5_load_state_data(chip->model_data);
		if (ret == -EAGAIN)
			return -EAGAIN;
		if (ret < 0)
			dev_warn(chip->dev, "Load Model Using Default State (%d)\n",
				ret);

		/* use the state from the DT when GMSR is invalid */
	}

	/* failure on the gauge: retry as long as model_reload > IDLE */
	ret = max_m5_load_gauge_model(chip->model_data);
	if (ret < 0) {
		dev_err(chip->dev, "Load Model Failed ret=%d\n", ret);
		return -EAGAIN;
	}

	/* fix capacity outliers algo */
	ret = max_m5_fixup_outliers(&chip->drift_data, chip->model_data);
	if (ret < 0)
		dev_err(chip->dev, "Load Model fixing drift data rc=%d\n", ret);

	/* mark model state as "safe" */
	chip->reg_prop_capacity_raw = MAX1720X_REPSOC;
	chip->model_state_valid = true;
	return 0;
}

static void max1720x_model_work(struct work_struct *work)
{
	struct max1720x_chip *chip = container_of(work, struct max1720x_chip,
						  model_work.work);
	bool new_model = false;
	u16 reg_cycle;
	int rc;

	if (!chip->model_data)
		return;

	mutex_lock(&chip->model_lock);

	/* set model_reload to the #attempts, might change cycle count */
	if (chip->model_reload >= MAX_M5_LOAD_MODEL_REQUEST) {

		rc = max1720x_model_load(chip);
		if (rc == 0) {
			rc = max1720x_clear_por(chip);

			dev_info(chip->dev, "Model OK, Clear Power-On Reset (%d)\n", rc);
			/* TODO: keep trying to clear POR if the above fail */

			if (max_m5_recal_state(chip->model_data) == RE_CAL_STATE_IDLE) {
				rc = max1720x_restore_battery_cycle(chip);
				if (rc < 0)
					dev_err(chip->dev, "%s cannot restore cycle count (%d)\n",
						__func__, rc);
			} else { /* if recal is ongoing, no need to restore cycle */
				chip->cycle_reg_ok = true;
			}

			rc = REGMAP_READ(&chip->regmap, MAX1720X_CYCLES, &reg_cycle);
			if (rc == 0) {
				chip->model_reload = MAX_M5_LOAD_MODEL_IDLE;
				chip->model_ok = true;
				new_model = true;
				/* saved new value in max1720x_set_next_update */
				chip->model_next_update = reg_cycle > 0 ? reg_cycle - 1 : 0;
			}
		} else if (rc != -EAGAIN) {
			chip->model_reload = MAX_M5_LOAD_MODEL_DISABLED;
			chip->model_ok = false;
		} else if (chip->model_reload > MAX_M5_LOAD_MODEL_IDLE) {
			chip->model_reload += 1;
		}
	}

	/* b/171741751, fix capacity drift (if POR is cleared) */
	if (max1720x_check_drift_enabled(&chip->drift_data))
		max1720x_fixup_capacity(chip, chip->cap_estimate.cable_in);

	if (chip->model_reload >= MAX_M5_LOAD_MODEL_REQUEST) {
		const unsigned long delay = msecs_to_jiffies(60 * 1000);

		mod_delayed_work(system_wq, &chip->model_work, delay);
	}

	if (new_model) {
		dev_info(chip->dev, "FG Model OK, ver=%d cap_lsb=%d next_update=%d\n",
			 max_m5_fg_model_version(chip->model_data),
			 max_m5_cap_lsb(chip->model_data),
			 chip->model_next_update);
		max1720x_prime_battery_qh_capacity(chip, POWER_SUPPLY_STATUS_UNKNOWN);
		power_supply_changed(chip->psy);
	}

	mutex_unlock(&chip->model_lock);
}


static int max17201_init_rc_switch(struct max1720x_chip *chip)
{
	int ret = 0;

	if (chip->gauge_type != MAX_M5_GAUGE_TYPE)
		return -EINVAL;

	chip->rc_switch.enable = of_property_read_bool(chip->dev->of_node, "maxim,rc-enable");

	ret = of_property_read_u32(chip->dev->of_node, "maxim,rc-soc", &chip->rc_switch.soc);
	if (ret < 0)
		return -EINVAL;

	ret = of_property_read_u32(chip->dev->of_node, "maxim,rc-temp", &chip->rc_switch.temp);
	if (ret < 0)
		return -EINVAL;

	ret = of_property_read_u16(chip->batt_node, "maxim,rc1-tempco", &chip->rc_switch.rc1_tempco);
	if (ret < 0)
		return -EINVAL;

	ret = max_m5_get_rc_switch_param(chip->model_data, &chip->rc_switch.rc2_tempco,
					 &chip->rc_switch.rc2_learncfg);
	if (ret < 0)
		return -EINVAL;

	chip->rc_switch.available = true;

	dev_info(chip->dev, "rc_switch soc:%d temp:%d rc1_tempco:%#x rc2_tempco:%#x cfg:%#x\n",
		 chip->rc_switch.soc, chip->rc_switch.temp, chip->rc_switch.rc1_tempco,
		 chip->rc_switch.rc2_tempco, chip->rc_switch.rc2_learncfg);

	if (chip->rc_switch.enable)
		schedule_delayed_work(&chip->rc_switch.switch_work, msecs_to_jiffies(60 * 1000));

	return 0;
}

#define RC_WORK_TIME_MS	60 * 1000
#define RC_WORK_TIME_QUICK_MS	5 * 1000
static void max1720x_rc_work(struct work_struct *work)
{
	struct max1720x_chip *chip = container_of(work, struct max1720x_chip,
						  rc_switch.switch_work.work);
	int interval = RC_WORK_TIME_MS;
	u16 data, learncfg;
	bool to_rc1, to_rc2;
	int ret = 0, soc, temp;

	if (!chip->rc_switch.available || !chip->rc_switch.enable)
		return;

	if (chip->por || !chip->resume_complete)
		goto reschedule;

	/* Read SOC */
	ret = REGMAP_READ(&chip->regmap, MAX_M5_REPSOC, &data);
	if (ret < 0)
		goto reschedule;

	soc = (data >> 8) & 0x00FF;

	/* Read Temperature */
	ret = max17x0x_reg_read(&chip->regmap, MAX17X0X_TAG_temp, &data);
	if (ret < 0)
		goto reschedule;

	temp = reg_to_deci_deg_cel(data);

	/* Read LearnCfg */
	ret = REGMAP_READ(&chip->regmap, MAX_M5_LEARNCFG, &learncfg);
	if (ret < 0)
		goto reschedule;

	/* Disable LearnCfg.LearnTCO */
	if (learncfg & MAX_M5_LEARNCFG_LEARNTCO_CLEAR) {
		learncfg = MAX_M5_LEARNCFG_LEARNTCO_CLR(learncfg);
		ret = REGMAP_WRITE(&chip->regmap, MAX_M5_LEARNCFG, learncfg);
		if (ret < 0)
			dev_warn(chip->dev, "Unable to clear LearnTCO\n");
	}

	to_rc1 = soc < chip->rc_switch.soc || temp < chip->rc_switch.temp;
	to_rc2 = soc >= chip->rc_switch.soc && temp >= chip->rc_switch.temp;

	if (to_rc1 && ((learncfg & MAX_M5_LEARNCFG_RC_VER) == MAX_M5_LEARNCFG_RC2)) {
		/*
		 * 1: set LearnCfg.LearnRComp = 0
		 * 2: load TempCo value from RC1 INI file
		 * 3: set LearnCfg.RCx = 0
		 */
		learncfg = MAX_M5_LEARNCFG_LEARNRCOMP_CLR(learncfg);
		ret = REGMAP_WRITE(&chip->regmap, MAX_M5_LEARNCFG, learncfg);

		if (ret == 0)
			ret = REGMAP_WRITE(&chip->regmap, MAX_M5_TEMPCO, chip->rc_switch.rc1_tempco);

		learncfg = MAX_M5_LEARNCFG_RC_VER_CLR(learncfg);
		if (ret == 0)
			ret = REGMAP_WRITE(&chip->regmap, MAX_M5_LEARNCFG, learncfg);

		gbms_logbuffer_prlog(chip->monitor_log, LOGLEVEL_INFO, 0, LOGLEVEL_INFO,
				     "%s to RC1. ret=%d soc=%d temp=%d tempco=0x%x, learncfg=0x%x",
				     __func__, ret, soc, temp, chip->rc_switch.rc1_tempco, learncfg);

	} else if (to_rc2 && ((learncfg & MAX_M5_LEARNCFG_RC_VER) == MAX_M5_LEARNCFG_RC1)) {
		/*
		 * 1: load LearnCfg.LearnRComp from RC2 INI value
		 * 2: load TempCo value from RC2 INI value
		 * 3: set LearnCfg.RCx = 1
		 */

		learncfg |= (chip->rc_switch.rc2_learncfg & MAX_M5_LEARNCFG_LEARNRCOMP);
		ret = REGMAP_WRITE(&chip->regmap, MAX_M5_LEARNCFG, learncfg);

		if (ret == 0)
			ret = REGMAP_WRITE(&chip->regmap, MAX_M5_TEMPCO, chip->rc_switch.rc2_tempco);

		learncfg = MAX_M5_LEARNCFG_RC_VER_SET(learncfg);
		if (ret == 0)
			ret = REGMAP_WRITE(&chip->regmap, MAX_M5_LEARNCFG, learncfg);

		gbms_logbuffer_prlog(chip->monitor_log, LOGLEVEL_INFO, 0, LOGLEVEL_INFO,
				     "%s to RC2. ret=%d soc=%d temp=%d tempco=0x%x, learncfg=0x%x",
				     __func__, ret, soc, temp, chip->rc_switch.rc2_tempco, learncfg);
	}

reschedule:
	if (ret != 0) {
		interval = RC_WORK_TIME_QUICK_MS;
		gbms_logbuffer_prlog(chip->monitor_log, LOGLEVEL_WARNING, 0, LOGLEVEL_INFO,
				     "%s didn't finish. ret=%d", __func__, ret);
	}

	mod_delayed_work(system_wq, &chip->rc_switch.switch_work, msecs_to_jiffies(interval));
}

static int read_chip_property_u32(const struct max1720x_chip *chip,
				  char *property, u32 *data32)
{
	int ret;

	if (chip->batt_node) {
		ret = of_property_read_u32(chip->batt_node, property, data32);
		if (ret == 0)
			return ret;
	}

	return of_property_read_u32(chip->dev->of_node, property, data32);
}

/* fix capacity drift after loading the model */
static int max17201_init_fix_capacity(struct max1720x_chip *chip)
{
	struct max1720x_drift_data *ddata = &chip->drift_data;
	u32 data32 = 0;
	u16 data16;
	int ret;

	ret = gbms_storage_read(GBMS_TAG_CMPC, &data16, sizeof(data16));
	if (ret == -EPROBE_DEFER)
		return -EPROBE_DEFER;
	if (ret == 0)
		chip->comp_update_count = data16;
	else
		chip->comp_update_count = 0;

	ret = gbms_storage_read(GBMS_TAG_DXAC, &data16, sizeof(data16));
	if (ret == -EPROBE_DEFER)
		return -EPROBE_DEFER;
	if (ret == 0)
		chip->dxacc_update_count = data16;
	else
		chip->dxacc_update_count = 0;

	/* device dependent values */
	ddata->rsense = chip->RSense;
	/* update design_capacity after loading the model if not set in dt */
	ret = of_property_read_u32(chip->dev->of_node, "maxim,capacity-design",
				   &data32);
	if (ret < 0) {
		ddata->design_capacity = -1;
	} else if (data32 != 0) {
		ddata->design_capacity = data32;
	} else if (chip->regmap_nvram.regmap) {
		/*
		 * TODO: read design capacity from NVRAM if available
		 * ret = REGMAP_READ(&chip->regmap_nvram, MAX1720X_NDESIGNCAP,
		 *		  &ddata->design_capacity);
		 */
		ret = REGMAP_READ(&chip->regmap, MAX1720X_DESIGNCAP,
				  &ddata->design_capacity);
		if (ret < 0)
			return -EPROBE_DEFER;

		/* add retries? */
	}

	/*
	 * chemistry dependent codes:
	 * NOTE: ->batt_node is initialized in *_handle_dt_shadow_config
	 */
	ret = read_chip_property_u32(chip, "maxim,capacity-rcomp0", &data32);
	if (ret < 0)
		ddata->ini_rcomp0 = -1;
	else
		ddata->ini_rcomp0 = data32;

	ret = read_chip_property_u32(chip, "maxim,capacity-tempco", &data32);
	if (ret < 0)
		ddata->ini_tempco = -1;
	else
		ddata->ini_tempco = data32;

	ret = of_property_read_u32(chip->dev->of_node, "maxim,capacity-stable",
				   &data32);
	if (ret < 0)
		ddata->cycle_stable = BATTERY_DEFAULT_CYCLE_STABLE;
	else
		ddata->cycle_stable = data32;

	ret = of_property_read_u32(chip->dev->of_node, "maxim,capacity-fade",
				   &data32);
	if (ret < 0)
		ddata->cycle_fade = BATTERY_DEFAULT_CYCLE_FADE;
	else
		ddata->cycle_fade = data32;

	ret = of_property_read_u32(chip->dev->of_node, "maxim,capacity-band",
				   &data32);
	if (ret < 0) {
		ddata->cycle_band = BATTERY_DEFAULT_CYCLE_BAND;
	} else {
		ddata->cycle_band = data32;
		if (ddata->cycle_band > BATTERY_MAX_CYCLE_BAND)
			ddata->cycle_band = BATTERY_MAX_CYCLE_BAND;
	}

	/*
	 * Set to force loading the model with corresponding algo-version.
	 * MW A0+ MW-A0 should use MAX1720X_DA_VER_ORIG while and MW-A1 should
	 * use MAX1720X_DA_VER_MWA1 for RC1 or MAX1720X_DA_VER_NONE for RC2.
	 * MW-A2 should use MAX1720X_DA_VER_NONE for RC1 and RC2.
	 * Not used for max1720x and max1730x.
	 */
	if (max_m5_check_devname(chip->devname) ) {
		ret = of_property_read_u32(chip->dev->of_node,
					   "maxim,algo-version",
					   &data32);
		if (ret < 0 || data32 > MAX1720X_DA_VER_MWA2)
			ddata->algo_ver = MAX1720X_DA_VER_NONE;
		else
			ddata->algo_ver = data32;
	} else {
		ddata->algo_ver = MAX1720X_DA_VER_ORIG;
	}

	ret = read_chip_property_u32(chip, "maxim,capacity-filtercfg", &data32);
	if (ret < 0)
		ddata->ini_filtercfg = -1;
	else
		ddata->ini_filtercfg = data32;

	if (ddata->ini_filtercfg != -1)
		dev_info(chip->dev, "ini_filtercfg=0x%x\n",
			 ddata->ini_filtercfg);

	return 0;
}

static int max1720x_check_config(struct max1720x_chip *chip)
{
	u16 data;
	int ret;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_CONFIG, &data);
	if (ret == 0 && (data & MAX1720X_CONFIG_TEN) == 0)
		return -EINVAL;

	return 0;
}

static int max1720x_log_event(struct max1720x_chip *chip, gbms_tag_t tag)
{
	u8 event_count;
	int ret = 0;

	ret = gbms_storage_read(tag, &event_count, sizeof(event_count));
	if (ret < 0)
		return ret;

	/* max count */
	if (event_count == 0xFE)
		return 0;

	/* initial value */
	if (event_count == 0xFF)
		event_count = 1;
	else
		event_count++;

	ret = gbms_storage_write(tag, &event_count, sizeof(event_count));
	if (ret < 0)
		return ret;

	dev_info(chip->dev, "tag:0x%X, event_count:%d\n", tag, event_count);

	return 0;
}

/* handle recovery of FG state */
static int max1720x_init_max_m5(struct max1720x_chip *chip)
{
	int ret;

	if (!chip->model_data)
		return 0;

	if (!max_m5_fg_model_check_version(chip->model_data)) {
		if (max_m5_needs_reset_model_data(chip->model_data)) {
			ret = max_m5_reset_state_data(chip->model_data);
			if (ret < 0)
				dev_err(chip->dev, "GMSR: failed to erase RC2 saved model data"
						" ret=%d\n", ret);
			else
				dev_warn(chip->dev, "GMSR: RC2 model data erased\n");
		}

		/* this is expected */
		ret = max1720x_full_reset(chip);

		dev_warn(chip->dev, "FG Version Changed, Reset (%d), Will Reload\n",
			 ret);
		return 0;
	}

	/* TODO add retries */
	ret = max_m5_model_read_state(chip->model_data);
	if (ret < 0) {
		dev_err(chip->dev, "FG Model Error (%d)\n", ret);
		return -EPROBE_DEFER;
	}

	/* this is a real failure and must be logged */
	ret = max_m5_model_check_state(chip->model_data);
	if (ret < 0) {
		int rret, sret = -1;

		rret = max1720x_full_reset(chip);
		if (rret == 0)
			sret = max_m5_model_read_state(chip->model_data);

		dev_err(chip->dev, "FG State Corrupt (%d), Reset (%d), State (%d) Will reload\n",
			ret, rret, sret);

		ret = max1720x_log_event(chip, GBMS_TAG_SELC);
		if (ret < 0)
			dev_err(chip->dev, "Cannot log the event (%d)\n", ret);

		return 0;
	}

	ret = max1720x_check_config(chip);
	if (ret < 0) {
		ret = max1720x_full_reset(chip);
		if (ret == 0)
			ret = max_m5_model_read_state(chip->model_data);

		dev_err(chip->dev, "Invalid config data, Reset (%d), Will reload\n",
			ret);

		ret = max1720x_log_event(chip, GBMS_TAG_CELC);
		if (ret < 0)
			dev_err(chip->dev, "Cannot log the event (%d)\n", ret);

		return 0;
	}

	ret = max1720x_set_next_update(chip);
	if (ret < 0)
		dev_warn(chip->dev, "Error on Next Update, Will retry\n");

	dev_info(chip->dev, "FG Model OK, ver=%d cap_lsb=%d next_update=%d\n",
			max_m5_model_read_version(chip->model_data),
			max_m5_cap_lsb(chip->model_data),
			chip->model_next_update);

	chip->reg_prop_capacity_raw = MAX1720X_REPSOC;
	chip->model_state_valid = true;
	chip->model_ok = true;
	return 0;
}

static int max1720x_init_chip(struct max1720x_chip *chip)
{
	int ret;
	u8 vreg, vpor;
	u16 data = 0, tmp;
	bool force_recall = false;

	if (of_property_read_bool(chip->dev->of_node, "maxim,force-hard-reset"))
		max1720x_full_reset(chip);

	ret = REGMAP_READ(&chip->regmap, MAX1720X_STATUS, &data);
	if (ret < 0)
		return -EPROBE_DEFER;
	chip->por = (data & MAX1720X_STATUS_POR) != 0;
	if (chip->por && chip->regmap_nvram.regmap) {
		dev_err(chip->dev, "Recall: POR bit is set\n");
		force_recall = true;
	}

	/* TODO: disable with maxim,fix-ignore-zero-rsense */
	chip->RSense = max1720x_read_rsense(chip);
	if (chip->RSense == 0) {
		dev_err(chip->dev, "Recall: RSense value 0 micro Ohm\n");
		force_recall = true;
	}

	/* read por force recall and reset when version is the por */
	ret = max17x0x_read_dt_version_por(chip->dev->of_node,
					   chip->gauge_type, &vreg, &vpor);
	if (ret == 0) {
		ret = REGMAP_READ(&chip->regmap_nvram, vreg, &tmp);
		if ((ret == 0) && (vpor == (tmp & 0x00ff))) {
			dev_err(chip->dev, "Recall: POR version %d\n", vpor);
			force_recall = true;
		}
	}

	/* b/129384855 fix mismatch between pack INI file and overrides */
	if (of_property_read_bool(chip->dev->of_node, "maxim,fix-vempty")) {
		ret = REGMAP_READ(&chip->regmap, MAX1720X_VEMPTY, &data);
		if ((ret == 0) && (reg_to_vrecovery(data) == 0)) {
			dev_err(chip->dev, "Recall: zero vrecovery\n");
			force_recall = true;
		}
	}

	if (force_recall && chip->regmap_nvram.regmap) {
		/* debug only */
		ret = max17x0x_nvram_cache_init(&chip->nRAM_por,
						chip->gauge_type);
		if (ret == 0)
			ret = max17x0x_cache_load(&chip->nRAM_por,
						  &chip->regmap_nvram);
		if (ret < 0) {
			dev_err(chip->dev, "POR: Failed to backup config\n");
			return -EPROBE_DEFER;
		}

		dev_info(chip->dev, "Recall Battery NVRAM\n");
		ret = max17x0x_nvram_recall(chip);
		if (ret == 0)
			chip->needs_reset = true;

		/* TODO: enable with maxim,fix-nagefccfg */
		if (chip->gauge_type == MAX1720X_GAUGE_TYPE)
			REGMAP_WRITE(&chip->regmap_nvram,
				     MAX1720X_NAGEFCCFG, 0);
	}

	/* device dependent fixups to the registers */
	if (chip->fixups_fn) {
		ret = chip->fixups_fn(chip);
		if (ret < 0) {
			dev_err(chip->dev, "Fixups failed (%d)\n", ret);
			return ret;
		}
	}

	/* set maxim,force-batt-id in DT to not delay the probe */
	ret = max1720x_read_batt_id(&chip->batt_id, chip);
	if (ret == -EPROBE_DEFER) {
		if (chip->batt_id_defer_cnt) {
			chip->batt_id_defer_cnt -= 1;
			return -EPROBE_DEFER;
		}

		chip->batt_id = DEFAULT_BATTERY_ID;
		dev_info(chip->dev, "default device battery ID = %d\n",
			 chip->batt_id);
	} else {
		dev_info(chip->dev, "device battery RID: %d kohm\n",
			 chip->batt_id);
	}

	if (chip->batt_id == DEFAULT_BATTERY_ID || chip->batt_id == DUMMY_BATTERY_ID) {
		ret = REGMAP_WRITE(&chip->regmap, MAX_M5_CONFIG2, 0x0);
		if (ret < 0)
			dev_warn(chip->dev, "Cannot write 0x0 to Config(%d)\n", ret);
	}

	/*
	 * The behavior of the drift workaround changes with the capacity
	 * learning algo used in the part. Integrated FG might have
	 * configurable capacity learning.
	 */
	ret = max17201_init_fix_capacity(chip);
	if (ret < 0)
		dev_err(chip->dev, "Capacity drift WAR not enabled(%d)\n", ret);
	/*
	 * FG model is ony used for integrated FG (MW). Loading a model might
	 * change the capacity drift WAR algo_ver and design_capacity.
	 * NOTE: design_capacity used for drift might be updated after loading
	 * a FG model.
	 */
	ret = max1720x_init_model(chip);
	if (ret < 0)
		dev_err(chip->dev, "Cannot init FG model (%d)\n", ret);

	/* dump capacity drift fixup configuration only when enabled */
	if (chip->drift_data.algo_ver != MAX1720X_DA_VER_NONE) {
		struct max1720x_drift_data *ddata = &chip->drift_data;

		dev_info(chip->dev, "ver=%d rsns=%d cnts=%d,%d dc=%d cap_sta=%d cap_fad=%d rcomp0=0x%x tempco=0x%x\n",
			 ddata->algo_ver, ddata->rsense,
			 chip->comp_update_count, chip->dxacc_update_count,
			 ddata->design_capacity, ddata->cycle_stable,
			 ddata->cycle_fade, ddata->ini_rcomp0,
			 ddata->ini_tempco);
	}

	/*
	 * The RC change is WA for MaxCap increase abnormally b/213425610
	 */
	ret = max17201_init_rc_switch(chip);
	if (ret < 0)
		chip->rc_switch.available = false;

	/* not needed for FG with NVRAM */
	ret = max17x0x_handle_dt_shadow_config(chip);
	if (ret == -EPROBE_DEFER)
		return ret;

	ret = max17x0x_handle_dt_register_config(chip);
	if (ret == -EPROBE_DEFER)
		return ret;

	(void) max1720x_handle_dt_nconvgcfg(chip);
	(void) max1720x_handle_dt_filtercfg(chip);

	/* recall, force & reset SW */
	if (chip->needs_reset) {
		max17x0x_fg_reset(chip);

		if (chip->RSense == 0)
			chip->RSense = max1720x_read_rsense(chip);
	}

	ret = max17x0x_dump_param(chip);
	if (ret < 0)
		return -EPROBE_DEFER;
	dev_info(chip->dev, "RSense value %d micro Ohm\n", chip->RSense * 10);

	ret = REGMAP_READ(&chip->regmap, MAX1720X_STATUS, &data);
	if (!ret && data & MAX1720X_STATUS_BR) {
		dev_info(chip->dev, "Clearing Battery Removal bit\n");
		regmap_update_bits(chip->regmap.regmap, MAX1720X_STATUS,
				   MAX1720X_STATUS_BR, 0x0);
	}
	if (!ret && data & MAX1720X_STATUS_BI) {
		dev_info(chip->dev, "Clearing Battery Insertion bit\n");
		regmap_update_bits(chip->regmap.regmap, MAX1720X_STATUS,
				   MAX1720X_STATUS_BI, 0x0);
	}

	ret = max1720x_restore_battery_cycle(chip);
	if (ret < 0)
		dev_err(chip->dev, "%s cannot restore cycle count (%d)\n", __func__, ret);

	/* max_m5 triggers loading of the model in the irq handler on POR */
	if (!chip->por && chip->gauge_type == MAX_M5_GAUGE_TYPE) {
		ret = max1720x_init_max_m5(chip);
		if (ret < 0)
			return ret;
	} else if (chip->por && chip->gauge_type != MAX_M5_GAUGE_TYPE) {
		ret = regmap_update_bits(chip->regmap.regmap,
					 MAX1720X_STATUS,
					 MAX1720X_STATUS_POR, 0x0);
		dev_info(chip->dev, "Clearing Power-On Reset bit (%d)\n", ret);
		chip->reg_prop_capacity_raw = MAX1720X_REPSOC;
	}


	max1720x_restore_battery_qh_capacity(chip);

	return 0;
}

static int max1730x_decode_sn(char *serial_number,
			      unsigned int max,
			      const u16 *data)
{
	int tmp, count = 0;

	if (data[0] != 0x4257)	/* "BW": DSY */
		return -EINVAL;

	count += scnprintf(serial_number + count, max - count, "%02X%02X%02X",
			   data[3] & 0xFF,
			   data[4] & 0xFF,
			   data[5] & 0xFF);

	tmp = (((((data[1] >> 9) & 0x3f) + 1980) * 10000) +
		((data[1] >> 5) & 0xf) * 100 + (data[1] & 0x1F));
	count += scnprintf(serial_number + count, max - count, "%d",
			   tmp);

	count += scnprintf(serial_number + count, max - count, "%c%c",
			   data[0] >> 8, data[0] & 0xFF);

	count += scnprintf(serial_number + count, max - count, "%c%c%c%c",
			   data[7] >> 8,
			   data[8] >> 8,
			   data[9] >> 8,
			   data[9] & 0xFF);

	count += scnprintf(serial_number + count, max - count, "%c",
			   data[2] & 0xFF);

	count += scnprintf(serial_number + count, max - count, "%c%c",
			   data[6] >> 8, data[6] & 0xFF);
	return count;
}

static int max1720x_decode_sn(char *serial_number,
			      unsigned int max,
			      const u16 *data)
{
	int tmp, count = 0, shift;
	char cell_vendor;

	if (data[0] == 0x5357) /* "SW": SWD */
		shift = 0;
	else if (data[0] == 0x4257) /* "BW": DSY */
		shift = 8;
	else
		return -EINVAL;

	count += scnprintf(serial_number + count, max - count, "%02X%02X%02X",
			   data[1] >> shift,
			   data[2] >> shift,
			   data[3] >> shift);

	tmp = (((((data[4] >> 9) & 0x3f) + 1980) * 10000) +
		((data[4] >> 5) & 0xf) * 100 + (data[4] & 0x1F));
	count += scnprintf(serial_number + count, max - count, "%d",
			   tmp);

	count += scnprintf(serial_number + count, max - count, "%c%c",
			   data[0] >> 8,
			   data[0] & 0xFF);

	count += scnprintf(serial_number + count, max - count, "%c%c%c",
			   data[5] >> shift,
			   data[6] >> shift,
			   data[7] >> shift);

	tmp = data[8];
	if (tmp >> 8 == 0)
		tmp = ('?' << 8) | (tmp & 0xFF);
	if ((tmp & 0xFF) == 0)
		tmp = (tmp & 0xFF00) | '?';
	count += scnprintf(serial_number + count, max - count, "%c%c",
			   tmp >> 8,
			   tmp & 0xFF);

	cell_vendor = (shift == 8) ? (data[9] >> 8) : (data[9] & 0xFF);
	count += scnprintf(serial_number + count, max - count, "%c",
			   cell_vendor);

	if (shift == 8) {
		count += scnprintf(serial_number + count, max - count, "%02X",
				   data[10] >> 8);
	} else {
		count += scnprintf(serial_number + count, max - count, "%c%c",
				   data[10] >> 8, data[10] & 0xFF);
	}

	return count;
}

static void *ct_seq_start(struct seq_file *s, loff_t *pos)
{
	struct max1720x_history *hi = (struct max1720x_history *)s->private;

	if (*pos >= hi->history_count)
		return NULL;
	hi->history_index = *pos;

	return &hi->history_index;
}

static void *ct_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
	loff_t *spos = (loff_t *)v;
	struct max1720x_history *hi = (struct max1720x_history *)s->private;

	*pos = ++*spos;
	if (*pos >= hi->history_count)
		return NULL;

	return spos;
}

static void ct_seq_stop(struct seq_file *s, void *v)
{
	/* iterator in hi, no need to free */
}

static int ct_seq_show(struct seq_file *s, void *v)
{
	char temp[96];
	loff_t *spos = (loff_t *)v;
	struct max1720x_history *hi = (struct max1720x_history *)s->private;
	const size_t offset = *spos * hi->page_size;

	format_battery_history_entry(temp, sizeof(temp),
					hi->page_size, &hi->history[offset]);
	seq_printf(s, "%s\n", temp);

	return 0;
}

static const struct seq_operations ct_seq_ops = {
	.start = ct_seq_start,
	.next  = ct_seq_next,
	.stop  = ct_seq_stop,
	.show  = ct_seq_show
};

static int history_dev_open(struct inode *inode, struct file *file)
{
	struct max1720x_chip *chip =
		container_of(inode->i_cdev, struct max1720x_chip, hcdev);
	struct max1720x_history *hi;
	int history_count;

	hi = __seq_open_private(file, &ct_seq_ops, sizeof(*hi));
	if (!hi)
		return -ENOMEM;

	mutex_lock(&chip->history_lock);
	history_count = max1720x_history_read(chip, hi);
	if (history_count < 0) {
		mutex_unlock(&chip->history_lock);
		return history_count;
	} else if (history_count == 0) {
		dev_info(chip->dev, "No battery history has been recorded\n");
	}
	mutex_unlock(&chip->history_lock);

	return 0;
}

static int history_dev_release(struct inode *inode, struct file *file)
{
	struct max1720x_history *hi =
		((struct seq_file *)file->private_data)->private;

	if (hi) {
		max1720x_history_free(hi);
		seq_release_private(inode, file);
	}

	return 0;
}

static const struct file_operations hdev_fops = {
	.open = history_dev_open,
	.owner = THIS_MODULE,
	.read = seq_read,
	.release = history_dev_release,
};

static void max1720x_cleanup_history(struct max1720x_chip *chip)
{
	if (chip->history_added)
		cdev_del(&chip->hcdev);
	if (chip->history_available)
		device_destroy(chip->hcclass, chip->hcmajor);
	if (chip->hcclass)
		class_destroy(chip->hcclass);
	if (chip->hcmajor != -1)
		unregister_chrdev_region(chip->hcmajor, 1);
}

static int max1720x_init_history_device(struct max1720x_chip *chip)
{
	struct device *hcdev;

	mutex_init(&chip->history_lock);

	chip->hcmajor = -1;

	/* cat /proc/devices */
	if (alloc_chrdev_region(&chip->hcmajor, 0, 1, HISTORY_DEVICENAME) < 0)
		goto no_history;
	/* ls /sys/class */
	chip->hcclass = class_create(THIS_MODULE, HISTORY_DEVICENAME);
	if (chip->hcclass == NULL)
		goto no_history;
	/* ls /dev/ */
	hcdev = device_create(chip->hcclass, NULL, chip->hcmajor, NULL,
		HISTORY_DEVICENAME);
	if (hcdev == NULL)
		goto no_history;

	chip->history_available = true;
	cdev_init(&chip->hcdev, &hdev_fops);
	if (cdev_add(&chip->hcdev, chip->hcmajor, 1) == -1)
		goto no_history;

	chip->history_added = true;
	return 0;

no_history:
	max1720x_cleanup_history(chip);
	return -ENODEV;
}

static int max1720x_init_history(struct max1720x_chip *chip)
{
	if (chip->gauge_type == MAX1730X_GAUGE_TYPE) {
		chip->nb_history_pages = MAX1730X_N_OF_HISTORY_PAGES;
		chip->history_page_size = MAX1730X_HISTORY_PAGE_SIZE;
		chip->nb_history_flag_reg = MAX1730X_N_OF_HISTORY_FLAGS_REG;
	} else if (chip->gauge_type == MAX1720X_GAUGE_TYPE) {
		chip->nb_history_pages = MAX1720X_N_OF_HISTORY_PAGES;
		chip->history_page_size = MAX1720X_HISTORY_PAGE_SIZE;
		chip->nb_history_flag_reg = MAX1720X_N_OF_HISTORY_FLAGS_REG;
	} else {
		return -EINVAL;
	}

	return 0;
}

/* ------------------------------------------------------------------------- */

static int max17x0x_storage_info(gbms_tag_t tag, size_t *addr, size_t *count,
				 void *ptr)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)ptr;

	if (!chip->history_available)
		return -ENOENT;

	*count = chip->history_page_size * 2; /* storage is in byte */
	*addr = -1;
	return 0;
}

#define REG_HALF_HIGH(reg)     ((reg >> 8) & 0x00FF)
#define REG_HALF_LOW(reg)      (reg & 0x00FF)
static int max17x0x_collect_history_data(void *buff, size_t size,
					 struct max1720x_chip *chip)
{
	struct max17x0x_eeprom_history hist = { 0 };
	u16 data, designcap;
	int temp, ret;

	if (chip->por)
		return -EINVAL;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_TEMPCO, &data);
	if (ret)
		return ret;

	hist.tempco = data;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_RCOMP0, &data);
	if (ret)
		return ret;

	hist.rcomp0 = data;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_TIMERH, &data);
	if (ret)
		return ret;

	/* Convert LSB from 3.2hours(192min) to 5days(7200min) */
	hist.timerh = data * 192 / 7200;

	if (chip->designcap) {
		designcap = chip->designcap;
	} else {
		ret = REGMAP_READ(&chip->regmap, MAX1720X_DESIGNCAP, &designcap);
		if (ret)
			return ret;
	}

	/* multiply by 100 to convert from mAh to %, LSB 0.125% */
	ret = REGMAP_READ(&chip->regmap, MAX1720X_FULLCAPNOM, &data);
	if (ret)
		return ret;

	temp = (int)data * 800 / (int)designcap;
	hist.fullcapnom = temp > MAX_HIST_FULLCAP ? MAX_HIST_FULLCAP : temp;

	/* multiply by 100 to convert from mAh to %, LSB 0.125% */
	ret = REGMAP_READ(&chip->regmap, MAX1720X_FULLCAPREP, &data);
	if (ret)
		return ret;

	temp = (int)data * 800 / (int)designcap;
	hist.fullcaprep = temp > MAX_HIST_FULLCAP ? MAX_HIST_FULLCAP : temp;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_MIXSOC, &data);
	if (ret)
		return ret;

	/* Convert LSB from 1% to 2% */
	hist.mixsoc = REG_HALF_HIGH(data) / 2;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_VFSOC, &data);
	if (ret)
		return ret;

	/* Convert LSB from 1% to 2% */
	hist.vfsoc = REG_HALF_HIGH(data) / 2;


	ret = REGMAP_READ(&chip->regmap, MAX1720X_MAXMINVOLT, &data);
	if (ret)
		return ret;

	/* LSB is 20mV, store values from 4.2V min */
	hist.maxvolt = (REG_HALF_HIGH(data) * 20 - 4200) / 20;
	/* Convert LSB from 20mV to 10mV, store values from 2.5V min */
	hist.minvolt = (REG_HALF_LOW(data) * 20 - 2500) / 10;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_MAXMINTEMP, &data);
	if (ret)
		return ret;

	/* Convert LSB from 1degC to 3degC, store values from 25degC min */
	hist.maxtemp = ((s8)REG_HALF_HIGH(data) - 25) / 3;
	/* Convert LSB from 1degC to 3degC, store values from -20degC min */
	hist.mintemp = ((s8)REG_HALF_LOW(data) + 20) / 3;

	ret = REGMAP_READ(&chip->regmap, MAX1720X_MAXMINCURR, &data);
	if (ret)
		return ret;

	/* Convert LSB from 0.08A to 0.5A */
	hist.maxchgcurr = (s8)REG_HALF_HIGH(data) * 8 / 50;
	hist.maxdischgcurr = (s8)REG_HALF_LOW(data) * 8 / 50;

	memcpy(buff, &hist, sizeof(hist));
	return (size_t)sizeof(hist);
}

/*
 * The standard device call this with !data && !size && index=0 on start and
 * !data && !size && index<0 on stop. The call on start free and reload the
 * history from the gauge potentially increasing the number of entries (note
 * clients will not see that until they call start). On close the code just
 * release the allocated memory and entries: this is not a problem for cliets
 * that might be open because the data will be reloaded on next access.
 * This might create some churn but it's ok since we should not have more than
 * one client for this.
 */
static int max17x0x_storage_history_read(void *buff, size_t size, int index,
					 struct max1720x_chip *chip)
{
	struct max1720x_history *hi = &chip->history_storage;

	/* (!buff || !size) -> free the memory
	 *	if index == INVALID -> return 0
	 *	if index < 0 -> return -EIVAL
	 *	if index >= 0 -> re-read history
	 */
	if (!buff || !size) {
		max1720x_history_free(hi);
		if (index == GBMS_STORAGE_INDEX_INVALID)
			return 0;
	}

	if (index < 0)
		return -EINVAL;

	/* read history if needed */
	if (hi->history_count < 0) {
		int ret;

		ret = max1720x_history_read(chip, hi);
		if (ret < 0)
			return ret;
	}

	/* index == 0 is ok here */
	if (index >= hi->history_count)
		return -ENODATA;

	/* !buff, !size to read iterator count */
	if (!size || !buff)
		return hi->history_count;

	memcpy(buff, &hi->history[index * chip->history_page_size], size);
	return size;
}

static int max17x0x_storage_read_data(gbms_tag_t tag, void *buff, size_t size,
				      int index, void *ptr)
{
	int ret;
	struct max1720x_chip *chip = (struct max1720x_chip *)ptr;

	switch (tag) {
	case GBMS_TAG_HIST:
		/* short reads are invalid */
		if (size && size != chip->history_page_size * 2)
			return -EINVAL;

		mutex_lock(&chip->history_lock);
		ret = max17x0x_storage_history_read(buff, size, index, chip);
		mutex_unlock(&chip->history_lock);
		return ret;
	default:
		ret = -ENOENT;
		break;
	}

	return ret;
}

static int max17x0x_storage_iter(int index, gbms_tag_t *tag, void *ptr)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)ptr;
	static gbms_tag_t keys[] = {GBMS_TAG_SNUM, GBMS_TAG_BCNT,
				    GBMS_TAG_MXSN, GBMS_TAG_MXCN,
				    GBMS_TAG_RAVG, GBMS_TAG_RFCN,
				    GBMS_TAG_CMPC, GBMS_TAG_DXAC};
	const int count = ARRAY_SIZE(keys);


	if (index >= 0 && index < count) {
		*tag = keys[index];
	} else if (chip->history_available && index == count) {
		*tag = GBMS_TAG_HIST;
	} else {
		return -ENOENT;
	}

	return 0;
}

static int max17x0x_storage_read(gbms_tag_t tag, void *buff, size_t size,
				 void *ptr)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)ptr;
	const struct max17x0x_reg *reg;
	u16 data[32] = {0};
	int ret;

	switch (tag) {
	case GBMS_TAG_SNUM:
	case GBMS_TAG_MXSN:
		reg = max17x0x_find_by_tag(&chip->regmap_nvram,
					   MAX17X0X_TAG_SNUM);
		if (reg && reg->size > size)
			return -ERANGE;

		ret = max17x0x_reg_load(&chip->regmap_nvram, reg, &data);
		if (ret < 0)
			return ret;

		if (chip->gauge_type == MAX1730X_GAUGE_TYPE)
			ret = max1730x_decode_sn(buff, size, data);
		else if (chip->gauge_type == MAX1720X_GAUGE_TYPE)
			ret = max1720x_decode_sn(buff, size, data);
		break;

	case GBMS_TAG_BCNT:
	case GBMS_TAG_MXCN:
		reg = max17x0x_find_by_tag(&chip->regmap_nvram,
					   MAX17X0X_TAG_BCNT);
		if (reg && reg->size != size)
			return -ERANGE;
		ret = max17x0x_reg_load(&chip->regmap_nvram, reg, buff);
		if (ret == 0)
			ret = reg->size;
		break;

	/* RAVG: was POWER_SUPPLY_PROP_RESISTANCE_AVG, TODO: merge with EEPROM */
	case GBMS_TAG_RAVG:
		if (size != sizeof(u16))
			return -ERANGE;

		/* TODO(167639130) use tags */
		ret = batt_res_registers(chip, true, SEL_RES_AVG, (u16 *)buff);
		if (ret == -EINVAL)
			*(u16 *)buff = -1;
		return 0;

	/* RAVG: was POWER_SUPPLY_PROP_RES_FILTER_COUNT, TODO: merge with EEPROM */
	case GBMS_TAG_RFCN:
		if (size != sizeof(u16))
			return -ERANGE;

		/* TODO(167639130) use tags */
		ret = batt_res_registers(chip, true, SEL_RES_FILTER_COUNT,
					(u16 *)buff);
		if (ret == -EINVAL)
			*(u16 *)buff = -1;
		return 0;

	case GBMS_TAG_DXAC:
/*	MAX17201_DXACC_UPDATE_CNT = MAX1720X_NTALRTTH, */
	case GBMS_TAG_CMPC:
/*	MAX17201_COMP_UPDATE_CNT = MAX1720X_NVALRTTH, */
		reg = NULL;
		break;

	default:
		reg = NULL;
		break;
	}

	if (!reg)
		return -ENOENT;

	return ret;
}

static int max17x0x_storage_write(gbms_tag_t tag, const void *buff, size_t size,
				  void *ptr)
{
	int ret;
	const struct max17x0x_reg *reg;
	struct max1720x_chip *chip = (struct max1720x_chip *)ptr;

	switch (tag) {
	case GBMS_TAG_MXCN:
		reg = max17x0x_find_by_tag(&chip->regmap_nvram,
					   MAX17X0X_TAG_BCNT);
		if (reg && reg->size != size)
			return -ERANGE;
	break;

	/* RAVG: Was POWER_SUPPLY_PROP_RESISTANCE_AVG, TODO: merge with EEPROM */
	case GBMS_TAG_RAVG:
		if (size != sizeof(u16))
			return -ERANGE;
		return batt_res_registers(chip, false, SEL_RES_AVG,
					  (u16 *)buff);
	/* RAVG: Was POWER_SUPPLY_PROP_RES_FILTER_COUNT, TODO: merge with EEPROM */
	case GBMS_TAG_RFCN:
		if (size != sizeof(u16))
			return -ERANGE;
		return batt_res_registers(chip, false, SEL_RES_FILTER_COUNT,
					  (u16 *)buff);

	case GBMS_TAG_DXAC:
/*	MAX17201_DXACC_UPDATE_CNT = MAX1720X_NTALRTTH, */
	case GBMS_TAG_CMPC:
/*	MAX17201_COMP_UPDATE_CNT = MAX1720X_NVALRTTH, */
		reg = NULL;
		break;

	default:
		reg = NULL;
		break;
	}

	if (!reg)
		return -ENOENT;

	ret = max17x0x_reg_store(&chip->regmap_nvram, reg, buff);
	if (ret == 0)
		ret = reg->size;

	return ret;
}

/* when without eeprom */
static struct gbms_storage_desc max17x0x_storage_dsc = {
	.info = max17x0x_storage_info,
	.iter = max17x0x_storage_iter,
	.read = max17x0x_storage_read,
	.write = max17x0x_storage_write,
	.read_data = max17x0x_storage_read_data,
};

/* ------------------------------------------------------------------------- */

static int max17x0x_prop_iter(int index, gbms_tag_t *tag, void *ptr)
{
	static gbms_tag_t keys[] = {GBMS_TAG_CLHI};
	const int count = ARRAY_SIZE(keys);

	if (index >= 0 && index < count) {
		*tag = keys[index];
		return 0;
	}

	return -ENOENT;
}

static int max17x0x_prop_read(gbms_tag_t tag, void *buff, size_t size,
			      void *ptr)
{
	struct max1720x_chip *chip = (struct max1720x_chip *)ptr;
	int ret = -ENOENT;

	switch (tag) {
	case GBMS_TAG_CLHI:
		ret = max17x0x_collect_history_data(buff, size, chip);
		break;

	default:
		break;
	}

	return ret;
}

static struct gbms_storage_desc max17x0x_prop_dsc = {
	.iter = max17x0x_prop_iter,
	.read = max17x0x_prop_read,
};

/* ------------------------------------------------------------------------- */

/* this must be not blocking */
static void max17x0x_read_serial_number(struct max1720x_chip *chip)
{
	struct device_node *node = chip->dev->of_node;
	char buff[32] = {0};
	u32 sn_source = EEPROM_SN;
	int ret;

	ret = of_property_read_u32(node, "maxim,read-batt-sn", &sn_source);
	dev_info(chip->dev, "batt-sn source: %d (%d)\n", sn_source, ret);

	if (sn_source == EEPROM_SN)
		ret = gbms_storage_read(GBMS_TAG_MINF, buff, GBMS_MINF_LEN);
	else if (sn_source == MAX1720X_SN)
		ret = gbms_storage_read(GBMS_TAG_MXSN, buff, sizeof(chip->serial_number));
	else
		ret = gbms_storage_read(GBMS_TAG_SNUM, buff, sizeof(chip->serial_number));

	if (ret >= 0)
		strncpy(chip->serial_number, buff, ret);
	else
		chip->serial_number[0] = '\0';
}

static void max1720x_init_work(struct work_struct *work)
{
	struct max1720x_chip *chip = container_of(work, struct max1720x_chip,
						  init_work.work);
	int ret = 0;

	if (chip->gauge_type != -1) {

		/* TODO: move to max1720x1 */
		if (chip->regmap_nvram.regmap) {
			ret = gbms_storage_register(&max17x0x_storage_dsc,
						    "max1720x", chip);
			if (ret == -EBUSY)
				ret = 0;
		}

		/* these don't require nvm storage */
		ret = gbms_storage_register(&max17x0x_prop_dsc, "maxfg", chip);
		if (ret == -EBUSY)
			ret = 0;

		if (ret == 0)
			ret = max1720x_init_chip(chip);
		if (ret == -EPROBE_DEFER) {
			schedule_delayed_work(&chip->init_work,
				msecs_to_jiffies(MAX1720X_DELAY_INIT_MS));
			return;
		}
	}

	/* serial number might not be stored in the FG */
	max17x0x_read_serial_number(chip);

	mutex_init(&chip->cap_estimate.batt_ce_lock);
	chip->prev_charge_status = POWER_SUPPLY_STATUS_UNKNOWN;
	chip->fake_capacity = -EINVAL;
	chip->resume_complete = true;
	chip->init_complete = true;
	chip->bhi_acim = 0;

	/*
	 * Handle any IRQ that might have been set before init
	 * NOTE: will clear the POR bit and trigger model load if needed
	 */
	max1720x_fg_irq_thread_fn(-1, chip);

	max1720x_update_timer_base(chip);

	dev_info(chip->dev, "init_work done\n");
	if (chip->gauge_type == -1)
		return;

	/* Init History and Capacity Estimate only when gauge type is known. */
	ret = max1720x_init_history(chip);
	if (ret == 0)
		(void)max1720x_init_history_device(chip);

	ret = batt_ce_load_data(&chip->regmap_nvram, &chip->cap_estimate);
	if (ret == 0)
		batt_ce_dump_data(&chip->cap_estimate, chip->ce_log);
}

/* TODO: fix detection of 17301 for non samples looking at FW version too */
static int max17xxx_read_gauge_type(struct max1720x_chip *chip)
{
	u8 reg = MAX1720X_DEVNAME;
	struct i2c_msg xfer[2];
	uint8_t buf[2] = { };
	int ret, gauge_type;

	/* some maxim IF-PMIC corrupt reads w/o Rs b/152373060 */
	xfer[0].addr = chip->primary->addr;
	xfer[0].flags = 0;
	xfer[0].len = 1;
	xfer[0].buf = &reg;

	xfer[1].addr = chip->primary->addr;
	xfer[1].flags = I2C_M_RD;
	xfer[1].len = 2;
	xfer[1].buf = buf;

	ret = i2c_transfer(chip->primary->adapter, xfer, 2);
	if (ret != 2)
		return -EIO;

	/* it might need devname later */
	chip->devname = buf[1] << 8 | buf[0];
	dev_info(chip->dev, "chip devname:0x%X\n", chip->devname);

	ret = of_property_read_u32(chip->dev->of_node, "maxim,gauge-type",
				   &gauge_type);
	if (ret == 0) {
		dev_warn(chip->dev, "forced gauge type to %d\n", gauge_type);
		return gauge_type;
	}

	/* 0 not M5, !=0 M5 */
	ret = max_m5_check_devname(chip->devname);
	if (ret)
		return MAX_M5_GAUGE_TYPE;

	switch (chip->devname >> 4) {
	case 0x404: /* max1730x sample */
	case 0x405: /* max1730x pass2 silicon initial samples */
	case 0x406: /* max1730x pass2 silicon */
		gauge_type = MAX1730X_GAUGE_TYPE;
		break;
	default:
		break;
	}

	switch (chip->devname & 0x000F) {
	case 0x1: /* max17201 or max17211 */
	case 0x5: /* max17205 or max17215 */
	default:
		gauge_type = MAX1720X_GAUGE_TYPE;
		break;
	}

	return gauge_type;
}


/* NOTE: NEED TO COME BEFORE REGISTER ACCESS */
static int max17x0x_regmap_init(struct max1720x_chip *chip)
{
	int secondary_address = 0xb;
	struct device *dev = chip->dev;

	if (chip->gauge_type == MAX1730X_GAUGE_TYPE) {
		/* redefine primary for max1730x */
		chip->regmap.regmap = devm_regmap_init_i2c(chip->primary,
						&max1730x_regmap_cfg);
		if (IS_ERR(chip->regmap.regmap)) {
			dev_err(chip->dev, "Failed to re-initialize regmap (%ld)\n",
				IS_ERR_VALUE(chip->regmap.regmap));
			return -EINVAL;
		}

		/* shadow override is not supported on early samples */
		chip->shadow_override = (chip->devname >> 4) != 0x404;

		chip->regmap.regtags.max = ARRAY_SIZE(max1730x);
		chip->regmap.regtags.map = max1730x;
		chip->fixups_fn = max1730x_fixups;
	} else if (chip->gauge_type == MAX_M5_GAUGE_TYPE) {
		int ret;

		ret = max_m5_regmap_init(&chip->regmap, chip->primary);
		if (ret < 0) {
			dev_err(chip->dev, "Failed to re-initialize regmap (%ld)\n",
				IS_ERR_VALUE(chip->regmap.regmap));
			return -EINVAL;
		}

		chip->shadow_override = false;
		secondary_address = 0;
	} else if (chip->gauge_type == MAX1720X_GAUGE_TYPE) {

		chip->regmap.regmap = devm_regmap_init_i2c(chip->primary,
							&max1720x_regmap_cfg);
		if (IS_ERR(chip->regmap.regmap)) {
			dev_err(chip->dev, "Failed to initialize primary regmap (%ld)\n",
				IS_ERR_VALUE(chip->regmap.regmap));
			return -EINVAL;
		}

		/* max1720x is default map */
		chip->regmap.regtags.max = ARRAY_SIZE(max1720x);
		chip->regmap.regtags.map = max1720x;
	}

	/* todo read secondary address from DT */
	if (!secondary_address) {
		dev_warn(chip->dev, "Device 0x%x has no permanent storage\n",
			chip->devname);
		return 0;
	}

	chip->secondary = i2c_new_ancillary_device(chip->primary,
						   "nvram",
						   secondary_address);
	if (chip->secondary == NULL) {
		dev_err(dev, "Failed to initialize secondary i2c device\n");
		return -ENODEV;
	}

	i2c_set_clientdata(chip->secondary, chip);

	if (chip->gauge_type == MAX1730X_GAUGE_TYPE) {
		chip->regmap_nvram.regmap =
			devm_regmap_init_i2c(chip->secondary,
					     &max1730x_regmap_nvram_cfg);
		if (IS_ERR(chip->regmap_nvram.regmap)) {
			dev_err(chip->dev, "Failed to initialize nvram regmap (%ld)\n",
				PTR_ERR(chip->regmap_nvram.regmap));
			return -EINVAL;
		}

		chip->regmap_nvram.regtags.max = ARRAY_SIZE(max1730x);
		chip->regmap_nvram.regtags.map = max1730x;
	} else {
		chip->regmap_nvram.regmap =
			devm_regmap_init_i2c(chip->secondary,
					     &max1720x_regmap_nvram_cfg);
		if (IS_ERR(chip->regmap_nvram.regmap)) {
			dev_err(chip->dev, "Failed to initialize nvram regmap (%ld)\n",
				PTR_ERR(chip->regmap_nvram.regmap));
			return -EINVAL;
		}

		chip->regmap_nvram.regtags.max = ARRAY_SIZE(max1720x);
		chip->regmap_nvram.regtags.map = max1720x;
	}

	return 0;
}

static int max1720x_init_irq(struct max1720x_chip *chip)
{
	unsigned long irqf = IRQF_TRIGGER_LOW | IRQF_ONESHOT;
	int ret, irqno;

	chip->irq_shared = of_property_read_bool(chip->dev->of_node,
						 "maxim,irqf-shared");
	irqno = chip->primary->irq;
	if (!irqno) {
		int irq_gpio;

		irq_gpio = of_get_named_gpio(chip->dev->of_node,
					     "maxim,irq-gpio", 0);
		if (irq_gpio >= 0) {
			chip->primary->irq = gpio_to_irq(irq_gpio);
			if (chip->primary->irq <= 0) {
				chip->primary->irq = 0;
				dev_warn(chip->dev, "fg irq not avalaible\n");
				return 0;
			}
		}
	}

	if (chip->irq_shared)
		irqf |= IRQF_SHARED;

	ret = request_threaded_irq(chip->primary->irq, NULL,
				   max1720x_fg_irq_thread_fn, irqf,
				   MAX1720X_I2C_DRIVER_NAME, chip);
	dev_info(chip->dev, "FG irq handler registered at %d (%d)\n",
			    chip->primary->irq, ret);
	if (ret == 0)
		enable_irq_wake(chip->primary->irq);

	return ret;
}

/* possible race */
void *max1720x_get_model_data(struct i2c_client *client)
{
	struct max1720x_chip *chip = i2c_get_clientdata(client);

	return chip ? chip->model_data : NULL;
}


static int max1720x_init_fg_capture(struct max1720x_chip *chip)
{
	struct device *dev = &chip->psy->dev;
	int ret;

	/* Logging FG Learning */
	maxfg_init_fg_learn_capture_config(&chip->cb_lh.config,
					   &chip->regmap, &chip->regmap);
	ret = maxfg_alloc_capture_buf(&chip->cb_lh, MAX_FG_LEARN_PARAM_MAX_HIST);
	if (ret < 0)
		return -ENOMEM;

	ret = device_create_file(dev, &dev_attr_fg_learning_events);
	if (ret)
		dev_err(dev, "Failed to create fg_learning_params attribute\n");

	return ret;
}

static int max1720x_probe(struct i2c_client *client,
			  const struct i2c_device_id *id)
{
	struct max1720x_chip *chip;
	struct device *dev = &client->dev;
	struct power_supply_config psy_cfg = { };
	const struct max17x0x_reg *reg;
	const char *psy_name = NULL;
	char monitor_name[32];
	int ret = 0;
	u32 data32;

	chip = devm_kzalloc(dev, sizeof(*chip), GFP_KERNEL);
	if (!chip)
		return -ENOMEM;

	chip->dev = dev;
	chip->fake_battery = of_property_read_bool(dev->of_node, "maxim,no-battery") ? 0 : -1;
	chip->primary = client;
	chip->batt_id_defer_cnt = DEFAULT_BATTERY_ID_RETRIES;
	i2c_set_clientdata(client, chip);

	/* NOTE: < 0 not avalable, it could be a bare MLB */
	chip->gauge_type = max17xxx_read_gauge_type(chip);
	if (chip->gauge_type < 0)
		chip->gauge_type = -1;

	ret = of_property_read_u32(dev->of_node, "maxim,status-charge-threshold-ma",
				   &data32);
	if (ret == 0)
		chip->status_charge_threshold_ma = data32;
	else if (chip->gauge_type == MAX_M5_GAUGE_TYPE)
		chip->status_charge_threshold_ma = DEFAULT_STATUS_CHARGE_MA;
	else
		chip->status_charge_threshold_ma = 0;

	/* needs chip->primary and (optional) chip->secondary */
	ret = max17x0x_regmap_init(chip);
	if (ret < 0) {
		dev_err(dev, "Failed to initialize regmap(s)\n");
		goto i2c_unregister;
	}

	dev_warn(chip->dev, "device gauge_type: %d shadow_override=%d\n",
		 chip->gauge_type, chip->shadow_override);

	if (of_property_read_bool(dev->of_node, "maxim,log_writes")) {
		bool debug_reglog;

		debug_reglog = max17x0x_reglog_init(chip);
		dev_info(dev, "write log %savailable\n",
			 debug_reglog ? "" : "not ");
	}

	/* M5 requires zero IRQ */
	chip->zero_irq  = -1;
	if (chip->gauge_type == MAX_M5_GAUGE_TYPE)
		chip->zero_irq = 1;
	if (chip->zero_irq == -1)
		chip->zero_irq = of_property_read_bool(chip->dev->of_node,
						       "maxim,zero-irq");

	/* TODO: do not request the interrupt if the gauge is not present */
	ret = max1720x_init_irq(chip);
	if (ret < 0) {
		dev_err(dev, "cannot allocate irq\n");
		return ret;
	}

	psy_cfg.drv_data = chip;
	psy_cfg.of_node = chip->dev->of_node;

	ret = of_property_read_string(dev->of_node,
				      "maxim,dual-battery", &psy_name);
	if (ret == 0)
		chip->max1720x_psy_desc.name = devm_kstrdup(dev, psy_name, GFP_KERNEL);
	else
		chip->max1720x_psy_desc.name = "maxfg";

	dev_info(dev, "max1720x_psy_desc.name=%s\n", chip->max1720x_psy_desc.name);

	/* fuel gauge model needs to know the batt_id */
	mutex_init(&chip->model_lock);

	chip->get_prop_ws = wakeup_source_register(NULL, "GetProp");
	if (!chip->get_prop_ws)
		dev_info(chip->dev, "failed to register wakeup sources\n");

	chip->max1720x_psy_desc.type = POWER_SUPPLY_TYPE_BATTERY;
	chip->max1720x_psy_desc.get_property = max1720x_get_property;
	chip->max1720x_psy_desc.set_property = max1720x_set_property;
	chip->max1720x_psy_desc.property_is_writeable = max1720x_property_is_writeable;
	chip->max1720x_psy_desc.properties = max1720x_battery_props;
	chip->max1720x_psy_desc.num_properties = ARRAY_SIZE(max1720x_battery_props);

	if (of_property_read_bool(dev->of_node, "maxim,psy-type-unknown"))
		chip->max1720x_psy_desc.type = POWER_SUPPLY_TYPE_UNKNOWN;

	chip->psy = devm_power_supply_register(dev, &chip->max1720x_psy_desc,
					       &psy_cfg);
	if (IS_ERR(chip->psy)) {
		dev_err(dev, "Couldn't register as power supply\n");
		ret = PTR_ERR(chip->psy);
		goto irq_unregister;
	}

	ret = device_create_file(&chip->psy->dev, &dev_attr_offmode_charger);
	if (ret) {
		dev_err(dev, "Failed to create offmode_charger attribute\n");
		goto psy_unregister;
	}

	/* Was POWER_SUPPLY_PROP_RESISTANCE_ID */
	ret = device_create_file(&chip->psy->dev, &dev_attr_resistance_id);
	if (ret)
		dev_err(dev, "Failed to create resistance_id attribute\n");

	/* POWER_SUPPLY_PROP_RESISTANCE */
	ret = device_create_file(&chip->psy->dev, &dev_attr_resistance);
	if (ret)
		dev_err(dev, "Failed to create resistance attribute\n");

	/* Read GMSR */
	ret = device_create_file(&chip->psy->dev, &dev_attr_gmsr);
	if (ret)
		dev_err(dev, "Failed to create gmsr attribute\n");

	/* RC switch enable/disable */
	ret = device_create_file(&chip->psy->dev, &dev_attr_rc_switch_enable);
	if (ret)
		dev_err(dev, "Failed to create rc_switch_enable attribute\n");

	/*
	 * TODO:
	 *	POWER_SUPPLY_PROP_CHARGE_FULL_ESTIMATE -> GBMS_TAG_GCFE
	 *	POWER_SUPPLY_PROP_RES_FILTER_COUNT -> GBMS_TAG_RFCN
	 */

	/* M5 battery model needs batt_id and is setup during init() */
	chip->model_reload = MAX_M5_LOAD_MODEL_DISABLED;
	if (chip->gauge_type == MAX_M5_GAUGE_TYPE) {
		ret = device_create_file(&chip->psy->dev,
					 &dev_attr_m5_model_state);
		if (ret)
			dev_err(dev, "Failed to create model_state, ret=%d\n",
				ret);
	}

	chip->ce_log = logbuffer_register(chip->max1720x_psy_desc.name);
	if (IS_ERR(chip->ce_log)) {
		ret = PTR_ERR(chip->ce_log);
		dev_err(dev, "failed to obtain logbuffer, ret=%d\n", ret);
		chip->ce_log = NULL;
	}

	scnprintf(monitor_name, sizeof(monitor_name), "%s_%s",
		  chip->max1720x_psy_desc.name, "monitor");
	chip->monitor_log = logbuffer_register(monitor_name);
	if (IS_ERR(chip->monitor_log)) {
		ret = PTR_ERR(chip->monitor_log);
		dev_err(dev, "failed to obtain logbuffer, ret=%d\n", ret);
		chip->monitor_log = NULL;
	}

	ret = of_property_read_u32(dev->of_node, "google,bhi-fcn-count",
				   &chip->bhi_fcn_count);
	if (ret < 0)
		chip->bhi_fcn_count = BHI_CAP_FCN_COUNT;

	/* use VFSOC until it can confirm that FG Model is running */
	reg = max17x0x_find_by_tag(&chip->regmap, MAX17X0X_TAG_vfsoc);
	chip->reg_prop_capacity_raw = (reg) ? reg->reg : MAX1720X_REPSOC;

	max17x0x_init_sysfs(chip);
	max1720x_init_fg_capture(chip);

	INIT_DELAYED_WORK(&chip->cap_estimate.settle_timer,
			  batt_ce_capacityfiltered_work);
	INIT_DELAYED_WORK(&chip->init_work, max1720x_init_work);
	INIT_DELAYED_WORK(&chip->model_work, max1720x_model_work);
	INIT_DELAYED_WORK(&chip->rc_switch.switch_work, max1720x_rc_work);

	schedule_delayed_work(&chip->init_work, 0);

	return 0;

psy_unregister:
	power_supply_unregister(chip->psy);
irq_unregister:
	free_irq(chip->primary->irq, chip);
i2c_unregister:
	i2c_unregister_device(chip->secondary);

	return ret;
}

static int max1720x_remove(struct i2c_client *client)
{
	struct max1720x_chip *chip = i2c_get_clientdata(client);

	if (chip->ce_log) {
		logbuffer_unregister(chip->ce_log);
		chip->ce_log = NULL;
	}

	max1720x_cleanup_history(chip);
	max_m5_free_data(chip->model_data);
	cancel_delayed_work(&chip->init_work);
	cancel_delayed_work(&chip->model_work);
	cancel_delayed_work(&chip->rc_switch.switch_work);

	if (chip->primary->irq)
		free_irq(chip->primary->irq, chip);
	power_supply_unregister(chip->psy);

	if (chip->secondary)
		i2c_unregister_device(chip->secondary);


	maxfg_free_capture_buf(&chip->cb_lh);
	wakeup_source_unregister(chip->get_prop_ws);

	return 0;
}

static const struct of_device_id max1720x_of_match[] = {
	{ .compatible = "maxim,max1720x"},
	{ .compatible = "maxim,max77729f"},
	{ .compatible = "maxim,max77759"},
	{},
};
MODULE_DEVICE_TABLE(of, max1720x_of_match);

static const struct i2c_device_id max1720x_id[] = {
	{"max1720x", 0},
	{}
};
MODULE_DEVICE_TABLE(i2c, max1720x_id);

#ifdef CONFIG_PM_SLEEP
static int max1720x_pm_suspend(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct max1720x_chip *chip = i2c_get_clientdata(client);

	pm_runtime_get_sync(chip->dev);
	chip->resume_complete = false;
	pm_runtime_put_sync(chip->dev);

	return 0;
}

static int max1720x_pm_resume(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct max1720x_chip *chip = i2c_get_clientdata(client);

	pm_runtime_get_sync(chip->dev);
	chip->resume_complete = true;
	if (chip->irq_disabled) {
		enable_irq(chip->primary->irq);
		chip->irq_disabled = false;
	}
	pm_runtime_put_sync(chip->dev);

	return 0;
}
#endif

static const struct dev_pm_ops max1720x_pm_ops = {
	SET_NOIRQ_SYSTEM_SLEEP_PM_OPS(max1720x_pm_suspend, max1720x_pm_resume)
};

static struct i2c_driver max1720x_i2c_driver = {
	.driver = {
		   .name = "max1720x",
		   .of_match_table = max1720x_of_match,
		   .pm = &max1720x_pm_ops,
		   .probe_type = PROBE_PREFER_ASYNCHRONOUS,
		   },
	.id_table = max1720x_id,
	.probe = max1720x_probe,
	.remove = max1720x_remove,
};

module_i2c_driver(max1720x_i2c_driver);
MODULE_AUTHOR("Thierry Strudel <tstrudel@google.com>");
MODULE_AUTHOR("AleX Pelosi <apelosi@google.com>");
MODULE_DESCRIPTION("MAX17x01/MAX17x05 Fuel Gauge");
MODULE_LICENSE("GPL");